編輯:Android 開發實例
關於網路資源載入的文章不少,基本思路都是「執行緒 + 緩存」。本文在這個骨架上做了幾點優化:
public class MemoryCache {
private static final String TAG = "MemoryCache";
// 放入緩存時是同步操作。
// LinkedHashMap 的最後一個參數 true 代表元素依最近使用次數由少到多排列(LRU),
// 如此一來需要淘汰時,直接遍歷開頭即可拿到最久未使用的項目。
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// 緩存中圖片所占用的位元組數,初始為 0
private long size = 0; // current allocated size
private long limit = 1000000; // max memory in bytes
public MemoryCache() {
// 使用可用堆的 25%
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id)) {
return null;
}
return cache.get(id);
} catch (NullPointerException ex) {
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id)) {
size -= getSizeInBytes(cache.get(id));
}
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
/**
* 嚴格控制堆記憶體,超標時先淘汰最近最少使用的那張
*/
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit) {
break;
}
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
/** 圖片占用的記憶體 */
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null) {
return 0;
}
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
寫成 SoftReference 版本程式碼會短很多:
public class MemoryCache {
private Map<String, SoftReference<Bitmap>> cache = Collections
.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
public Bitmap get(String id) {
if (!cache.containsKey(id)) {
return null;
}
SoftReference<Bitmap> ref = cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap) {
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
public void clear() {
cache.clear();
}
}
但我更推薦上面的 LRU 版本。差別在於 SoftReference 的回收時機由 GC 決定,你無法預期它何時被清掉,也可能在關鍵時刻突然全部失效;而自行計量 hit 的方式行為可預期,也便於除錯。
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// 有 SD 卡就在 SD 卡建立 LazyList 目錄存放緩存檔案,
// 沒有則退回系統的應用程式緩存目錄
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(), "LazyList");
} else {
cacheDir = context.getCacheDir();
}
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
public File getFile(String url) {
// 以 url 的 hashCode 作為檔名
String filename = String.valueOf(url.hashCode());
// 另一種做法:String filename = URLEncoder.encode(url);
return new File(cacheDir, filename);
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null) {
return;
}
for (File f : files) {
f.delete();
}
}
}
用 hashCode 當檔名的缺點是理論上存在碰撞風險,實務上若要更穩妥,可改用 URL 的 MD5 或 SHA-1 摘要。
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
// 執行緒池
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// 進入 listview 時的預設佔位圖,可替換成自己的資源
final int stub_id = R.drawable.stub;
/** 最主要的對外方法 */
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
// 先查記憶體緩存
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
// 沒有就開執行緒載入,並先顯示佔位圖
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// 先查檔案緩存
Bitmap b = decodeFile(f);
if (b != null) {
return b;
}
// 最後才從網路下載
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
return decodeFile(f);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// 解碼並按比例縮放以降低記憶體消耗;
// 虛擬機對單張圖片的可配置記憶體也是有限制的
private Bitmap decodeFile(File f) {
try {
// 先只讀取尺寸
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// 找出合適的縮放值,必須是 2 的次方
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// 帶著 inSampleSize 重新解碼
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// 佇列中的工作項目
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad)) {
return;
}
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// 更新 UI 必須回到 UI 執行緒
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
/**
* 防止圖片錯位(ListView 回收再利用導致的張冠李戴)
*/
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url)) {
return true;
}
return false;
}
// 在 UI 執行緒中更新介面
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
} else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
}
先查記憶體緩存 → 命中則直接顯示;未命中則丟進執行緒池,先查檔案緩存 → 仍未命中才從網路下載並寫檔 → 解碼縮放 → 最後切回 UI 執行緒更新:
a.runOnUiThread(...);
使用方式很簡單:
ImageLoader imageLoader = new ImageLoader(context); // ... imageLoader.DisplayImage(url, imageView);
最典型的掛載點是 ListView 的 getView(),GridView 也同樣適用。
imageViewReused 為什麼必要。ListView 會回收並重複使用 item 檢視。若使用者快速滾動,A 位置的請求可能還在飛行中,此時那個 ImageView 已經被拿去顯示 B 的內容,直接 setImageBitmap 就會造成圖文不符。用 WeakHashMap 記錄「這個 ImageView 目前應該顯示哪個 url」,回來時比對一次即可攔下過期結果。
兩次解碼的技巧。inJustDecodeBounds = true 讓 BitmapFactory 只讀取檔案標頭取得尺寸而不真正配置像素記憶體,算出 inSampleSize 後再正式解碼。這是控制 OOM 最有效的單一手段。
連線一定要關閉。範例中 HttpURLConnection 沒有 disconnect,實作時應補上並改用 try-with-resources 管理串流。
最後要補充的是時代背景:這套自行打造的分層緩存,正是今日 Glide、Fresco、Picasso 等函式庫在做的事,而且它們處理得更完整——包含請求取消、生命週期綁定、多種快取政策、進度回報與資源 reuse。新專案沒有必要重造這個輪子;理解本文的原理,是為了在函式庫行為不如預期時知道該往哪裡查。
Android 網絡通信案例:HttpURLConnection、HttpClient 與 Socket 三種路線比較
因為專案需要,我把 Android 的網絡通信方式整理了一遍,整體思路與 Java 平台相當接近。 Android 平台提供了多組 API 供開發者選用: 無論走哪一
Android 計時器實作:用秒數自行換算時分秒格式
需求很簡單:介面預設顯示「00:00:00」,按下開始鍵後先歸零再重新計時,讓數字像 10:28:34 這樣持續遞增,按下停止鍵則暫停計時。然而實作過程卻意外棘手。若採用
Android SQLite 增刪改查實戰:Person 模組逐層拆解
理論看再多,不如把一個完整的小模組從頭寫一遍。以下以「Person(聯絡人)」為例,依 Android 建議的分層方式拆成四個部分:實體類、資料庫 Helper、業務邏輯
Android 多媒體播放:MediaPlayer 類別與自製播放器的建置流程
Android 在音訊與影片播放上提供了不少 API,而 MediaPlayer 是最常被直接使用的一個。它把底層播放服務包成單一物件,讓你透過幾個方法就能控制播放、暫停