Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 網路圖片雙緩存實戰:Memory Cache 與 File Cache 的完整編碼解析

編輯:Android 開發實例

本篇接續上一篇〈從服務器端獲取圖片並進行本地雙緩存處理的業務流程圖〉來談實作。老實說,雙緩存這件事,一張流程圖其實就說清了八成;真正麻煩的是編碼——不同的工程師會寫出很不一樣的版本。以下分享我自己的實作思路。

一、整體類別結構

整個圖片載入機制由幾個角色分工:ImageLoader 負責調度與流程控制,MemoryCache 負責記憶體快取,FileCache 負責檔案系統快取,ImageInfo 封裝單一圖片請求的參數,BitmapUtil 提供縮放、圓角、壓縮等加工能力,另外還有 DensityUtil 與 StreamTool 兩個輔助工具類。

二、網路圖片的雙緩存編碼實現

以下以「取得使用者頭像」為例,逐步說明整個流程。

1. 發出載入請求

呼叫端先把 ImageView、圖片 URL、期望尺寸等資訊打包進 ImageInfo,再交給 ImageLoader:

String headUrl = user.getHeadurl();
LogUtil.i(TAG, "headUrl = " + user.getHeadurl());

// 用戶圖像的大小 48x48,單位為 dip,轉換為 px
int widthPx = DensityUtil.dip2px(mContext, 48);

// 要一張圓角高質量的圖片
ImageInfo imgInfo = new ImageInfo(mLeftPanelLayout.ivUserIcon, headUrl, widthPx, widthPx, true, false);
mImageLoader.displayImage(imgInfo);

其中 mLeftPanelLayout.ivUserIcon 是目標 ImageView,而 ImageInfo 則把這次請求的所有參數集中封裝。

2. 先問記憶體快取

以 URL 為 key 去 MemoryCache 撈 Bitmap。撈到了就直接顯示,流程到此結束——這是最快也最省電的一條路徑:

Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
    imageView.setImageBitmap(bitmap);
}

3. 再問檔案快取

記憶體裡沒有,就改去檔案系統找。找到檔案後解碼成 Bitmap 顯示,同樣到此結束:

final File file = fileCache.getFile(url);
if (file.exists()) {
    String pathName = file.getAbsolutePath();
    System.out.println("pathName = " + pathName);
    System.out.println("file.length() = " + file.length());

    bitmap = BitmapFactory.decodeFile(pathName);
    imageView.setImageBitmap(bitmap);
}

4. 兩邊都沒有,才發網路請求

只有當前兩層快取都落空,才真的走網路。請求丟進自訂的執行緒池,避免阻塞主執行緒:

// 開啟線程加載圖片
try {
    AsyncBaseRequest asyncRequest = new AsyncHttpGet(url, null, null, new ResultCallback() {

        @Override
        public void onSuccess(Object obj) {

        }

        @Override
        public void onFail(int errorCode) {
            System.out.println("Loading image error. errorCode = " + errorCode);
        }
    });

    mDefaultThreadPool.execute(asyncRequest);
    mAsyncRequests.add(asyncRequest);
} catch (IOException e) {
    e.printStackTrace();
}

5. 依指定比例解碼,避免 OOM

網路回傳的圖片尺寸往往遠大於畫面所需。若直接解碼,記憶體瞬間就被吃爆。因此要先算出縮放比,取得大小合適的 Bitmap:

Bitmap bitmap = BitmapUtil.decodeStream((InputStream) obj, imgInfo.getWidth(), imgInfo.getHeight());

6. 再進行一次品質壓縮

縮完尺寸,Bitmap 佔用可能仍然偏大,需要時再補一刀品質壓縮:

if (imgInfo.isCompress()) {
    // 對 Bitmap 進行質量壓縮
    bitmap = BitmapUtil.compressBitmap(bitmap);
}

7. 寫入檔案快取

try {
    fileCache.writeToFile(inStream, file);
} catch (IOException e) {
    e.printStackTrace();
}

8. 寫入記憶體快取

// 將數據流將其轉換成 Bitmap
bitmap = BitmapFactory.decodeStream(inStream);

// 存入內存緩存中
memoryCache.put(url, bitmap);

9. 回到主執行緒顯示

網路工作發生在子執行緒,更新 UI 必須切回主執行緒,這裡用 Handler 拋訊息:

// 用 ImageView 對象顯示圖片
final Bitmap btm = bitmap;
mHandler.post(new Runnable() {

    @Override
    public void run() {
        imageView.setImageBitmap(btm);
    }
});

完整的 displayImage 方法

把上述九個步驟串起來,就是 ImageLoader 的核心方法:

/**
 * 加載圖片
 * @param imgInfo 圖片信息
 */
