java.lang.OutOfMemoryError 是 Android 開發中最令開發者頭疼的崩潰之一。本文從 JVM/Dalvik/ART 差異切入,系統梳理 7 大優化方向:對象生命週期控制、Bitmap 降採樣、VMRuntime 堆調優、軟引用緩存、資源流優化,並提供可直接落地的代碼片段。
// ❌ 錯誤:每次循環 new 對象
for (int i = 0; i < 1000; i++) {
String s = new String("item" + i);
list.add(s);
}
// ✅ 正確:複用對象或使用 StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.setLength(0);
sb.append("item").append(i);
list.add(sb.toString());
}
// 不再使用的大對象
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle(); // 立即釋放 Native 像素內存 (API < 21 有效)
bitmap = null;
}
// 列表清空
list.clear();
list = null;
public static Bitmap decodeSampledBitmap(File file, int reqWidth, int reqHeight) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);
opts.inJustDecodeBounds = false;
opts.inPreferredConfig = Bitmap.Config.RGB_565; // 節省 50% 內存
opts.inPurgeable = true; // API < 21 允許被回收
opts.inInputShareable = true;
return BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
}
private static int calculateInSampleSize(BitmapFactory.Options opts, int reqW, int reqH) {
int inSampleSize = 1;
if (opts.outHeight > reqH || opts.outWidth > reqW) {
int halfH = opts.outHeight / 2;
int halfW = opts.outWidth / 2;
while ((halfH / inSampleSize) >= reqH && (halfW / inSampleSize) >= reqW) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
// 在 Application.onCreate() 最早調用
private static final float TARGET_UTILIZATION = 0.75f;
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_UTILIZATION);
// 設置最小堆大小(如需預留 6MB)
VMRuntime.getRuntime().setMinimumHeapSize(6 * 1024 * 1024);
風險: 過大最小堆可能導致系統頻繁殺死後台進程,影響多任務體驗。
// 內存緩存:佔用最大可用內存 1/8
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
LruCache memoryCache = new LruCache(maxMemory / 8) {
@Override protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
磁盤緩存推薦使用 DiskLruCache 或成熟圖片庫內建方案。
// ❌ 直接文件流,易受路徑、權限影響
InputStream is = new FileInputStream(new File(path));
// ✅ 使用 Resources 打開 raw/assets 資源,系統優化過
InputStream is = context.getResources().openRawResource(R.raw.image);
接入 LeakCanary 自動檢測 Activity/Fragment/View 洩漏,針對堆疊信息修復靜態引用、未註冊監聽器、Handler 延遲消息等典型問題。
inSampleSize 降採樣Glide/Coil 自動管理生命週期onDestroy 統一解註冊adb shell dumpsys meminfo <pkg> 觀察 PSS 變化內存優化是系統工程,而非單點修補。建立「分配即負責、用畢即釋放」的團隊編碼規範,才是治本之道。