編輯:關於Android編程
使用Volley很簡單,過程分為兩步:
1. 建立請求隊列RequestQueue queue = new Volley.newRequestQueue()
2. 新建請求XXRequest,然後將請求加入隊列queue中:queue.add(XXRequest);
一、Volley.newRequestQueue()
新建queue之後只要將各類請求放入該隊列即可,系統會自動對其進行處理。現在先看一下Volley.newRequestQueue做了些什麼:
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; }
該函數中的核心代碼為:
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start();
newRequestQueue中的兩個參數分別用於處理緩存請求和網絡請求。這個一會再講。先看後面一句~queue.start();
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(); } }
從代碼中可看到,queue.start()的執行開啟了其中的mCacheDispatcher和networkDispatcher,也就是負責處理Cache請求及Network請求的線程。
綜上,Volley.newRequestQueue新建了一個請求隊列,並開啟了處理緩存請求的線程mCacheDispatcher和處理網絡請求的線程networkDispatcher。
二、NetworkDispatcher& CacheDispatcher
NetworkDispatcher用於處理網絡請求。其構造函數為:
public NetworkDispatcher(BlockingQueuequeue, Network network, Cache cache, ResponseDelivery delivery) { mQueue = queue; mNetwork = network; mCache = cache; mDelivery = delivery; }
現在再回過頭看RequestQueue的start函數,其中有~RequestQueue.java/start():
NetworkDispatchernetworkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,mCache,mDelivery);
這裡的mNetworkQueue 是RequestQueue中定義&分配的~RequestQueue.java:
private final PriorityBlockingQueuemNetworkQueue = new PriorityBlockingQueue ();
這個由Request組成的BlockingQueue用於存放網絡Request。(RequestQueue中還聲明&定義了一個mCacheQueue,和mNetworkQueue類似,用於存放緩存請求)
現在看下NetworkDispatcher的run函數中執行的功能:
public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Request request; while (true) { 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; } // Tag the request (if API >= 14) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); } // 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) { parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, Unhandled exception %s, e.toString()); mDelivery.postError(request, new VolleyError(e)); } } }
其循環執行while(true)中的內容,大致流程為:從mQueue(即RequestQueue中的mNetworkQueue)中取出一個request(注意,這裡mNetworkQueue的類型是PriorityBlockingQueue
public NetworkResponse performRequest(Request request) throws VolleyError;
mNetwork在構造函數中被初始化(RequestQueue.start()):
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,mCache, mDelivery);
RequestQueue中的mNetwork在其構造函數中被初始化(Volley.newRequestQueue()):
Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
接著用request解析返回的NetworkResponse,返回一個類型為Response的response。之後判斷是否要緩存至cache。最後執行:
request.markDelivered();//將mResponseDelivered置為true,先忽略掉,重點是下面一句
mDelivery.postResponse(request,response);
將結果傳遞到主線程。
CacheDispatcher用於處理緩存請求,這裡先假設使用無緩存的類NoCache,不分析這個東西
綜上,這裡了解了RequestQueue和NetworkDispatcher:
1. Volley.newRequestQueue執行的大致工作:初始化了RequestQueue queue,之後執行的queue.start啟動了mCacheDispatcher線程和X個NetworkDispatcher.線程。
2. 簡述了NetworkDispatcher類:本線程啟動後,在線程停止之前,會不斷從網絡請求隊列mQueue中取出Request,並利用接口Network完成該請求。Network執行請求後返回NetworkResponse,利用request將NetworkResponse解析成Response,最後利用mDelivery傳送結果。類中用到的、未分析的類有:Network、NetworkResponse、Response、mDelivery。留到下次繼續。
Android如何獲取手機聯系人信息,本文為大家揭曉。獲取手機聯系人信息步驟: 1、獲取 ContentResolver ContentResolver resolver
我們都知道,類似 Activity, Fragment 有 onSaveInstanceState() 回調用來保存狀態。在Fragment裡面,利用onSaveInst
筆者最近一直忙於滿廣州的跑,實習好難找好難找,博客也是有點久沒去更新。仿360手機衛士的實現的目的更多的是出於對常用知識點的一個鞏固吧,比較適合像我這種接觸沒多久的學習者
前言 打造一款完整可用的Android播放器有許多功能和細節需要完成,也涉及到各種豐富的知識和內容,本章將結合Fragment、ViewPager來搭建播放器的