Volley源码解析(一)

来源:互联网 发布:java编程的发展方向 编辑:程序博客网 时间:2024/05/16 17:11

      • volley的使用方式
      • volley类分析

volley的使用方式

//创建一个队列RequestQueue requestQueue = Volley.newRequestQueue(this);String url="http://www.baidu.com";//一个最简单的请求,//参数1:url//参数2:请求成功回调//参数3:错误回调StringRequest request = new StringRequest(url,    new Response.Listener<String>() {        @Override        public void onResponse(String response) {            //do something        }    },    new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError error) {             //do something        }    });//将请求添加到队列requestQueue.add(request);

volley类分析

先看volley源码,注释写在源码上

public class Volley {    /** Default on-disk cache directory. */    private static final String DEFAULT_CACHE_DIR = "volley";    /**     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.     *     * @param context A {@link Context} to use for creating the cache dir.     * @param stack An {@link HttpStack} to use for the network, or null for default.     * @return A started {@link RequestQueue} instance.     */    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);        String userAgent = "volley/0";        try {            String packageName = context.getPackageName();            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);            userAgent = packageName + "/" + info.versionCode;        } catch (NameNotFoundException e) {        }        //判断如果stack==null,使用volley默认的,否则使用自定义的stack        if (stack == null) {            //判断如果版本>=9,使用HttpURLConnection,否则使用HttpClient            if (Build.VERSION.SDK_INT >= 9) {                stack = new HurlStack();            } else {                // Prior to Gingerbread, HttpUrlConnection was unreliable.                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));            }        }        //创建network         Network network = new BasicNetwork(stack);        //创建queue         RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);        queue.start();        return queue;    }    /**     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.     *     * @param context A {@link Context} to use for creating the cache dir.     * @return A started {@link RequestQueue} instance.     */    public static RequestQueue newRequestQueue(Context context) {        return newRequestQueue(context, null);    }}
0 0
原创粉丝点击