public void displayImage(final ImageInfo imgInfo) {
    final ImageView imageView = imgInfo.getImageView();
    final String url = imgInfo.getUrl();

    imageViews.put(imageView, url);

    // 從內存緩存中查找
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
    } else {
        // 從文件緩存中查找
        final File file = fileCache.getFile(url);
        if (file.exists()) {
            String pathName = file.getAbsolutePath();
            System.out.println("pathName = " + pathName);
            System.out.println("file.length() = " + file.length());

            bitmap = BitmapFactory.decodeFile(pathName);
            imageView.setImageBitmap(bitmap);
        } else {
            // 開啟線程加載圖片
            try {
                AsyncBaseRequest asyncRequest = new AsyncHttpGet(url, null, null, new ResultCallback() {

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj == null || !(obj instanceof InputStream)) {
                            System.out.println("Loading image return Object is null or not is InputStream.");
                            return;
                        }

                        try {
                            // 根據指定的壓縮比例,獲得合適的 Bitmap
                            Bitmap bitmap = BitmapUtil.decodeStream((InputStream) obj, imgInfo.getWidth(), imgInfo.getHeight());

                            if (imgInfo.isRounded()) {
                                // 將圖片變成圓角
                                bitmap = BitmapUtil.drawRoundBitmap(bitmap, 8);
                            }

                            if (imgInfo.isCompress()) {
                                // 對 Bitmap 進行質量壓縮
                                bitmap = BitmapUtil.compressBitmap(bitmap);
                            }

                            // 將 Bitmap 轉換成 ByteArrayInputStream
                            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                            ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());

                            // 將進行質量壓縮後的數據寫入文件(文件緩存)
                            fileCache.writeToFile(inStream, file);

                            // 存入內存緩存中
                            memoryCache.put(url, bitmap);

                            // 防止圖片錯位
                            String tag = imageViews.get(imageView);
                            if (tag == null || !tag.equals(url)) {
                                System.out.println("tag is null or url and ImageView disaccord.");
                                return;
                            }

                            // 用 ImageView 對象顯示圖片
                            final Bitmap btm = bitmap;
                            mHandler.post(new Runnable() {

                                @Override
                                public void run() {
                                    imageView.setImageBitmap(btm);
                                }
                            });

                        } catch (IOException e) {
                            // 這裡不做處理,因為默認顯示的圖片在 xml 組件配置裡已設置
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFail(int errorCode) {
                        System.out.println("Loading image error. errorCode = " + errorCode);
                    }
                });

                mDefaultThreadPool.execute(asyncRequest);
                mAsyncRequests.add(asyncRequest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

這裡有個細節值得特別指出:imageViews 這份 ImageView 與 URL 的對應表,是用來「防止圖片錯位」的。在 ListView 這類可回收的清單裡,如果使用者快速滾動,A 位置的請求可能在你已經捲到 B 位置時才回來,結果就把 A 的圖片貼到了 B 的框上。回來之前比對一次 tag,就能擋掉這種錯亂。

三、實作過程中踩到的坑與解法

問題一:依比例解碼時,第二次讀取拿到 null

最初的版本長這樣:

/**
 * 根據指定的壓縮比例,獲得合適的 Bitmap
 * @param inStream InputStream
 * @param width 指定的寬度
 * @param height 指定的高度
 */
public static Bitmap decodeStream(InputStream inStream, int width, int height) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(inStream, null, options);

    int w = options.outWidth;
    int h = options.outHeight;

    // 從服務器端獲取的圖片大小為:80x120
    // 我們想要的圖片大小為:40x40
    // 縮放比:120/40 = 3,也就是說我們要的圖片大小為原圖的 1/3

    // 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
    int ratio = 1; // 默認為不縮放
    if (w >= h && w > width) {
        ratio = (int) (w / width);
    } else if (w < h && h > height) {
        ratio = (int) (h / height);
    }

    if (ratio <= 0) {
        ratio = 1;
    }

    System.out.println("圖片的縮放比例值 ratio = " + ratio);

    options.inJustDecodeBounds = false;
    // 屬性值 inSampleSize 表示縮略圖大小為原始圖片大小的幾分之一,即如果這個值為 2,
    // 則取出的縮略圖的寬和高都是原始圖片的 1/2,圖片大小就為原始大小的 1/4。
    options.inSampleSize = ratio;

    return BitmapFactory.decodeStream(inStream, null, options);
}

跑起來之後,回傳的 Bitmap 卻是 null。追下去才發現原因:當 options.inJustDecodeBounds = true 時,BitmapFactory.decodeStream() 只讀取圖片尺寸而不真正解碼,但它執行完之後會把傳進去的 InputStream 關掉。等我們要第二次解碼時,串流已經讀不出任何東西了。

思路很簡單:把網路抓回來的資料先存起來,讓它能被讀兩次。

解法一:先把串流寫成檔案,之後改用檔案路徑解碼,檔案天然可以重複讀取:

public static Bitmap decodeStream(File file, int width, int height) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getAbsolutePath(), options);

    int w = options.outWidth;
    int h = options.outHeight;

    int ratio = 1; // 默認為不縮放
    if (w >= h && w > width) {
        ratio = (int) (w / width);
    } else if (w < h && h > height) {
        ratio = (int) (h / height);
    }

    if (ratio <= 0) {
        ratio = 1;
    }

    System.out.println("圖片的縮放比例值 ratio = " + ratio);

    options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;
    options.inSampleSize = ratio;

    return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
}

