0

我使用单例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);
    }

}

请注意,一切都在相应地工作,没有发生崩溃。就在应用程序进入后台并返回时,未传递响应。有什么我想念的吗?

提前致谢。

4

1 回答 1

0
@Override
    public void onPause() {
        RequestQueueSingleton.getInstance(context).cancelRequests(requestId);
        super.onPause();
    }

在调用之前使用取消所有请求super.onPause();

检查此链接https://developer.android.com/guide/components/activities.html#SavingActivityState 以获得我对答案的支持。

于 2016-11-28T11:02:04.130 回答