Android网络框架很多,但是基于Google自己的volley,无疑是优秀的一款。

网络框架,无外乎解决一下几个问题,队列,缓存,图片异步加载,统一的网络请求和处理等。

一.Volley 队列 启动

Volley的队列,首先我们看队列的启动:com.android.volley.toolbox.Volley.java

 /**
     * 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) {
        }

        if (stack == null) {
            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 = new BasicNetwork(stack);

        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();

        return queue;
    }

我们依次分析这个方法。这个方法是队列启动的代码。

开始就是获取缓存文件夹,以及userAgent 一些信息。

Build.VERSION.SDK_INT >= 9

会使用HTTPURLConnection作为网络请求,而老的版本就使用httpclient来处理。

关于这2者的区别,很多地方有介绍。HttpUrlConnection是HttpClient轻量级版本。

应该说性能更好,并且足够android平台使用了。

当然,也可以使用自己定义的HttpStack。

Network network = new BasicNetwork(stack);

Network对stack的进一步封装,然后创建队列和启动队列。

com/android/volley/RequestQueue.java:

    /**
     * Starts the dispatchers in this queue.
     */
    public void start() {
        stop();  // Make sure any currently running dispatchers are stopped.
        // Create the cache dispatcher and start it.
        mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
        mCacheDispatcher.start();

        // Create network dispatchers (and corresponding threads) up to the pool size.
        for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }

启动队列,就是启动了一条cache thread 和4个 network thread。

然后分析CacheDispatcher 和NetworkDispatcher 这两个东东。

 

二:NetworkDispatcher

这一节我们分析网络请求,所以就忽略cache的部分,将在下一节分析:

public class NetworkDispatcher extends Thread

NetworkDispatcher是一个thread,可见network请求应该是从requestQueue队列中获取数据以后,已while(true)的形式不断的向服务器请求,

当requestQueue 为空时,线程讲block住,直到队列有数据,或者线程推出为止。

com/android/volley/NetworkDispatcher.java:

@Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            Request<?> request;
            try {
                // Take a request from the queue.
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }

            try {
                request.addMarker("network-queue-take");

                // If the request was cancelled already, do not perform the
                // network request.
                if (request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                    continue;
                }

                addTrafficStatsTag(request);

                // Perform the network request.
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");

                // If the server returned 304 AND we delivered a response already,
                // we're done -- don't deliver a second identical response.
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish("not-modified");
                    continue;
                }

                // Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");

                // Write to cache if applicable.
                // TODO: Only update cache metadata instead of entire record for 304s.
                if (request.shouldCache() && response.cacheEntry != null) {
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }

                // Post the response back.
                request.markDelivered();
                mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                VolleyError volleyError = new VolleyError(e);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                mDelivery.postError(request, volleyError);
            }
        }
    }
run

相关文章:

  • 2021-10-31
  • 2021-05-22
  • 2021-05-27
  • 2022-03-08
  • 2021-07-04
  • 2022-02-20
  • 2021-05-16
  • 2021-12-12
猜你喜欢
  • 2021-10-02
  • 2021-04-22
  • 2022-12-23
  • 2021-07-02
  • 2021-10-08
  • 2022-12-23
相关资源
相似解决方案