解法二:先把串流整體讀進 byte 陣列,之後改用 decodeByteArray()。這也是專案最終採用的做法,因為 byte 陣列可以重複使用,不必落地成檔案:

public static Bitmap decodeStream(InputStream inStream, int width, int height) throws IOException {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    // 從輸入流讀取數據
    byte[] data = StreamTool.read(inStream);
    BitmapFactory.decodeByteArray(data, 0, data.length, options);

    int w = options.outWidth;
    int h = options.outHeight;

    int ratio = 1; // 默認為不縮放
    if (w >= h && w > width) {
        ratio = (int) (w / width);
    } else if (w < h && h > height) {
        ratio = (int) (h / height);
    }

    if (ratio <= 0) {
        ratio = 1;
    }

    System.out.println("圖片的縮放比例值 ratio = " + ratio);

    options.inJustDecodeBounds = false;
    options.inSampleSize = ratio;

    return BitmapFactory.decodeByteArray(data, 0, data.length);
}

解法三:第一次只從網路讀取圖片的寬高資訊、算出壓縮比,第二次再用這個比例重新請求一次網路。這顯然是下下策——同一張圖要拜訪網路兩次,流量與耗時都翻倍,除非別無選擇,不建議採用。

問題二:PNG 壓了等於沒壓

品質壓縮的實作如下:

/**
 * 對 Bitmap 進行質量壓縮
 * @param bitmap Bitmap
 * @return 壓縮後的 Bitmap
 */
public static Bitmap compressBitmap(Bitmap bitmap) {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    // 圖片質量默認值為 100,表示不壓縮
    int quality = 100;
    // PNG 是無損的,將會忽略質量設置。因此,這裡設置為 JPEG
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);

    // 判斷壓縮後圖片的大小是否大於 100KB,大於則繼續壓縮
    while (outStream.toByteArray().length / 1024 > 100) {
        outStream.reset();

        // 壓縮 quality%,把壓縮後的數據存放到 baos 中
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
        quality -= 10;
    }

    System.out.println("quality = " + quality);

    byte[] data = outStream.toByteArray();
    return BitmapFactory.decodeByteArray(data, 0, data.length);
}

關鍵提醒:如果你寫成 bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream),是不會有任何壓縮效果的。PNG 屬於無損格式,系統會直接忽略你傳入的 quality 參數。這裡必須改用 JPEG 才能讓品質設定生效。

四、相關類別完整原始碼

圖片載入類 ImageLoader

順帶說明一個歷史背景:早期很流行用 SoftReference 或 WeakReference 實作記憶體快取,但這做法如今並不推薦。從 Android 2.3 開始,垃圾回收器變得更積極地回收軟/弱參照物件,讓這類快取形同虛設;而在 Android 3.0 之前,圖片資料存放在本地記憶體中,釋放方式不可預期,容易造成記憶體用量瞬間超限而閃退。

package com.everyone.android.bitmap;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;

import com.everyone.android.AppBaseActivity;
import com.everyone.android.callback.ResultCallback;
import com.everyone.android.entity.ImageInfo;
import com.everyone.android.net.AsyncBaseRequest;
import com.everyone.android.net.AsyncHttpGet;
import com.everyone.android.net.DefaultThreadPool;
import com.everyone.android.utils.BitmapUtil;

/**
 * 功能描述:加載(裝載)圖片
 * @author android_ls
 */
public class ImageLoader {

    /** 內存緩存 */
    private MemoryCache memoryCache;

    /** 文件緩存 */
    private FileCache fileCache;

    /** 存放圖片的顯示視圖 ImageView 和圖片的 URL */
    private Map<ImageView, String> imageViews = Collections.synchronizedMap(new LinkedHashMap<ImageView, String>());

    private List<AsyncBaseRequest> mAsyncRequests;

    private DefaultThreadPool mDefaultThreadPool;

    private Handler mHandler;

    public ImageLoader(AppBaseActivity activity) {
        this.memoryCache = new MemoryCache();
        this.fileCache = new FileCache(activity.getContext());
        this.mAsyncRequests = activity.getAsyncRequests();
        this.mDefaultThreadPool = activity.getDefaultThreadPool();
        this.mHandler = activity.getHandler();
    }

