我使用单例RequestQueue
对Volley请求进行排队。我在我的活动的onStop
中添加了取消方法,该方法会停止请求。但是当我将取消的请求添加到队列中进行重试时,它不起作用。这是代码:
我的活动课程:
public class MainActivity extends Activity {
private int requestId;
protected Request previousRequest;
private RequestQueueSingleton requestQueueSingleton;
@Override
public void onStart() {
super.onStart();
if(previousRequest != null && previousRequest.isCancelled) {
requestQueueSingleton.add(previousRequest);
}
}
@Override
public void onStop() {
super.onStop();
requestQueueSingleton.cancelRequests(requestId);
}
}
请求单身人士:
public class RequestQueueSingleton {
private static RequestQueueSingleton instance;
private RequestQueue requestQueue;
public static RequestQueueSingleton getInstance(Context context) {
if (instance == null) {
instance = new RequestQueueSingleton(context);
}
return instance;
}
private RequestQueueSingleton(Context context) {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
}
public void addToQueue(Request request) {
requestQueue.add(request);
}
public void cancelRequests(int tag) {
requestQueue.cancelAll(tag);
}
}
请注意,一切都正常运行,不会发生崩溃。它就在应用程序进入后台并返回时,响应无法传递。有什么我想念的吗?
提前致谢。
答案 0 :(得分:0)
@Override
public void onPause() {
RequestQueueSingleton.getInstance(context).cancelRequests(requestId);
super.onPause();
}
在致电super.onPause();
点击此链接https://developer.android.com/guide/components/activities.html#SavingActivityState 我对答案的支持。