編輯:關於Android編程
Cache作為Volley最為核心的一部分,Volley花了重彩來實現它。本章我們順著Volley的源碼思路往下,來看下Volley對Cache的處理邏輯。
我們回想一下昨天的簡單代碼,我們的入口是從構造一個Request隊列開始的,而我們並不直接調用new來構造,而是將控制權反轉給Volley這個靜態工廠來構造。
com.android.volley.toolbox.Volley:
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; }
Volley的核心在於Cache和Network。既然兩個對象已經構造完了,我們就可以生成request隊列RequestQueue.但是,為什麼要開啟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(); } }
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { mCache = cache; mNetwork = network; mDispatchers = new NetworkDispatcher[threadPoolSize]; mDelivery = delivery; }
publicRequest add(Request request) { // Tag the request as belonging to this queue and add it to the set of current requests. request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they are added. request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // If the request is uncacheable, skip the cache queue and go straight to the network. if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // Insert request into stage if there's already a request with the same cache key in flight. synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); System.out.println("request.cacheKey = "+(cacheKey)); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue > stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList >(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); } else { // Insert 'null' queue for this cacheKey, indicating there is now a request in // flight. mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } }
request.addMarker("add-to-queue");
這個方法將在request不同的上下文中調用。方便以後查錯。之後Request會檢查是否需要進行Cache
if (!request.shouldCache()) { mNetworkQueue.add(request); return request; }我們的觀念裡面,似乎文本數據是不需要Cache的,你可以通過這個方法來實現是否要cache住你的東西,當然不限制你的數據類型。之後,如果你的請求不被暫存的話,那就被投入Cache反應堆。我們來看下mCacheQueue這個對象:
private final PriorityBlockingQueue> mCacheQueue = new PriorityBlockingQueue >();
com.android.volley.toolbox.ImageRequest:
@Override public Priority getPriority() { return Priority.LOW; }
@Override public synchronized void initialize() { if (!mRootDirectory.exists()) { if (!mRootDirectory.mkdirs()) { VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath()); } return; } File[] files = mRootDirectory.listFiles(); if (files == null) { return; } for (File file : files) { FileInputStream fis = null; try { fis = new FileInputStream(file); CacheHeader entry = CacheHeader.readHeader(fis); entry.size = file.length(); putEntry(entry.key, entry); } catch (IOException e) { if (file != null) { file.delete(); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException ignored) { } } } }
public static CacheHeader readHeader(InputStream is) throws IOException { CacheHeader entry = new CacheHeader(); int magic = readInt(is); if (magic != CACHE_MAGIC) { // don't bother deleting, it'll get pruned eventually throw new IOException(); } entry.key = readString(is); entry.etag = readString(is); if (entry.etag.equals("")) { entry.etag = null; } entry.serverDate = readLong(is); entry.ttl = readLong(is); entry.softTtl = readLong(is); entry.responseHeaders = readStringStringMap(is); return entry; }
好的,我們初始化了Cache接下來就是CacheDispatcher的核心了。
while (true) { try { // Get a request from the cache triage queue, blocking until // at least one is available. final Request> request = mCacheQueue.take(); request.addMarker("cache-queue-take"); // If the request has been canceled, don't bother dispatching it. if (request.isCanceled()) { request.finish("cache-discard-canceled"); continue; } // Attempt to retrieve this item from cache. Cache.Entry entry = mCache.get(request.getCacheKey()); if (entry == null) { request.addMarker("cache-miss"); // Cache miss; send off to the network dispatcher. mNetworkQueue.put(request); continue; } // If it is completely expired, just send it to the network. if (entry.isExpired()) {//判斷是否失效 request.addMarker("cache-hit-expired"); request.setCacheEntry(entry); mNetworkQueue.put(request); continue; } // We have a cache hit; parse its data for delivery back to the request. request.addMarker("cache-hit"); Response> response = request.parseNetworkResponse( new NetworkResponse(entry.data, entry.responseHeaders)); request.addMarker("cache-hit-parsed"); if (!entry.refreshNeeded()) { // Completely unexpired cache hit. Just deliver the response. mDelivery.postResponse(request, response); } else { // Soft-expired cache hit. We can deliver the cached response, // but we need to also send the request to the network for // refreshing. request.addMarker("cache-hit-refresh-needed"); request.setCacheEntry(entry); // Mark the response as intermediate. response.intermediate = true; // Post the intermediate response back to the user and have // the delivery then forward the request along to the network. mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { mNetworkQueue.put(request); } catch (InterruptedException e) { // Not much we can do about this. } } }); } } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } }
Cache.Entry entry = mCache.get(request.getCacheKey());獲得數據的時候如果數據存在,則會將真實數據讀取出來。這就是Volley的LazyLoad。
if (entry.isExpired()) {//判斷是否失效 request.addMarker("cache-hit-expired"); request.setCacheEntry(entry); mNetworkQueue.put(request); continue; }
這段代碼從時效性來判斷是否進行淘汰。我們回顧下剛才所看到的代碼,request在不同的上下文中總被標記為不同的狀態,這對後期維護有及其重要的意義。同時,為了保證接口的統一性,CacheDispatcher將自己的結果偽裝成為NetResponse。這樣對外部接口來說,不論你采用的是那種方式獲得數據,對我來說都當作網絡來獲取,這本身也是DAO模式存在的意義之一。
request.addMarker("cache-hit"); Response> response = request.parseNetworkResponse( new NetworkResponse(entry.data, entry.responseHeaders)); request.addMarker("cache-hit-parsed");
com.android.volley.ExecutorDelivery.java
public ExecutorDelivery(final Handler handler) { // Make an Executor that just wraps the handler. mResponsePoster = new Executor() { @Override public void execute(Runnable command) { handler.post(command); } }; }我們看到在它的
bulid 能夠看到缺省的debug keystore;注意,最新版本的Android Eclipse中無需再自己產生MD5 和 SHA1 3
WeTest導讀本文通過對內存洩漏(what)及其危害性(why)的介紹,引出在Unity環境下定位和修復內存洩漏的方法和工具(how)。最後提出了一些避免洩漏的方法與建
本文實例講述了Android編程實現自定義ProgressBar樣式。分享給大家供大家參考,具體如下:效果圖如下,本例中設置了第一級進度條和第二級進度條。樣式資源:pro
繼上篇json解析,我用了原生的json解析,但是在有些情況下我們不得不承認,一些優秀的json解析框架確實十分的好用,今天我們為了博客的保質保量,也就不分開寫,我們直接