Android - 取消 Volley 请求

Android - cancel Volley request

我在我的项目中使用 Android Volley 库来执行网络请求,一切正常,但我在使用此库的 "cancel" 功能时遇到了一些问题。我解释一下我的问题..

我有一个 activity,我在 OnCreate 方法中执行请求,请求被调用,没问题。但是为了确保 cancel 方法有效,我想测试并尝试两件事:

  1. 我发出请求,然后像这样取消它:

    MySingleton.getMyData("urltocall", getDataListener, requestTag); MySingleton.getRequestQueue().cancelAll(requestTag);

这个有效!调用取消(我也可以在 Volley 的请求 class 中看到它):

public void cancel() {
        mCanceled = true; // my breakpoint is called here
    }
  1. 我触发了我的请求,并在调用 activity 的 finish() 方法之后和 onDestroy and/or onStop 方法中 activity,我正在调用相同的代码:

    MySingleton.getMyData("urltocall", getDataListener, requestTag); MySingleton.getRequestQueue().cancelAll(requestTag);

但这行不通

requestTag 不为空并且很好地传递给了 Volley,所以我不明白为什么第一种方法有效而另一种方法无效...知道我的目的是在 onDestroy 时取消请求叫..

感谢您的帮助

我的猜测是,在第一种情况下,请求仅被添加到 RequestQueue,这就是调用 cancelAll() 有效的原因。在第二种情况下,在开始请求和 pausing/destroying 和 Activity 之间有轻微的延迟:在那个延迟中,HTTP 请求已经开始。您可能不知道调用 cancelAll() 仅适用于仍在 RequestQueue 中的那些请求。它不适用于已经开始的 HTTP 请求,无法停止。

话虽如此,文档 here 暗示一旦请求被取消(即通过调用 cancel()),它可以有效地被视为从未在第一名。不会调用与特定请求关联的回调(尽管收到的响应可能保存在本地缓存中)。

我建议你在onPause()方法中取消添加的请求。考虑:

onPause() The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back). source: Android Developers

https://developer.android.com/training/volley/simple.html#cancel

这基本上是说

Once cancelled, Volley guarantees that your response handler will never be called.

所以即使没有办法 undo/cancel 已经开始的 http 请求(这是有道理的),与请求关联的回调也不会被调用,这对我来说有效地意味着我可以处理在大多数情况下是一个取消的请求,即使这样静默接收的响应可能在缓存中可用。

您可以取消附加到 TAGRequest。所以基本上你必须为每个 Request.

添加一个标签

yourRequestObject.setTag(TAG);

RequestQueue mRequestQueue;

mRequestQueue.cancelAll(TAG);

这样你就可以用特定的 TAG.

取消所有 Request