Transmitting Network Data Using Volley - Setting Up a RequestQueue
2015-03-01 11:57
411 查看
The previous lesson showed you how to use the convenience method
taking advantage of Volley's default behaviors. This lesson walks you through the explicit steps of creating a
This lesson also describes the recommended practice of creating a
the lifetime of your app.
A
implementations of these available in the Volley toolbox:
a network transport based on your choice of
be initialized with the HTTP client your app is using to connect to the network. Typically this is
Use
apps targeting Android API levels lower than API Level 9 (Gingerbread). Prior to Gingerbread,
unreliable. For more discussion of this topic, see Android's HTTP Clients.
Use
apps targeting Android API Level 9 (Gingerbread) and higher.
To create an app that runs on all versions of Android, you can check the version of Android the device is running and choose the appropriate HTTP client, for example:
This snippet shows you the steps involved in setting up a
If you just need to make a one-time request and don't want to leave the thread pool around, you can create the
it and call
described in Sending a Simple Request. But the more common use case is to create the
a singleton to keep it running for the lifetime of your app, as described in the next section.
If your application makes constant use of the network, it's probably most efficient to set up a single instance of
last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates
Another approach is to subclass
set up the
But this approach is discouraged; a static singleton can provide the same functionality in a more modular
way.
A key concept is that the
not an
that the
Here is an example of a singleton class that provides
Here are some examples of performing
NEXT: MAKING A STANDARD REQUEST
Volley.newRequestQueueto set up a
RequestQueue,
taking advantage of Volley's default behaviors. This lesson walks you through the explicit steps of creating a
RequestQueue, to allow you to supply your own custom behavior.
This lesson also describes the recommended practice of creating a
RequestQueueas a singleton, which makes the
RequestQueuelast
the lifetime of your app.
Set Up a Network and Cache
A RequestQueueneeds two things to do its job: a network to perform transport of the requests, and a cache to handle caching. There are standard
implementations of these available in the Volley toolbox:
DiskBasedCacheprovides a one-file-per-response cache with an in-memory index, and
BasicNetworkprovides
a network transport based on your choice of
AndroidHttpClientor
HttpURLConnection.
BasicNetworkis Volley's default network implementation. A
BasicNetworkmust
be initialized with the HTTP client your app is using to connect to the network. Typically this is
AndroidHttpClientor
HttpURLConnection:
Use
AndroidHttpClientfor
apps targeting Android API levels lower than API Level 9 (Gingerbread). Prior to Gingerbread,
HttpURLConnectionwas
unreliable. For more discussion of this topic, see Android's HTTP Clients.
Use
HttpURLConnectionfor
apps targeting Android API Level 9 (Gingerbread) and higher.
To create an app that runs on all versions of Android, you can check the version of Android the device is running and choose the appropriate HTTP client, for example:
HttpStack stack; ... // If the device is running a version >= Gingerbread... if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { // ...use HttpURLConnection for stack. } else { // ...use AndroidHttpClient for stack. } Network network = new BasicNetwork(stack);
This snippet shows you the steps involved in setting up a
RequestQueue:
RequestQueue mRequestQueue; // Instantiate the cache Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap // Set up the network to use HttpURLConnection as the HTTP client. Network network = new BasicNetwork(new HurlStack()); // Instantiate the RequestQueue with the cache and network. mRequestQueue = new RequestQueue(cache, network); // Start the queue mRequestQueue.start(); String url ="http://www.myurl.com"; // Formulate the request and handle the response. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Do something with the response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error } }); // Add the request to the RequestQueue. mRequestQueue.add(stringRequest); ...
If you just need to make a one-time request and don't want to leave the thread pool around, you can create the
RequestQueuewherever you need
it and call
stop()on the
RequestQueueonce your response or error has come back, using the
Volley.newRequestQueue()method
described in Sending a Simple Request. But the more common use case is to create the
RequestQueueas
a singleton to keep it running for the lifetime of your app, as described in the next section.
Use a Singleton Pattern
If your application makes constant use of the network, it's probably most efficient to set up a single instance ofRequestQueuethat will
last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates
RequestQueueand other Volley functionality.
Another approach is to subclass
Applicationand
set up the
RequestQueuein
Application.onCreate().
But this approach is discouraged; a static singleton can provide the same functionality in a more modular
way.
A key concept is that the
RequestQueuemust be instantiated with the
Applicationcontext,
not an
Activitycontext. This ensures
that the
RequestQueuewill last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
Here is an example of a singleton class that provides
RequestQueueand
ImageLoaderfunctionality:
private static MySingleton mInstance; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private static Context mCtx; private MySingleton(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } public static synchronized MySingleton getInstance(Context context) { if (mInstance == null) { mInstance = new MySingleton(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } public ImageLoader getImageLoader() { return mImageLoader; } }
Here are some examples of performing
RequestQueueoperations using the singleton class:
// Get a RequestQueue RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()). getRequestQueue(); ... // Add a request (in this example, called stringRequest) to your RequestQueue. MySingleton.getInstance(this).addToRequestQueue(stringRequest);
NEXT: MAKING A STANDARD REQUEST
相关文章推荐
- Transmitting Network Data Using Volley -Making a Standard Request
- Transmitting Network Data Using Volley -Implementing a Custom Request
- Transmitting Network Data Using Volley 之Sending a Simple Request
- Transmitting Network Data Using Volley - Sending a Simple Request
- Android训练课程(Android Training) - 使用Volley传输网络数据(Transmitting Network Data Using Volley)
- Transmitting Network Data Using Volley - Volley is an HTTP library that makes networking for Android
- Transmitting Network Data Using Volley
- Transmitting Network Data Using Volley
- volley建立请求队列(Setting Up a RequestQueue)
- Android训练课程(Android Training) - 使用Volley传输网络数据(Transmitting Network Data Using Volley)
- 跟Google 学代码:Transmitting Network Data Using Volley
- Transmitting Network Data Using Volley(使用Volley框架传输网络数据)
- Android开发训练之第五章第七节——Transmitting Network Data Using Volley
- Setting up and using the Rational Data Architect - Rational ClearCase integration
- Setting Up a RequestQueue
- Volley之RequestQueue
- Android中关于Volley的使用(五)从RequestQueue开始来深入认识Volley
- 17.1.1.8?Setting Up Replication with Existing Data设置复制使用存在的数据
- Fast convolutional neural network training using selective data sampling: Application to hemorrhage
- Android中关于Volley的使用(五)从RequestQueue开始来深入认识Volley