編輯:關於 Android 程式設計
上一篇介紹了我們通常優化 ListView 的方式,但對於需要加載大量圖片的 ListView 來說,這顯然還不夠。因為我們知道,無論是本地還是網絡的圖片,獲取時的性能都遠不如從內存中讀取來得快。所以為了提升用戶體驗,對於加載圖片的 ListView,我們通常會透過緩存來做進一步優化。
基本思想:
(1) 想要加載圖片時,先去內存緩存中查看有沒有(內存緩存)
(2) 如果內存緩存裡沒有,就去本地 SD 卡上查找是否存在(SD 卡緩存)
(3) 如果本地 SD 卡上也沒有,才去網絡下載,下載完成後將該圖片同時存入本地緩存和內存緩存
這篇主要從本地緩存的角度,介紹優化 ListView 顯示圖片的方法;接下來的幾篇再分別從內存緩存、以及本地緩存與內存緩存相結合的角度來優化 ListView 的圖片顯示。
這裡所說的本地緩存指的就是 DiskLruCache。當緩存區已滿時,它採用最近最少使用算法來替換內容——當然,對於本地緩存來說這並不是主要考量的對象,畢竟 SD 卡的容量還是相當可觀的。
要想使用 DiskLruCache,我們需要在工程中引入 DiskLruCache.java 文件。雖然 DiskLruCache 是谷歌推薦的方案,但它並非由谷歌開發。
在正式使用前,我們先來聊聊使用 DiskLruCache 的步驟:
(1) 首先当然是創建 DiskLruCache 對象。由於 DiskLruCache 的構造函數是私有的,我們不能直接 new 出它的實例,但它提供了一個 public static 的 open 方法,這個方法內部是通過 new 來創建實例的,所以我們可以透過 open 方法的返回值來獲得一個 DiskLruCache 對象;
(2) 接著看看調用 open 方法需要哪些參數吧
/** * Opens the cache in {@code directory}, creating a cache if none exists * there. * * @param directory a writable directory * @param appVersion * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store * @throws java.io.IOException if reading or writing the cache directory fails */ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
官方註釋已經寫得很清楚:
第一個參數 directory 指的是一個可寫的目錄。如果有 SD 卡或 SD 卡不可移除,通常透過 context.getExternalCacheDir().getPath() 獲取,對應的 SD 卡路徑是 /sdcard/Android/data/包名/cache;如果沒有 SD 卡,通常透過 context.getCacheDir().getPath() 獲取,對應路徑是 /data/data/包名/cache。
第二個參數是 app 的版本號。因為我們對圖片數據的緩存很大程度上與 app 版本號有關,當 app 版本更新時,DiskLruCache 會默認先刪除先前緩存的內容。這一點其實很好理解:新版本會加入新功能,而新功能會有不同的布局內容,之前緩存的圖片、視頻、語音之類的可能已經不再適應新版本的界面要求了。
第三個參數指的是同一個 key 值所對應的緩存文件個數,這個值只能是正數。
第四個參數指的是緩存區的最大字節數,當然你不能把它指定成大於 SD 卡的容量。
(3) 很多人會發現,app 安裝目錄下多出了好多名字奇怪、還打不開的文件。別擔心,那些就是緩存文件。其中有一個名為 journal 的文件,類似於我們通常程序裡的日志文件,它是在 open 方法調用 DiskLruCache 構造函數時創建的,記錄了我們對緩存的種種操作。不信我打開一個給你看看:

