我正在开发一个完全依赖RESTful API的Android应用程序。几乎每个应用程序屏幕都在进行网络呼叫。我使用以下帮助程序类来进行网络请求。
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class RequestHandler {
private final String deviceID;
private RequestQueue queue;
private StringRequest stringRequest;
private NetworkRequestListener networkRequestListener;
private NetworkResponseListener networkResponseListener;
private SharedPreferences sharedPreferences;
public RequestHandler(Context context) {
queue = Volley.newRequestQueue(context);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
deviceID = UtilityMethods.getDeviceId(context);
}
public void makeNetworkRequest(String url, int method, final String body) {
stringRequest = new StringRequest(method, appendedURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
if (networkResponseListener != null) {
networkResponseListener.onResponseLoaded(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (networkResponseListener != null) {
networkResponseListener.onResponseFailed(error);
}
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() {
try {
return body.getBytes("utf-8");
} catch (UnsupportedEncodingException | NullPointerException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", body, "utf-8");
return null;
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("version", AppConstants.VERSION);
headers.put("Content-Type", "application/json");
return headers;
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
String response = UtilityMethods.networkResponseToString(networkResponse);
networkResponseListener.onResponseReceived(response);
return super.parseNetworkResponse(networkResponse);
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
if (networkRequestListener != null) {
networkRequestListener.beforeMakeRequest(stringRequest);
}
queue.add(stringRequest);
}
public void setNetworkResponseListener(NetworkResponseListener networkResponseListener) {
this.networkResponseListener = networkResponseListener;
}
public void setNetworkRequestListener(NetworkRequestListener networkRequestListener) {
this.networkRequestListener = networkRequestListener;
}
public RequestQueue getQueue() {
return queue;
}
public StringRequest getStringRequest() {
return stringRequest;
}
}
现在问题是,我不知道取消网络请求的方法(将回调接口设置为null也不起作用)。如果来自网络调用的响应在活动被销毁之后出现,则处理程序方法因为上下文为null或视图而抛出NPE(尽管活动被破坏,代码仍然被执行)。在销毁活动时是否有可能取消/忽略网络响应?此外,如果由于此类几乎每个活动都有内存泄漏,可以改进此实现。
答案 0 :(得分:0)
像这样在这个类中创建一个方法
public static final String TAG = "MyTag";
StringRequest stringRequest; // Assume this exists.
RequestQueue queue; // Assume this exists.
// Set the tag on the request.
stringRequest.setTag(TAG);
// Add the request to the RequestQueue.
queue.add(stringRequest);
public void cancelTag() {
return queue.cancelAll(TAG);;
}
在活动onStop()
中调用此CancelTag()