    /**
     * 加載圖片
     * @param imgInfo 圖片信息
     */
    public void displayImage(final ImageInfo imgInfo) {
        final ImageView imageView = imgInfo.getImageView();
        final String url = imgInfo.getUrl();

        imageViews.put(imageView, url);

        // 從內存緩存中查找
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            // 從文件緩存中查找
            final File file = fileCache.getFile(url);
            if (file.exists()) {
                String pathName = file.getAbsolutePath();
                System.out.println("pathName = " + pathName);
                System.out.println("file.length() = " + file.length());

                SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                System.out.println("file.lastModified() = " + mDateFormat.format(file.lastModified()));

                bitmap = BitmapFactory.decodeFile(pathName);
                imageView.setImageBitmap(bitmap);
            } else {
                // 開啟線程加載圖片
                try {
                    AsyncBaseRequest asyncRequest = new AsyncHttpGet(url, null, null, new ResultCallback() {

                        @Override
                        public void onSuccess(Object obj) {
                            if (obj == null || !(obj instanceof InputStream)) {
                                System.out.println("Loading image return Object is null or not is InputStream.");
                                return;
                            }

                            try {
                                // 根據指定的壓縮比例,獲得合適的 Bitmap
                                Bitmap bitmap = BitmapUtil.decodeStream((InputStream) obj, imgInfo.getWidth(), imgInfo.getHeight());

                                if (imgInfo.isRounded()) {
                                    // 將圖片變成圓角
                                    bitmap = BitmapUtil.drawRoundBitmap(bitmap, 8);
                                }

                                if (imgInfo.isCompress()) {
                                    // 對 Bitmap 進行質量壓縮
                                    bitmap = BitmapUtil.compressBitmap(bitmap);
                                }

                                // 將 Bitmap 轉換成 ByteArrayInputStream
                                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                                ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());

                                // 將進行質量壓縮後的數據寫入文件(文件緩存)
                                fileCache.writeToFile(inStream, file);

                                // 存入內存緩存中
                                memoryCache.put(url, bitmap);

                                // 防止圖片錯位
                                String tag = imageViews.get(imageView);
                                if (tag == null || !tag.equals(url)) {
                                    System.out.println("tag is null or url and ImageView disaccord.");
                                    return;
                                }

                                // 用 ImageView 對象顯示圖片
                                final Bitmap btm = bitmap;
                                mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        imageView.setImageBitmap(btm);
                                    }
                                });

                            } catch (IOException e) {
                                // 這裡不做處理,因為默認顯示的圖片在 xml 組件配置裡已設置
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFail(int errorCode) {
                            System.out.println("Loading image error. errorCode = " + errorCode);
                        }
                    });

                    mDefaultThreadPool.execute(asyncRequest);
                    mAsyncRequests.add(asyncRequest);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

記憶體快取類 MemoryCache

package com.everyone.android.bitmap;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.graphics.Bitmap;
import android.util.Log;

/**
 * 功能描述:內存緩存類
 * @author android_ls
 */
public class MemoryCache {

    /** 打印 LOG 的 TAG */
    private static final String TAG = "MemoryCache";

    /**
     * 放入緩存時是個同步操作
     * LinkedHashMap 構造方法的最後一個參數 true 代表這個 map 裡的元素將按照最近使用次數由少到多排列,
     * 這樣的好處是如果要將緩存中的元素替換,則先遍歷出最近最少使用的元素來替換以提高效率
     */
    private Map<String, Bitmap> cacheMap = Collections.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));

    // 緩存只能占用的最大堆內存
    private long maxMemory;

    public MemoryCache() {
        // 使用 25% 的可用的堆大小
        maxMemory = Runtime.getRuntime().maxMemory() / 4;
        Log.i(TAG, "MemoryCache will use up to " + (maxMemory / 1024 / 1024) + "MB");
    }

    /**
     * 根據 key 獲取相應的圖片
     * @param key
     * @return Bitmap
     */
    public Bitmap get(String key) {
        if (!cacheMap.containsKey(key)) {
            return null;
        }
        return cacheMap.get(key);
    }

    /**
     * 添加圖片到緩存
     * @param key
     * @param bitmap
     */
    public synchronized void put(String key, Bitmap bitmap) {
        checkSize();
        cacheMap.put(key, bitmap);

        Log.i(TAG, "cache size=" + cacheMap.size() + " bitmap size = " + getBitmapSize(bitmap));
    }

    /**
     * 嚴格控制堆內存,如果超過將首先替換最近最少使用的那個圖片緩存
     */
    private void checkSize() {
        long count = 0;
        Iterator<Entry<String, Bitmap>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, Bitmap> entry = iterator.next();
            count += getBitmapSize(entry.getValue());
        }

