Android Volley 和 AsyncTask
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20675072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Volley and AsyncTask
提问by pmb
I read a post about Volley and I know it's great networking library. But I couldn't understand one thing.
我读过一篇关于 Volley 的文章,我知道它是一个很棒的网络库。但我无法理解一件事。
All requests are Async Task or not?
所有请求是否都是异步任务?
When I want to send asyncTask request using Volley do I need put Volley request in AsyncTask? or should I just call Volley Request if it is already AsyncTask request?
当我想使用 Volley 发送 asyncTask 请求时,是否需要将 Volley 请求放在 AsyncTask 中?或者如果它已经是 AsyncTask 请求,我应该只调用 Volley Request 吗?
private class MyClass extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// do Volley request
}
}
Is this right approach?
这是正确的方法吗?
回答by Gru
You don't need to run Volley request on AsyncTask.
您不需要在 AsyncTask 上运行 Volley 请求。
Why:
为什么:
They manage all network related task on separate thread. If you look closely at library project they did not picture the AsyncTask. But they intelligently handle all network related task efficiently.
他们在单独的线程上管理所有与网络相关的任务。如果您仔细查看库项目,他们并没有描绘出 AsyncTask。但他们智能高效地处理所有与网络相关的任务。
Check RequestQueue.javaclass in Volley's main package
检查Volley 主包中的RequestQueue.java类
here I am pasting java doc.
我在这里粘贴 java 文档。
/**
* A request dispatch queue with a thread pool of dispatchers.
*
* Calling {@link #add(Request)} will enqueue the given Request for dispatch,
* resolving from either cache or network on a worker thread, and then delivering
* a parsed response on the main thread.
*/
Edited:
编辑:
Forming a Request:
形成请求:
With Volley, network communication is managed by the RequestQueue. The best way to utilize the RequestQueue and all of its tools, especially the cache, is by instantiating it once and keeping it around as a singleton. At this point you can then add or cancel requests, stop or start requests, and access the response cache(s).
使用 Volley,网络通信由 RequestQueue 管理。利用 RequestQueue 及其所有工具(尤其是缓存)的最佳方法是将其实例化一次并将其作为单例保留。此时,您可以添加或取消请求、停止或启动请求以及访问响应缓存。
RequestQueue queue =Volley.newRequestQueue(this);
Once the RequestQueue has been instantiated a request must be formed. This can be done utilizing a few different “out of the box” request classes included with the Volley Library or by extending Volley's request class into your own custom request. The request classes already included in Volley are a String request, JSON requests, and an Image Request. Most of the request classes included in Volley library utilize constructors much like the one below.
一旦 RequestQueue 被实例化,就必须形成一个请求。这可以通过使用 Volley 库中包含的几个不同的“开箱即用”请求类或通过将 Volley 的请求类扩展到您自己的自定义请求中来完成。Volley 中已经包含的请求类是字符串请求、JSON 请求和图像请求。Volley 库中包含的大多数请求类都使用与下面类似的构造函数。
Parameters being passed into constructor:
传递给构造函数的参数:
RequestMethod(get, post, delete, ect)JSONObject-An optional object that will be posted with your request ResponseListener- Where your data will go after the request is complete ErrorListener– What will be told when there was a problem with your request.
RequestMethod(get, post, delete, ect) JSONObject- 将与您的请求一起发布的可选对象 ResponseListener- 请求完成后您的数据将去哪里 ErrorListener- 当您的请求出现问题时会被告知什么。
JsonObjectRequest request = JsonObjectRequest(Requestmethod, url, null, new ResponseListener(), new ErrorListener());
Listners to receive response:
接收响应的监听器:
Successful Response Listener
成功响应监听器
private class ResponseListener implements Response.Listener{
@Override
public void onResponse(JSONObject response){
}
}
Error Response Listener
错误响应监听器
private class ErrorListener implements Response.ErrorListener{
@Override
public void onErrorResponse(VolleyError error){
}
}
Finally add your request to Request queue, rest of everything Volley will handle for you.
最后将您的请求添加到请求队列,Volley 将为您处理其余的一切。
Making call:
拨打电话:
Now, that we have made our request and response classes we are ready to add the request to the queue and retrieve the data. To do so we simply add the request to the queue.
现在,我们已经创建了请求和响应类,我们准备将请求添加到队列并检索数据。为此,我们只需将请求添加到队列中。
queue.add(request);
The response or error will then be delivered to the response/error classes that we defined in our request. You can add as many requests to the queue that you would like at one time and the responses will be delivered to their respective response/error classes
然后响应或错误将被传递到我们在请求中定义的响应/错误类。您可以一次将任意数量的请求添加到队列中,并且响应将被传送到它们各自的响应/错误类
回答by Toon Borgers
When you use Volley, there's no need to combine it with AsyncTask
. It does the networking stuff on another thread for you.
使用 Volley 时,无需将其与AsyncTask
. 它在另一个线程上为您处理网络问题。
Hereis a basic example of a network call using Volley. As you can see, all the code is just in the Activity
, without any need to define an AsyncTask
.
下面是一个使用 Volley 进行网络调用的基本示例。正如你所看到的,所有的代码只是在Activity
,而无需定义AsyncTask
。
回答by Chinmai KH
Volley cannot be inserted inside AsyncTask because,
Volley 不能插入到 AsyncTask 中,因为,
Volley is initiating background thread(s) on its own so all the network requests are executed off the UI thread so primarily you don't need to extend AsyncTask anymore. Of course you will have to take care to cancel the running requests on rotation or when user exits your activity.. As Volley is mainly used for minor Networking purposes in Android (for major use DownloadManager). It does similar working of AsyncTask Class. Implement Singleton in Volley. Images can also be sent in Volley.
Volley 自己启动后台线程,因此所有网络请求都在 UI 线程之外执行,因此主要您不再需要扩展 AsyncTask。当然,您必须注意在轮换或用户退出活动时取消正在运行的请求。因为 Volley 主要用于 Android 中的次要网络目的(主要用于 DownloadManager)。它执行 AsyncTask 类的类似工作。在 Volley 中实现 Singleton。图像也可以在 Volley 中发送。
回答by IrshadKumail
The whole point of introducing Volley library was to make sure user doesnt have to worry about all the "obvious" stuff while sending a network request. This means that volley takes care of the following on its own
引入 Volley 库的重点是确保用户在发送网络请求时不必担心所有“明显”的东西。这意味着 volley 会自行处理以下事项
- Switching Background thread
- Transparent disk and memory response
- Multiple concurrent network connections. etc
- 切换后台线程
- 透明磁盘和内存响应
- 多个并发网络连接。等等
To answer your question- You don't need to worry about switching to background thread, Volley takes care of this on its own. Also once the request is completed the success or failure callback is invoked on the main thread.Hence with Volley developer need not worry about switching threads
回答您的问题 -您无需担心切换到后台线程,Volley 会自行处理。同样,一旦请求完成,在主线程上调用成功或失败回调。因此与 Volley 开发人员不必担心切换线程
This tutorial heregives a good step by step explanation of Working with Volley Library
本教程在这里提供了使用 Volley 库的良好分步说明