为什么强迫 Runnable 成为一个不被设计的东西? 只需拥有自己的界面即可拥有所需的签名。 例如。
Runnable
public interface Callback<T> { void run(T parameter); } public void startRequest(RequestOperation operation, final Callback<JSONObject> onSuccess, final Callback<VolleyError> onError, final Runnable onFinished) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, instance_context.getResources().getString(R.string.base_url), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { onSuccess.run(response); onFinished.run(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { onError.run(error); onFinished.run(); } }); queue.add(request); }
甚至更好(如果你问我):
public interface Callback { void onSucces(JSONObject response); void onError(VolleyError error); void onFinished(); } public void startRequest(RequestOperation operation, final Callback callback) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, instance_context.getResources().getString(R.string.base_url), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { callback.onSuccess(response); callback.onFinished(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(error); callback.onFinished(); } }); queue.add(request); }
你也可以 Callback 再次通用,如果你需要:
Callback
public interface Callback<R, E> { void onSucces(R response); void onError(E error); void onFinished(); } public void startRequest(RequestOperation operation, final Callback<JSONObject, VolleyError> callback) {...}
使用:
public class SimpleCallback implements Callback { public void onSucces(JSONObject response) { doSomethingWithResponse(response); } public void onError(VolleyError error) { doSomethingWithError(error); } void onFinished() { logFinishTime(); } } startRequest(operation, new SimpleCallback());