        Log.i(TAG, "cache size=" + count + " length=" + cacheMap.size());

        if (count > maxMemory) {
            while (iterator.hasNext()) {
                Entry<String, Bitmap> entry = iterator.next();
                count -= getBitmapSize(entry.getValue());

                iterator.remove();
                if (count <= maxMemory) {
                    System.out.println("夠用了,不用在刪除了");
                    break;
                }
            }
            Log.i(TAG, "Clean cache. New size " + cacheMap.size());
        }
    }

    /**
     * 獲取 bitmap 的字節大小
     * @param bitmap
     * @return
     */
    private long getBitmapSize(Bitmap bitmap) {
        if (bitmap == null) {
            return 0;
        }
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    /**
     * 清空緩存
     */
    public void clear() {
        cacheMap.clear();
    }
}

這裡有兩個設計要點:一是用 LinkedHashMap(initialCapacity, loadFactor, true) 的第三個參數打開「存取順序」模式,讓 Map 自動變成 LRU 結構,淘汰時永遠從最久沒用到的元素下手;二是把快取上限設為可用堆的 25%,並在每次 put 前檢查總量,避免圖片快取把 App 的記憶體吃乾。

檔案快取類 FileCache

package com.everyone.android.bitmap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;

import android.content.Context;
import android.os.StatFs;

/**
 * 功能描述:網絡下載文件本地緩存類
 * @author android_ls
 */
public class FileCache {

    /** 本地與我們應用程序相關文件存放的根目錄 */
    private static final String ROOT_DIR_PATH = "CopyEveryone";

    /** 下載文件存放的目錄 */
    private static final String IMAGE_DOWNLOAD_CACHE_PATH = ROOT_DIR_PATH + "/Download/cache";

    /** 默認的磁盤緩存大小(20MB) */
    private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 20;

    /** 緩存文件存放目錄 */
    private File cacheDir;

    /** 緩存根目錄 */
    private String cacheRootDir;

    private Context mContext;

    public FileCache(Context context) {
        mContext = context;

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheRootDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            cacheRootDir = mContext.getCacheDir().getAbsolutePath();
        }

        cacheDir = new File(cacheRootDir + File.separator + IMAGE_DOWNLOAD_CACHE_PATH);
        // 檢測文件緩存目錄是否存在,不存在則創建
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    /**
     * 獲取下載的文件要存放的緩存目錄
     * /mnt/sdcard/CopyEveryone/Download/cache
     * @return 緩存目錄的全路徑
     */
    public String getCacheDirPath() {
        return cacheDir.getAbsolutePath();
    }

    /**
     * 根據 URL 從文件緩存中獲取文件
     * @param url url 的 hashCode 為緩存的名文件名
     */
    public File getFile(String url) {
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }

