3、volley 官方教程-建立一个请求队列

来源:互联网 发布:精密减速机 知乎 编辑:程序博客网 时间:2024/06/05 06:43

文章摘要
1、volley 网络请求队列和缓冲请求队列
2、volley 单例模式


英文文献

一、设定网络请求队列和缓冲请求队列

RequestQueue需要两件事来做它的工作:
- 一个网络来执行请求的传输
- 一个缓存来处理缓存。

在Volley toolbox中有这些可用的标准实现:DiskBasedCache为每一个文件提供了具有内存索引的响应缓存,BasicNetwork根据您首选的HTTP客户端提供网络传输。

BasicNetwork是Volley的默认网络实现,BasicNetwork必须使用HTTP client来完成初始化,通常是HttpURLConnection。

此代码段显示了设置RequestQueue所涉及的步骤:

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        final TextView mTextView = (TextView) findViewById(R.id.text);        RequestQueue mRequestQueue;        // Instantiate the cache 1、初始化Cache        Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap        // Set up the network to use HttpURLConnection as the HTTP client.        //2、建立网络连接        Network network = new BasicNetwork(new HurlStack());        // Instantiate the RequestQueue with the cache and network.        //3、构建初始化RequestQueue        mRequestQueue = new RequestQueue(cache, network);        // Start the queue        //4、启动RequestQueue        mRequestQueue.start();        String url = "http://www.example.com";        // Formulate the request and handle the response.        //5、初始化并构建Request        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,                new Response.Listener<String>() {                    @Override                    public void onResponse(String response) {                        // Do something with the response                        mTextView.setText("Response is: " + response.substring(0, 500));                        Log.d("hlwang","CreateRequestQueue onResponse response is:"+response);                    }                },                new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                        // Handle error                        Log.d("hlwang","CreateRequestQueue onErrorResponse error is:"+error);                    }                });        // Add the request to the RequestQueue.        //6、将Request加入队列        mRequestQueue.add(stringRequest);    }

如果您只需要一次性请求,并且不想离开线程池,则可以在需要的地方创建RequestQueue,并在响应或错误返回后调用stop Queue,就像“在发送简单请求”中提到的Volley.newRequestQueue()方法。

但是更常见的用例是将RequestQueue创建为单例模式对象,以保持其在应用程序生命周期中运行:

二、使用Singleton模式

如果您的应用程序不断使用网络,可能最有效的方法是设置一个可以延长应用程序生命周期的RequestQueue实例。

要达到这种目标,有各种方式可以实现。 推荐的方法是实现封装RequestQueue和其他Volley功能的单例类。 另一种方法是在Application.onCreate()中继承Application并设置RequestQueue, 但这种做法是不鼓励的, 静态单例可以以更模块化的方式提供相同的功能。

一个关键的概念是RequestQueue必须用Application context而不是Activity context来实例化。 这样可以确保RequestQueue在您的应用程序生命周期中持续存在,而不是每次重新创建Activity时重新创建(例如,当用户旋转设备时)。

下面是一个提供RequestQueue和ImageLoader功能的单例类的例子:

package hailouwang.demosforapi.volley;import android.content.Context;import android.graphics.Bitmap;import android.util.LruCache;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.Volley;/** * Created by ifei on 2017/7/26. */public class MySingleton {    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;    }}

下面是执行的一些例子RequestQueue使用单例类的操作:

// Get a RequestQueueRequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).    getRequestQueue();// ...// Add a request (in this example, called stringRequest) to your RequestQueue.MySingleton.getInstance(this).addToRequestQueue(stringRequest);

关注我的技术公众号,查看更多优质技术文章推送

微信扫一扫下方二维码即可关注:

关注我的技术公众号,查看更多优质技术文章推送

原创粉丝点击