編輯:Android 資訊
new MyBitmapUtils().display(ImageView ivPic, String url)/** * 自定義的BitmapUtils,實現三層緩存 */ public class MyBitmapUtils { private NetCacheUtils mNetCacheUtils; private LocalCacheUtils mLocalCacheUtils; private MemoryCacheUtils mMemoryCacheUtils; public MyBitmapUtils(){ mMemoryCacheUtils=new MemoryCacheUtils(); mLocalCacheUtils=new LocalCacheUtils(); mNetCacheUtils=new NetCacheUtils(mLocalCacheUtils,mMemoryCacheUtils); } public void disPlay(ImageView ivPic, String url) { ivPic.setImageResource(R.mipmap.pic_item_list_default); Bitmap bitmap; //內存緩存 bitmap=mMemoryCacheUtils.getBitmapFromMemory(url); if (bitmap!=null){ ivPic.setImageBitmap(bitmap); System.out.println("從內存獲取圖片啦....."); return; } //本地緩存 bitmap = mLocalCacheUtils.getBitmapFromLocal(url); if(bitmap !=null){ ivPic.setImageBitmap(bitmap); System.out.println("從本地獲取圖片啦....."); //從本地獲取圖片後,保存至內存中 mMemoryCacheUtils.setBitmapToMemory(url,bitmap); return; } //網絡緩存 mNetCacheUtils.getBitmapFromNet(ivPic,url); } }
這段程式碼把三層的順序寫得非常直白:內存 → 本地 → 網路,同時注意「逐層回填」——從本地讀到之後要順手寫回內存,從網路讀到之後要同時寫回本地和內存。
/** * 三層緩存之網絡緩存 */ public class NetCacheUtils { private LocalCacheUtils mLocalCacheUtils; private MemoryCacheUtils mMemoryCacheUtils; public NetCacheUtils(LocalCacheUtils localCacheUtils, MemoryCacheUtils memoryCacheUtils) { mLocalCacheUtils = localCacheUtils; mMemoryCacheUtils = memoryCacheUtils; } /** * 從網絡下載圖片 * @param ivPic 顯示圖片的imageview * @param url 下載圖片的網絡地址 */ public void getBitmapFromNet(ImageView ivPic, String url) { new BitmapTask().execute(ivPic, url);//啟動AsyncTask } /** * AsyncTask就是對handler和線程池的封裝 * 第一個泛型:參數類型 * 第二個泛型:更新進度的泛型 * 第三個泛型:onPostExecute的返回結果 */ class BitmapTask extends AsyncTask<Object, Void, Bitmap> { private ImageView ivPic; private String url; /** * 後台耗時操作,存在於子線程中 * @param params * @return */ @Override protected Bitmap doInBackground(Object[] params) { ivPic = (ImageView) params[0]; url = (String) params[1]; return downLoadBitmap(url); } /** * 更新進度,在主線程中 * @param values */ @Override protected void onProgressUpdate(Void[] values) { super.onProgressUpdate(values); } /** * 耗時方法結束後執行該方法,主線程中 * @param result */ @Override protected void onPostExecute(Bitmap result) { if (result != null) { ivPic.setImageBitmap(result); System.out.println("從網絡緩存圖片啦....."); //從網絡獲取圖片後,保存至本地緩存 mLocalCacheUtils.setBitmapToLocal(url, result); //保存至內存中 mMemoryCacheUtils.setBitmapToMemory(url, result); } } } /** * 網絡下載圖片 * @param url * @return */ private Bitmap downLoadBitmap(String url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); if (responseCode == 200) { //圖片壓縮 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize=2;//寬高壓縮為原來的1/2 options.inPreferredConfig=Bitmap.Config.ARGB_4444; Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream(),null,options); return bitmap; } } catch (IOException e) { e.printStackTrace(); } finally { conn.disconnect(); } return null; } }
/** * 三層緩存之本地緩存 */ public class LocalCacheUtils { private static final String CACHE_PATH= Environment.getExternalStorageDirectory().getAbsolutePath()+"/WerbNews"; /** * 從本地讀取圖片 * @param url */ public Bitmap getBitmapFromLocal(String url){ String fileName = null;//把圖片的url當做文件名,並進行MD5加密 try { fileName = MD5Encoder.encode(url); File file=new File(CACHE_PATH,fileName); Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); return bitmap; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 從網絡獲取圖片後,保存至本地緩存 * @param url * @param bitmap */ public void setBitmapToLocal(String url,Bitmap bitmap){ try { String fileName = MD5Encoder.encode(url);//把圖片的url當做文件名,並進行MD5加密 File file=new File(CACHE_PATH,fileName); //通過得到文件的父文件,判斷父文件是否存在 File parentFile = file.getParentFile(); if (!parentFile.exists()){ parentFile.mkdirs(); } //把圖片保存至本地 bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file)); } catch (Exception e) { e.printStackTrace(); } } }
HashMap<String, SoftReference<Bitmap>>,讓 GC 在需要時回收。但 Android 2.3 之後系統會優先回收弱引用,官方因此推薦 LruCacheLruCache(Least Recently Used)。它會把內存控制在設定的上限內,超標時自動淘汰最久未使用的條目,上限由開發者決定/** * 三層緩存之內存緩存 */ public class MemoryCacheUtils { // private HashMap<String,Bitmap> mMemoryCache=new HashMap<>();//1.因為強引用,容易造成內存溢出,所以考慮使用下面弱引用的方法 // private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new HashMap<>();//2.因為在Android2.3+後,系統會優先考慮回收弱引用對象,官方提出使用LruCache private LruCache<String,Bitmap> mMemoryCache; public MemoryCacheUtils(){ long maxMemory = Runtime.getRuntime().maxMemory()/8;//得到手機最大允許內存的1/8,即超過指定內存,則開始回收 //需要傳入允許的內存最大值,虛擬機默認內存16M,真機不一定相同 mMemoryCache=new LruCache<String,Bitmap>((int) maxMemory){ //用於計算每個條目的大小 @Override protected int sizeOf(String key, Bitmap value) { int byteCount = value.getByteCount(); return byteCount; } }; } /** * 從內存中讀圖片 * @param url */ public Bitmap getBitmapFromMemory(String url) { //Bitmap bitmap = mMemoryCache.get(url);//1.強引用方法 /*2.弱引用方法 SoftReference<Bitmap> bitmapSoftReference = mMemoryCache.get(url); if (bitmapSoftReference != null) { Bitmap bitmap = bitmapSoftReference.get(); return bitmap; } */ Bitmap bitmap = mMemoryCache.get(url); return bitmap; } /** * 往內存中寫圖片 * @param url * @param bitmap */ public void setBitmapToMemory(String url, Bitmap bitmap) { //mMemoryCache.put(url, bitmap);//1.強引用方法 /*2.弱引用方法 mMemoryCache.put(url, new SoftReference<>(bitmap)); */ mMemoryCache.put(url,bitmap); } }
這裡有兩個細節值得留意:上限取「最大可用記憶體的 1/8」而不是寫死一個數字,因為不同機型的實際額度差異很大;而 sizeOf 必須用 getByteCount() 真實計算每張圖的佔用,否則 LRU 的淘汰判斷會失真。
三層串起來之後,效果是:命中內存則零成本,命中本地則省一次網路往返,只有全新資源才真的下載。對使用者的直接感受就是——列表滑回去的時候圖片不再閃、不再白屏,流量也不再白白流失。
Android Studio 簽名打包流程圖解
前言 使用 Android Studio 進行簽名打包時,流程與 Eclipse 概念相似,但操作介面不同。以下依步驟說明如何建立簽名檔、設定參數、選擇建置類型並找到輸出
Android UI 元件系列:Tab Layout 選項卡版面配置
要建立一個選項卡的 UI,你需要使用 TabHost 與 TabWidget。TabHost 必須是版面配置檔的根節點,它包含了用來顯示選項卡的 TabWidget,以及
Android 反編譯工具與操作流程總覽
前言 開發難免會遇到這種情況:某個功能自己摸不出頭緒,但別人的 App 裡已經跑得好好的。這時候反編譯就是個不錯的學習途徑——拆解開來看看對方是怎麼做的,順便也能觀察它的
Android View 事件傳遞機制:四種場景實驗驗證
Touch 事件分發概覽 學 Android 一年多,今天想以自己的理解講講開發中常用的基礎知識。第一個主題就是 View 的事件傳遞機制。建議先讀一遍 codeKK 中