        String filename = String.valueOf(url.hashCode());
        File file = new File(cacheDir, filename);
        return file;
    }

    /**
     * 計算存儲可用的大小
     * @return
     */
    public long getAvailableMemorySize() {
        StatFs stat = new StatFs(cacheRootDir);
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 將指定的數據寫入文件
     * @param inputStream InputStream
     * @param file File
     * @throws IOException
     */
    public synchronized void writeToFile(InputStream inputStream, File file) throws IOException {
        int fileSize = inputStream.available();
        System.out.println("fileSize = " + fileSize);

        long enabledMemory = getAvailableMemorySize();
        System.out.println("當前可用硬盤: " + (enabledMemory / 1024 / 1024)); // 單位:MB

        // 當前可用存儲空間不足 20M
        if (DEFAULT_DISK_CACHE_SIZE > enabledMemory) {
            if (fileSize > enabledMemory) {
                // 檢測可用空間大小,若不夠用則刪除最早的文件
                File[] files = cacheDir.listFiles();
                Arrays.sort(files, new FileLastModifSort());

                int length = files.length;
                for (int i = 0; i < length; i++) {
                    files[i].delete();
                    length = files.length;

                    enabledMemory = getAvailableMemorySize();
                    System.out.println("當前可用內存: " + enabledMemory);

                    if (fileSize <= enabledMemory) {
                        System.out.println("夠用了,不用在刪除了");
                        break;
                    }
                }
            }
        } else {
            int count = 0;
            File[] files = cacheDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                count += files[i].length();
            }

            System.out.println("file cache size = " + count);

            // 使用的空間大於上限
            enabledMemory = DEFAULT_DISK_CACHE_SIZE - count;
            if (fileSize > enabledMemory) {
                Arrays.sort(files, new FileLastModifSort());

                int length = files.length;
                for (int i = 0; i < length; i++) {
                    count -= files[i].length();
                    files[i].delete();
                    length = files.length;

                    enabledMemory = DEFAULT_DISK_CACHE_SIZE - count;
                    if (fileSize <= enabledMemory) {
                        System.out.println("夠用了,不用在刪除了");
                        break;
                    }
                }
            }
        }

        if (enabledMemory == 0) {
            return;
        }

        // 將數據寫入文件保存
        FileOutputStream outStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.flush();
        outStream.close();
        inputStream.close();

        // 設置最後修改的時間
        long newModifiedTime = System.currentTimeMillis();
        file.setLastModified(newModifiedTime);

        System.out.println("file.length() = " + file.length());

        SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println("writeToFile file.lastModified() = " + mDateFormat.format(file.lastModified()));
    }

    /**
     * 根據文件的最後修改時間進行排序
     * @author android_ls
     */
    class FileLastModifSort implements Comparator<File> {
        public int compare(File file1, File file2) {
            if (file1.lastModified() > file2.lastModified()) {
                return 1;
            } else if (file1.lastModified() == file2.lastModified()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    /**
     * 清空緩存的文件
     */
    public void clear() {
        if (!cacheDir.exists()) {
            return;
        }

        File[] files = cacheDir.listFiles();
        if (files != null) {
            for (File f : files) {
                f.delete();
            }
        }
    }
}

檔案快取的重點有兩個:一是優先把快取寫到外部儲存空間,外部不可用時才退回 App 的內部 cache 目錄;二是寫入前先檢查剩餘空間,不夠就依「最後修改時間」由舊到新刪除。用 URL 的 hashCode 當檔名,則讓查找變成一次 O(1) 的判斷。

圖片資訊實體類 ImageInfo

package com.everyone.android.entity;

import android.widget.ImageView;

/**
 * 功能描述:圖片信息實體類
 * @author android_ls
 */
public class ImageInfo {

    private int id;             // 唯一標識

    private ImageView imageView; // 用於顯示的組件

    private String url;         // 網絡 URL

    private int width;          // 寬度

    private int height;         // 高度

    private boolean rounded;    // 是否要轉換成圓角

    private boolean compress;   // 是否要進行質量壓縮

    public ImageInfo(ImageView imageView, String url) {
        this.imageView = imageView;
        this.url = url;
    }

    public ImageInfo() {
    }

    public ImageInfo(ImageView imageView, String url, int width, int height, boolean rounded, boolean compress) {
        this.imageView = imageView;
        this.url = url;
        this.width = width;
        this.height = height;
        this.rounded = rounded;
        this.compress = compress;
    }

    public ImageInfo(ImageView imageView, String url, boolean rounded) {
        this.imageView = imageView;
        this.url = url;
        this.rounded = rounded;
    }

    public ImageInfo(ImageView imageView, String url, int width, int height) {
        this.imageView = imageView;
        this.url = url;
        this.width = width;
        this.height = height;
    }

    public ImageInfo(ImageView imageView, String url, int width, int height, boolean rounded) {
        this.imageView = imageView;
        this.url = url;
        this.width = width;
        this.height = height;
        this.rounded = rounded;
    }

    public boolean isCompress() {
        return compress;
    }

    public void setCompress(boolean compress) {
        this.compress = compress;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public ImageView getImageView() {
        return imageView;
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public boolean isRounded() {
        return rounded;
    }

    public void setRounded(boolean rounded) {
        this.rounded = rounded;
    }
}

Bitmap 加工處理工具類 BitmapUtil

package com.everyone.android.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
 * 功能描述:Bitmap 加工處理工具類
 * @author android_ls
 */
public class BitmapUtil {

    /**
     * 將圖片變成圓角(方法一)
     * @param bitmap Bitmap
     * @param pixels 圓角的弧度
     * @return 圓角圖片
     */
    public static Bitmap drawRoundBitmap(Bitmap bitmap, float pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        // paint.setColor() 的參數,除不能為 Color.TRANSPARENT 外,可以任意寫
        paint.setColor(Color.RED);
        canvas.drawRoundRect(rectF, pixels, pixels, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 將圖片變成圓角(方法二)
     * @param bitmap Bitmap
     * @param pixels 圓角的弧度
     * @return 圓角圖片
     */
    public static Bitmap drawRoundCorner(Bitmap bitmap, float pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        RectF outerRect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // paint.setColor() 的參數,除不能為 Color.TRANSPARENT 外,可以任意寫
        paint.setColor(Color.WHITE);
        canvas.drawRoundRect(outerRect, pixels, pixels, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        Drawable drawable = new BitmapDrawable(bitmap);
        drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
        canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
        drawable.draw(canvas);
        canvas.restore();

        return output;
    }

    /**
     * 對 Bitmap 進行質量壓縮
     * @param bitmap Bitmap
     * @return 壓縮後的 Bitmap
     */
    public static Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 圖片質量默認值為 100,表示不壓縮
        int quality = 100;
        // PNG 是無損的,將會忽略質量設置。因此,這裡設置為 JPEG
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);

        // 判斷壓縮後圖片的大小是否大於 100KB,大於則繼續壓縮
        while (outStream.toByteArray().length / 1024 > 100) {
            outStream.reset();

            // 壓縮 quality%,把壓縮後的數據存放到 baos 中
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
            quality -= 10;
        }

        System.out.println("quality = " + quality);

        byte[] data = outStream.toByteArray();
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    /**
     * 根據指定的壓縮比例,獲得合適的 Bitmap(方法一)
     * @param file File
     * @param width 指定的寬度
     * @param height 指定的高度
     * @return Bitmap
     */
    public static Bitmap decodeStream(File file, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), options);

        int w = options.outWidth;
        int h = options.outHeight;

        // 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
        int ratio = 1; // 默認為不縮放
        if (w >= h && w > width) {
            ratio = (int) (w / width);
        } else if (w < h && h > height) {
            ratio = (int) (h / height);
        }

        if (ratio <= 0) {
            ratio = 1;
        }

        System.out.println("圖片的縮放比例值 ratio = " + ratio);

        options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        // inSampleSize 表示縮略圖大小為原始圖片大小的幾分之一
        options.inSampleSize = ratio;

        return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    }

    /**
     * 根據指定的壓縮比例,獲得合適的 Bitmap(方法二)
     * @param inStream InputStream
     * @param width 指定的寬度
     * @param height 指定的高度
     * @return Bitmap
     * @throws IOException
     */
    public static Bitmap decodeStream(InputStream inStream, int width, int height) throws IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // 從輸入流讀取數據
        byte[] data = StreamTool.read(inStream);
        BitmapFactory.decodeByteArray(data, 0, data.length, options);

        int w = options.outWidth;
        int h = options.outHeight;

        int ratio = 1; // 默認為不縮放
        if (w >= h && w > width) {
            ratio = (int) (w / width);
        } else if (w < h && h > height) {
            ratio = (int) (h / height);
        }

        if (ratio <= 0) {
            ratio = 1;
        }

        System.out.println("圖片的縮放比例值 ratio = " + ratio);

        options.inJustDecodeBounds = false;
        options.inSampleSize = ratio;

        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    /**
     * 根據指定的壓縮比例,獲得合適的 Bitmap(會出錯的方法,僅用於測試)
     */
    public static Bitmap decodeStreamError(InputStream inStream, int width, int height) throws IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inStream, null, options);

        int w = options.outWidth;
        int h = options.outHeight;

        int ratio = 1; // 默認為不縮放
        if (w >= h && w > width) {
            ratio = (int) (w / width);
        } else if (w < h && h > height) {
            ratio = (int) (h / height);
        }

        if (ratio <= 0) {
            ratio = 1;
        }

        System.out.println("圖片的縮放比例值 ratio = " + ratio);

        options.inJustDecodeBounds = false;
        options.inSampleSize = ratio;

        return BitmapFactory.decodeStream(inStream, null, options);
    }
}

單位轉換工具類 DensityUtil

package com.everyone.android.utils;

import android.content.Context;

/**
 * 功能描述:單位轉換工具類
 * @author android_ls
 */
public class DensityUtil {

    /**
     * 將單位為 dip 的值轉換成單位為 px 的值
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 將單位為 px 的值轉換成單位為 dip 的值
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 將 px 值轉換為 sp 值,保證文字大小不變
     */
    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 將 sp 值轉換為 px 值,保證文字大小不變
     */
    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }
}

數據流處理工具類 StreamTool

package com.everyone.android.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述:數據流處理工具類
 * @author android_ls
 */
public final class StreamTool {

    /**
     * 從輸入流讀取數據
     * @param inStream
     * @return
     * @throws IOException
     */
    public static byte[] read(InputStream inStream) throws IOException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }
}