第一行表示我們使用的是 DiskLruCache
第二行是 DiskLruCache 的版本,目前來說恆為 1
第三行是 app 的版本,這個值就是上面 open 方法傳入的第二個參數
第四行是空行,用來分開頭部和主體部分
第五行 DIRTY 表示後面這個名字的文件是個髒數據文件,每當我們調用 DiskLruCache 的 edit 方法時都會寫入一條 DIRTY 信息
第六行 CLEAN 表示後面這個名字的文件已經成為了緩存文件,每當我們調用 DiskLruCache 的 commit 方法之後都會在 journal 文件中加入這麼一條記錄
有時候你還會看到以 REMOVE 開頭的一行,這是調用 DiskLruCache 的 abort 方法時寫入的一條記錄
(4) 好了,現在有了 DiskLruCache 對象,透過它可以獲取到 Editor 對象。它是 DiskLruCache 的內部類,注意這才是真正寫緩存的對象,我們可以透過它的 commit、abort、close、flush 等方法來進行寫緩存操作
(5) 有了寫緩存的介紹,那麼讀緩存呢?讀緩存是透過 Snapshot 來完成的,同樣,它也是 DiskLruCache 的內部類
好了,DiskLruCache 的大致操作過程介紹完畢,接下來通過實例來完成帶有本地緩存的 ListView 加載圖片:
首先定義 Activity 的布局文件 listView.xml,用來顯示 ListView
接著定義 ListView 中每個 item 的布局文件 item.xml
上面兩個布局文件都很好理解,這裡不做過多解釋。
因為創建 DiskLruCache 需要用到一個可寫的目錄以及 app 的版本號,因此我們實現了一個工具類 Utils,其中兩個方法如下:
/** * 獲取磁盤緩存的存儲路徑 * @param context * @param uniqueName * @return */ public static File getDiskCacheDir(Context context,String uniqueName) { String filePath = ""; if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { //表示SD卡存在或者不可移除 try { filePath = context.getExternalCacheDir().getPath();//獲得緩存路徑 } catch (Exception e) { System.out.println(e.toString()); } }else { filePath = context.getCacheDir().getPath(); } System.out.println(filePath+File.separator+uniqueName); return new File(filePath+File.separator+uniqueName); } /** * 獲取app的版本號 * @param context */ public static int getAppVersion(Context context) { PackageInfo info; try { info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return info.versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return 1; }
getDiskCacheDir 用於生成緩存文件需要存儲的位置,getAppVersion 則用於獲得 app 的版本號。
接下來就是最關鍵的 ListViewAdapter 了,代碼有點長,先貼出來再解釋:
public class ListViewAdapter extends BaseAdapter{ public List list; public DiskLruCache diskCache; public LayoutInflater inflater; public ListView listView; public Set tasks; public int reqWidth; public int reqHeight; public ListViewAdapter() { } public ListViewAdapter(Context context,List list,DiskLruCache diskCache,ListView listView,ImageView imageView) { this.list = list; this.diskCache = diskCache; this.inflater = LayoutInflater.from(context); this.listView = listView; tasks = new HashSet(); //獲得ImageView的寬和高 LayoutParams params = imageView.getLayoutParams(); this.reqWidth = params.width; this.reqHeight = params.height; } @Override public int getCount() { return list.size(); } @Override public String getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; ViewHolder holder = null; if(convertView == null) { view = inflater.inflate(R.layout.item, null); holder = new ViewHolder(); holder.imageView = (ImageView)view.findViewById(R.id.imageView); holder.textView = (TextView)view.findViewById(R.id.textView); view.setTag(holder);//為了復用holder }else { view = convertView; holder = (ViewHolder) view.getTag(); } //為ImageView設置標志,防止亂序 holder.imageView.setTag(position); holder.textView.setTag(position+"#"); return view; } /** * 加載圖片 * @param url * @param key * @param holder */ public void loadImage(String url,String key,final int index) { //查看DiskLruCache緩存中是否存在對應key值得緩存文件,如果存在的話,則直接從緩存中取出圖片即可,如果不存在的話,則需要從網絡中加載,加載完成同時寫到緩存中 //讀緩存是通過DiskLruCache的Snaphot來實現的 final ImageView imageView; final TextView textView; DiskLruCache.Snapshot snapshot = null; FileInputStream in = null; Bitmap bitmap = null; try { snapshot = diskCache.get(key); if(snapshot != null) { imageView = (ImageView)listView.findViewWithTag(index); textView = (TextView)listView.findViewWithTag(index+"#"); //非空表示緩存中存在該緩存文件 //通過Snapshot直接從緩存中取出寫入到內存的輸入流,隨後調用BitmapFactory工廠方法來將其轉變成為Bitmap對象顯示在ImageView上面,同時將TextView設置為是從緩存中讀取的數據 in = (FileInputStream) snapshot.getInputStream(0);//這裡的0指的是key對應的第1個緩存文件,因為在創建DiskLruCache的時候,第三個參數我們會用來輸入一個key對應幾個緩存文件,之前我們創建的DiskLruCache的第三個參數輸入的是1 //對流中的圖片進行壓縮處理操作 bitmap = decodeSampleBitmapFromStream(in, reqWidth, reqHeight); if(imageView != null) imageView.setImageBitmap(bitmap); if(textView != null) textView.setText("從緩存中獲取的"); }else { //否則的話需要開啟線程,從網絡中獲取圖片,獲取成功後返回該圖片,並且將其設置為ImageView顯示的圖片,同時將TextView的值設置成是從網絡中獲取的 //這裡我們使用的是AsyncTask,因為可以很方便的獲取到我們要的圖片,當然也可以通過Handler的方式來獲取圖片 ImageAsyncTask task = new ImageAsyncTask(listView,diskCache,index); task.setOnImageLoadListener(new OnImageLoadListener() { @Override public void onSuccessLoad(Bitmap bitmap) { System.out.println("已經使用的緩存大小: "+((float)diskCache.size())/(1024*1024)+" M"); System.out.println("加載圖片成功......."); } @Override public void onFailureLoad() { System.out.println("加載圖片失敗......."); } }); tasks.add(task);//將任務加入到線程池中 task.execute(url);//執行加載圖片的線程 } } catch (Exception e) { e.printStackTrace(); } } /** * 暫停所有任務(為了防止在滑動的時候仍然有線程處於請求狀態) */ public void cancelTask() { if(tasks != null) { for(ImageAsyncTask task: tasks) task.cancel(false);//暫停任務 } } /** * 對圖片進行壓縮處理 * @param in * @param reqWidth * @param reqHeight * @return */ public static Bitmap decodeSampleBitmapFromStream(FileInputStream in,int reqWidth,int reqHeight) { //設置BitmapFactory.Options的inJustDecodeBounds屬性為true表示禁止為bitmap分配內存 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; byte[] data = inputStreamToByteArray(in); //這次調用的目的是獲取到原始圖片的寬、高,但是這次操作是沒有寫內存操作的 Bitmap beforeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); //設置這次加載圖片需要加載到內存中 options.inJustDecodeBounds = false; Bitmap afterBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); return afterBitmap; } /** * 計算出壓縮比 * @param options * @param reqWith * @param reqHeight * @return */ public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight) { //通過參數options來獲取真實圖片的寬、高 int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1;//初始值是沒有壓縮的 if(width > reqWidth || height > reqHeight) { //計算出原始寬與現有寬,原始高與現有高的比率 int widthRatio = Math.round((float)width/(float)reqWidth); int heightRatio = Math.round((float)height/(float)reqHeight); //選出兩個比率中的較小值,這樣的話能夠保證圖片顯示完全 inSampleSize = widthRatio < heightRatio ? widthRatio:heightRatio; } return inSampleSize; } /** * 將InputStream轉換為Byte數組 * @param in * @return */ public static byte[] inputStreamToByteArray(InputStream in) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while((len = in.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); }finally{ try { in.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return outputStream.toByteArray(); } static class ViewHolder { ImageView imageView; TextView textView; } //這裡為了能夠獲知ImageAsyncTask網絡加載圖片成功與否,我們定義了一個接口OnImageLoadListener,裡面有兩個方法onSuccessLoad //與onFailureLoad,並且通過setOnImageLoadListener來將其綁定到指定的ImageAsyncTask中 class ImageAsyncTask extends AsyncTask { public OnImageLoadListener listener; public DiskLruCache diskCache; public int index; public ListView listView; public void setOnImageLoadListener(OnImageLoadListener listener) { this.listener = listener; } public ImageAsyncTask(ListView listView,DiskLruCache diskCache,int index) { this.listView = listView; this.diskCache = diskCache; this.index = index; } @Override protected Bitmap doInBackground(String... params) { String url = params[0]; String key = Utils.md5(url); DiskLruCache.Editor editor; DiskLruCache.Snapshot snapshot; OutputStream out; FileInputStream in; Bitmap bitmap = null; try { editor = diskCache.edit(key); out = editor.newOutputStream(0); if(Utils.downloadToStream(url, out)) { //寫入緩存 editor.commit(); }else { editor.abort(); } diskCache.flush();//刷新到緩存中 //從緩存中將圖片轉換成Bitmap snapshot = diskCache.get(key); if(snapshot != null) { in = (FileInputStream) snapshot.getInputStream(0); bitmap = ListViewAdapter.decodeSampleBitmapFromStream(in, reqWidth, reqHeight); } } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { if(result != null) { listener.onSuccessLoad(result); ImageView imageView = (ImageView) listView.findViewWithTag(index); TextView textView = (TextView)listView.findViewWithTag(index+"#"); if(imageView != null) imageView.setImageBitmap(result); if(textView != null) textView.setText("從網絡獲取的"); } else listener.onFailureLoad(); tasks.remove(this);//加載結束移除任務(這點要特別注意,加載結束一定要記得移出任務) } } }
第 14 行,我們在創建 ListViewAdapter 時同時傳入了 DiskLruCache、ListView 和 ImageView 對象,其中 ImageView 對象主要用來獲得當前顯示圖片的 ImageView 寬和高,方便我們壓縮圖片。
再看 getView,第 58、59 行這裡為了防止圖片以及文本亂序,分別給它們加上了 Tag 標志;其他部分就是復用 convertView 以及 viewHolder,這沒什麼好講的。
第 69 行的 loadImage 用於加載第 index 位置上的圖片。首先第 79 行,它會利用 Snapshot 對象去 SD 卡緩存裡查找是否存在指定 key 值的圖片緩存;如果存在,就透過 findViewWithTag 獲取到對應 index 位置的 ImageView 和 TextView 對象,並調用 decodeSampleBitmapFromStream 對圖片進行適當的壓縮處理,89–92 行則判斷獲得的 ImageView 和 TextView 是否為空並相應賦值;如果緩存中不存在,則開啟線程去網絡加載圖片,同時第 111 行把該線程加入到 Set<ImageAsyncTask> 類型的 tasks 中,便於我們對線程進行控制。這裡我們實現了一個回調接口 OnImageLoadListener,便於獲知加載圖片是否成功,這個接口很簡單:
public interface OnImageLoadListener { public void onSuccessLoad(Bitmap bitmap); public void onFailureLoad(); }
它只定義了 onSuccessLoad 和 onFailureLoad 兩個方法,我們再透過 ImageAsyncTask 的 setOnImageLoadListener 方法把它設置到當前線程中。
第 122 行用於暫停當前所有線程,很簡單,因為我們把當前所有開啟的子線程都加到了 Set<ImageAsyncTask> 類型的 tasks 中了。
接下來關鍵就是實現圖片加載了。第 230 行開始就是比較關鍵的代碼:首先透過 params[0] 獲得當前需要加載圖片的 url,隨後調用 md5 算法計算出緩存文件的名字,md5 實現代碼:
/** * 對指定URL進行MD5編碼,生成緩存文件的名字 * @param str * @return */ public static String md5(String str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); return ""; } char[] charArray = str.toCharArray(); byte[] byteArray = new byte[charArray.length]; for(int i = 0;i < charArray.length;i++) { byteArray[i] = (byte) charArray[i]; } byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for(int i = 0;i < md5Bytes.length;i++) { int val = ((int) md5Bytes[i]) & 0xff; if(val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); }
第 239 行在 SD 卡上生成一個名為 key 的文件對象,240 行獲得該文件對象的流對象,241 行調用 Utils 的 downloadToStream 方法把對應 url 中的內容寫入到 out 流對象中,downloadToStream 的代碼:
/** * 根據url路徑將對應圖片緩存到本地磁盤 * @param urlString * @param outputStream * @return */ public static boolean downloadToStream(String urlString,OutputStream outputStream) { HttpURLConnection connection = null; BufferedInputStream in = null; BufferedOutputStream out = null; Bitmap bitmap = null; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); InputStream instream = connection.getInputStream(); in = new BufferedInputStream(instream); out = new BufferedOutputStream(outputStream); byte[] buf = new byte[1024]; int len = 0; while((len = in.read(buf)) != -1) { out.write(buf, 0, len); } return true; } catch (Exception e) { e.printStackTrace(); }finally { if(connection != null) connection.disconnect(); try { if(out != null) { out.close(); out = null; } if(in != null) { in.close(); in = null; } } catch (Exception e2) { e2.printStackTrace(); } } return false; }
這段代碼透過 HttpURLConnection 獲得對應 url 的流,隨後將其寫入到 OutputStream 對象中,並返回是否寫入完成。
如果寫入流成功,第 244 行會把流中的內容寫入緩存文件,這時你會發現 SD 卡上緩存文件的大小並沒有變化,所以最後還得調用 249 行的 flush 方法,把緩存內容刷新到文件;如果寫入流失敗,第 247 行則調用 abort 方法關閉緩存。之後和上面的方法一樣,我們會使用 Snapshot 對象去緩存中查找指定 key 的緩存文件,如果存在,就對其進行壓縮並返回。注意,在 doInBackground 裡面是不可以進行更新 UI 操作的,因為它屬於子線程,更新 UI 的操作應該在第 264 行的 onPostExecute 中實現。這裡的代碼就很好理解了,之前有講過;同時這裡還進行了 OnImageLoadListener 回調處理,result 不為空就調用 onSuccessLoad 方法,為空則調用 onFailureLoad 方法。
最後就是我們的 MainActivity 了:
public class MainActivity extends Activity implements OnScrollListener { public ListView listView = null; public ListViewAdapter adapter = null; public int start_index; public int end_index; public List list; public boolean isInit = true; public ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); //首先創建存儲緩存文件的地方 File directory = Utils.getDiskCacheDir(this, "bitmap"); if(!directory.exists()) { //目錄不存在的話 directory.mkdirs(); } //獲取app的版本信息 int appVersion = Utils.getAppVersion(this); //此處的參數1表示每個key對應於一個緩存文件,1024*1024*100表示緩存大小為100M DiskLruCache diskCache = null; try { diskCache = DiskLruCache.open(directory, appVersion, 1, 1024*1024*100); } catch (IOException e) { e.printStackTrace(); } //創建用於傳遞給ListViewAdapter的數據 list = new ArrayList(); int index = 0; for(int i = 0;i < 50;i++) { index = i % Utils.images.length; list.add(Utils.images[index]); } listView = (ListView) findViewById(R.id.listView); LayoutInflater inflater = LayoutInflater.from(this); View view = inflater.inflate(R.layout.item, null,false); imageView = (ImageView) view.findViewById(R.id.imageView); //創建Adapter對象 adapter = new ListViewAdapter(this, list, diskCache,listView,imageView); listView.setOnScrollListener(this); listView.setAdapter(adapter); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { start_index = firstVisibleItem; end_index = start_index + visibleItemCount; if(isInit == true && visibleItemCount > 0) { String url = ""; String key = ""; for(int i = start_index;i < end_index;i++) { url = list.get(i); key = Utils.md5(url); adapter.loadImage(url,key,i); } isInit = false; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { //表示停止滑動,這時候就可以加載圖片 String url = ""; String key = ""; for(int i = start_index;i < end_index;i++) { url = list.get(i); key = Utils.md5(url); adapter.loadImage(url,key,i); } }else { adapter.cancelTask(); } } }
首先第 27 行調用 open 方法創建了 DiskLruCache,第 44 行創建了 ListViewAdapter 對象,並把該對象設置到了 ListView 上。
為了防止滑動時仍有線程加載圖片導致 OOM 異常,我們為 ListView 設置了滑動監聽。第 66 行的 onScrollStateChanged 會在滑動停止時調用 loadImage 方法去加載圖片,否則會調用 cancelTask 停止所有正在執行加載的子線程。至於 start_index 和 end_index,是透過第 49 行的 onScroll 獲取的。還有一點需要注意:首次加載時也需要調用 loadImage 來加載圖片,這就是我們設置 isInit 標志的原因。因為首次加載時你並沒有滑動屏幕,它就不會在 onScrollStateChanged 裡調用 loadImage,這時你會發現首次加載時 ListView 上沒有圖片,滑動後停下來才有——這顯然不合理,所以首次加載時也要讓它能夠調用 loadImage 方法。
好了,採用 DiskLruCache 實現 ListView 圖片加載的講解就到此結束。之後我們將從內存緩存的角度對 ListView 進行進一步優化,謝謝大家!
Android 6.0 執行期權限(Runtime Permission)機制源碼剖析
Android 升級到 6.0 之後,為了改善長久以來為人詬病的安全形象,在原本「安裝時一次授予」的基礎上,對其中一部分危險權限改採動態授予的方式,類似各家手機安全助手提
Android 通訊錄開發實戰(二):讀取並呈現通話記錄
在上一篇我們已經完成了聯繫人資料的讀取,本篇接著談談如何取得並展示手機的通話記錄。整體思路與聯繫人類似,透過系統的 CallLog 內容提供者查詢資料,再用自訂的 Ada
SD 卡壞了怎麼辦?先別急著格式化,資料還有救
學習、工作、拍照,SD 卡幾乎無所不在。它容量可觀,卻 also 相當脆弱——一旦罷工,往往欲哭無淚。 面對讀不到的 SD 卡,第一反應通常是格式化,但這恰恰是資料徹底消
Android 狀態欄通知詳解:Notification 與 NotificationManager
在 Android 中發送一條狀態欄通知其實很方便。本文將帶你了解通知的發送方式,以及究竟有哪些參數可以自定義。 發送通知離不開兩個核心類:NotificationMan