編輯:關於 Android 程式設計
做過新聞、論壇、電商這類「以圖片為主」的 App,幾乎都會遇到同一個惡夢:清單滑到一半畫面忽然空白,接著應用程式被系統強制回收,Logcat 裡躺著一行 OutOfMemoryError。本文把這個問題的成因、常見解法,以及真正能解決問題的異步載入方案完整梳理一次。
Android 上的圖片以 Bitmap 形式存在記憶體中,佔用量約等於「像素寬 × 像素高 × 每像素位元組數」。一張 1000×1000 的 ARGB_8888 圖片,光是位圖本身就要吃掉約 4MB。而單一 App 可用的堆記憶體往往只有數十 MB,一張未經處理的大圖就足以把界面上其他物件一起拖下水;清單裡同時存在幾十上百張圖時,累積效應更是致命。
前兩項是必做的功課,但只能延後問題發生。當資料量放大到數百筆、使用者又快速滑動時,同步載入仍會在瞬間配置大量 Bitmap。真正讓應用程式穩定下來的,是第三項——異步載入,再搭配一層會被系統自動回收的快取。
實作完成後的效果如下:

範例拆成五個角色,職責清楚分工:
public class MainActivity extends Activity {
private ListView lv;
private MyAdapter adapter;
private ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
pd = new ProgressDialog(this);
pd.setTitle("載入菜單");
pd.setMessage("正在載入");
adapter = new MyAdapter(this);
new MyTask().execute("1");
}
public class MyTask extends AsyncTask<String, Void, List> {
protected void onPreExecute() { super.onPreExecute(); pd.show(); }
protected void onPostExecute(List result) {
super.onPostExecute(result);
adapter.setData(result);
lv.setAdapter(adapter);
pd.dismiss();
}
protected List doInBackground(String... params) {
String menuListStr = getListDishesInfo(params[0]);
return Utils.getInstance().parseMenusJSON(menuListStr);
}
}
private String getListDishesInfo(String sortId) {
String url = HttpUtil.BASE_URL + "servlet/MenuInfoServlet?sortId=" + sortId + "&flag=1";
return HttpUtil.queryStringForPost(url);
}
}
布局相當單純,一個 LinearLayout 包一個 ListView 即可:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<ListView android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
關鍵在 getView 裡只做兩件事:填文字、把 url 交給 ImageLoader。真正的解碼工作完全不在這裡發生。
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.listview_item, null);
viewHolder = new ViewHolder();
viewHolder.tv = (TextView) convertView.findViewById(R.id.item_tv);
viewHolder.iv = (ImageView) convertView.findViewById(R.id.item_iv);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv.setText(list.get(position).getDishes());
imageLoader.DisplayImage(list.get(position).getPicPath(), activity, viewHolder.iv);
return convertView;
}
DisplayImage 的邏輯是整個方案的靈魂:先查記憶體,命中就直接貼上;沒命中就把任務丟進佇列,同時先顯示一張佔位圖,讓使用者不會看到空白格。
public void DisplayImage(String url, Activity activity, ImageView imageView) {
imageViews.put(imageView, url); // 記錄這個 ImageView 該顯示誰
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView) {
// 同一個 ImageView 可能已被回收再用於其他項目,先清掉舊任務
picturesQueue.Clean(imageView);
PictureToLoad p = new PictureToLoad(url, imageView);
synchronized (picturesQueue.picturesToLoad) {
picturesQueue.picturesToLoad.push(p);
picturesQueue.picturesToLoad.notifyAll();
}
if (pictureLoaderThread.getState() == Thread.State.NEW) {
pictureLoaderThread.start();
}
}
工作執行緒的 run 方法用 wait/notify 達到「無事可做就睡、有事就醒」的效果,取到圖片後寫入記憶體快取,最後切回 UI 執行緒更新畫面:
public void run() {
try {
while (true) {
if (picturesQueue.picturesToLoad.size() == 0) {
synchronized (picturesQueue.picturesToLoad) {
picturesQueue.picturesToLoad.wait();
}
}
if (picturesQueue.picturesToLoad.size() != 0) {
PictureToLoad photoToLoad;
synchronized (picturesQueue.picturesToLoad) {
photoToLoad = picturesQueue.picturesToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
// 只有當 ImageView 仍指向同一個 url 時才更新,避免清單複用造成的錯位
String tag = imageViews.get(photoToLoad.imageView);
if (tag != null && tag.equals(photoToLoad.url)) {
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity activity = (Activity) photoToLoad.imageView.getContext();
activity.runOnUiThread(bd);
}
}
if (Thread.interrupted()) break;
}
} catch (InterruptedException e) {
// 允許執行緒在此平靜退出
}
}
真正省記憶體的地方在 decodeFile:第一趟只讀檔頭取得原始尺寸,不配置任何像素;算出 2 的冪倍 inSampleSize 後才做第二趟解碼。
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true; // 只讀邊界,不載入像素
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
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 必須是 2 的冪
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) { }
return null;
}
getBitmap 則負責「檔案快取優先,網路下載補位」,下載的同時順手落地成檔案,下次直接命中:
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);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
ImageUtil.CopyStream(is, os); // 邊寫檔,等於順便建立快取
os.close();
return decodeFile(f);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
檔案快取以 url 的 hashCode 當檔名,優先使用 SD 卡,沒有就退回應用程式私有目錄:
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "newnews");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists()) cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
return new File(cacheDir, filename);
}
public void clear() {
File[] files = cacheDir.listFiles();
for (File f : files) f.delete();
}
}
記憶體快取用 SoftReference 包裝 Bitmap。這是重點:當系統記憶體吃緊時,只有軟參考的物件會被回收器優先清掉,而不像硬引用那樣逼得整個 App 崩潰。
public class MemoryCache {
private HashMap cache = new HashMap();
public Bitmap get(String id) {
if (!cache.containsKey(id)) return null;
SoftReference ref = (SoftReference) cache.get(id);
return (Bitmap) ref.get();
}
public void put(String id, Bitmap bitmap) {
cache.put(id, new SoftReference(bitmap));
}
public void clear() { cache.clear(); }
}
最後是串流複製的小工具,用 1KB 緩衝區迴圈搬資料:
public class ImageUtil {
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) { }
}
}
把這幾層機制疊起來之後,即便清單裡有數百張網路圖片,記憶體曲線也會維持在一條平穩的水平線上,而不是一路爬升到崩潰。
Android開發學習之路:RxAndroid與Lambda的相遇
前面基本掌握了 RxJava 的簡單用法,接下來還有一個頗有意思的東西——Java 8 才引入的 Lambda。 一、在 Android Studio 下搭建 Lamb
Android TabHost 標籤頁的四種實作方式
Tab 標籤是 Android 早期常見的 UI 元件,核心類別是 TabHost。本文用四個由淺入深的例子把它的用法完整走一遍,最後再談談為什麼現在已經不建議使用它。
Volley 快速上手:發送 GET 請求並動態添加 apikey 等請求頭
最近在做一個 Android 新聞客戶端,收穫不少,順手把 Volley 取網絡數據的方式記錄下來。 Volley 是 Google I/O 2013 推出的網絡通信庫,
微信裡的影片怎麼存下來?透過瀏覽器下載的圖文教學
訂閱號上常有很好笑的短片,朋友圈裡也偶爾會出現值得留存的影片,但微信本身並沒有提供下載按鈕。想把它們存起來,得繞一小段路——借用瀏覽器就能完成。 下載微信影片的步驟 1.