五、網路模組調整過的原始碼

網路請求執行緒基類 AsyncBaseRequest

package com.everyone.android.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.Map;

import org.json.JSONException;

import com.everyone.android.callback.ParseCallback;
import com.everyone.android.callback.ResultCallback;
import com.everyone.android.utils.Constant;
import com.everyone.android.utils.LogUtil;
import com.everyone.android.utils.StreamTool;

/**
 * 功能描述:網絡請求線程基類
 * @author android_ls
 */
public abstract class AsyncBaseRequest implements Runnable, Serializable {

    private static final long serialVersionUID = 1L;

    /** LOG 打印標簽 */
    private static final String TAG = "AsyncBaseRequest";

    /** 網絡連接超時,默認值為 5 秒 */
    protected int connectTimeout = 5 * 1000;

    /** 網絡數據讀取超時,默認值為 5 秒 */
    protected int readTimeout = 5 * 1000;

    private boolean interrupted;

    public boolean isInterrupted() {
        return interrupted;
    }

    public void setInterrupted(boolean interrupted) {
        this.interrupted = interrupted;
    }

    protected void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    protected void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    protected String requestUrl;

    protected Map<String, String> parameter;

    private ParseCallback parseHandler;

    private ResultCallback requestCallback;

    protected HttpURLConnection mHttpURLConn;

