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

文章摘要
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 RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
    getRequestQueue();

// ...

// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hailushijie

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值