    protected InputStream mInStream;

    public AsyncBaseRequest(String url, Map<String, String> parameter, ParseCallback handler, ResultCallback requestCallback) {
        this.parseHandler = handler;
        this.requestUrl = url;
        this.parameter = parameter;
        this.requestCallback = requestCallback;
    }

    /**
     * 發送網絡請求
     * @return 網絡請求返回的 InputStream 數據流
     * @throws IOException
     */
    protected abstract InputStream getRequestResult() throws IOException;

    @Override
    public void run() {
        if (interrupted) {
            LogUtil.i(TAG, "訪問網絡前中斷業務處理線程(終止)");
            return;
        }

        try {
            mInStream = getRequestResult();
            if (mInStream != null) {
                if (interrupted) {
                    LogUtil.i(TAG, "讀取數據前中斷業務處理線程(終止)");
                    return;
                }

                Object obj = null;
                if (parseHandler != null) {
                    byte[] data = StreamTool.read(mInStream);
                    if (interrupted) {
                        LogUtil.i(TAG, "解析數據前中斷業務處理線程(終止)");
                        return;
                    }

                    String result = new String(data);
                    obj = parseHandler.parse(result);
                }

                if (interrupted) {
                    LogUtil.i(TAG, "刷新 UI 前中斷業務處理線程(終止)");
                    return;
                }

                if (obj != null) {
                    requestCallback.onSuccess(obj);
                } else {
                    requestCallback.onSuccess(mInStream);
                }

            } else {
                LogUtil.i(TAG, "get InputStream By HttpURLConnection return result is NULL.");
                requestCallback.onFail(Constant.NETWORK_REQUEST_RETUN_NULL); // 網絡請求返回 NULL
            }
        } catch (JSONException e) {
            requestCallback.onFail(Constant.NETWORK_REQUEST_RESULT_PARSE_ERROR); // 網絡請求返回結果解析出錯
            e.printStackTrace();
        } catch (IOException e) {
            requestCallback.onFail(Constant.NETWORK_REQUEST_IOEXCEPTION_CODE); // IO 異常標識
            e.printStackTrace();
        }
    }

    public HttpURLConnection getRequestConn() {
        return mHttpURLConn;
    }
}

這個基類有個實用的設計:在「訪問網路前、讀取資料前、解析資料前、刷新 UI 前」四個關鍵節點都插入了中斷檢查。當使用者離開頁面、需要取消一連串圖片請求時,就能及早短路,不必等整批下載跑完。

HTTP GET 請求 AsyncHttpGet

package com.everyone.android.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.protocol.HTTP;

import com.everyone.android.callback.ParseCallback;
import com.everyone.android.callback.ResultCallback;

/**
 * 功能描述:通過 HTTP 協議發送 GET 請求
 * @author android_ls
 */
public class AsyncHttpGet extends AsyncBaseRequest {

    private static final long serialVersionUID = 2L;

    public AsyncHttpGet(String url, Map<String, String> parameter, ParseCallback handler, ResultCallback requestCallback) throws IOException {
        super(url, parameter, handler, requestCallback);
    }

    @Override
    protected InputStream getRequestResult() throws IOException {
        StringBuilder sb = new StringBuilder(requestUrl);
        if (parameter != null && !parameter.isEmpty()) {
            sb.append('?');
            for (Map.Entry<String, String> entry : parameter.entrySet()) {
                sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), HTTP.UTF_8)).append('&');
            }
            sb.deleteCharAt(sb.length() - 1);
        }

        URL url = new URL(sb.toString());
        mHttpURLConn = (HttpURLConnection) url.openConnection();
        mHttpURLConn.setConnectTimeout(connectTimeout);
        mHttpURLConn.setRequestMethod("GET");
        if (mHttpURLConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return mHttpURLConn.getInputStream();
        }
        return null;
    }
}

六、運行結果

完成上述所有類別後執行 App,列表中的頭像便會依序經過記憶體快取、檔案快取與網路三層檢索;第二次進入同一頁時幾乎是瞬間呈現,這就是雙緩存帶來的體感差異。

轉自:https://blog.csdn.net/android_ls/article/details/8797740

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved