Android 記憶體洩漏本質是物件無法被垃圾回收器(GC)回收,導致堆積佔用記憶體,最終觸發 OutOfMemoryError。與標準 Java 不同,Android 的組件生命週期、系統服務註冊機制、有限記憶體環境使洩漏更嚴重且難以排查。
Android 系統服務(如 TelephonyManager、LocationManager、SensorManager、BroadcastReceiver、ContentObserver、RxJava 訂閱)會持有呼叫端的強引用。若在組件銷毀時未取消註冊,系統服務將永久持有該組件引用,導致整個 Activity/Context 無法回收。
// ❌ 錯誤範例:鎖屏介面監聽電話狀態未取消註冊
public class LockScreen extends View {
private PhoneStateListener phoneListener = new PhoneStateListener() {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
updateSignalUI(signalStrength);
}
};
public LockScreen(Context context) {
super(context);
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(phoneListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
// 缺少取消註冊!LockScreen 銷毀時 tm 仍持有 phoneListener 引用
}
}
// ✅ 正確範例:在 onDetachedFromWindow 或對應生命週期取消
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(phoneListener, PhoneStateListener.LISTEN_NONE); // 取消註冊
}
| 服務 | 註冊方法 | 取消方法 | 典型洩漏場景 |
|---|---|---|---|
| TelephonyManager | listen(listener, events) | listen(listener, LISTEN_NONE) | 鎖屏、通話記錄、信號監控 |
| LocationManager | requestLocationUpdates() | removeUpdates(listener) | 地圖、導航、打卡功能 |
| SensorManager | registerListener() | unregisterListener(listener) | 計步、遊戲控制、AR |
| BroadcastReceiver | registerReceiver() | unregisterReceiver(receiver) | 網路狀態、電量、開機完成 |
| ContentResolver | registerContentObserver() | unregisterContentObserver(observer) | 聯絡人、簡訊、設定變更監聽 |
| RxJava/流式庫 | subscribe() | dispose()/clear() | 網路請求、資料庫觀察、UI 事件 |
靜態集合(static List、static Map、static SparseArray)持有 Activity/View/Context 引用,且未在適當時機移除。
// ❌ 危險:靜態集合持有 Activity 引用
public class ImageLoader {
private static final Map cache = new HashMap<>();
private static final List pendingCallbacks = new ArrayList<>(); // 致命!
public static void loadImage(String url, Activity callback) {
pendingCallbacks.add(callback); // Activity 洩漏
}
}
// ✅ 正確:使用 WeakReference 或 Lifecycle 感知元件
public class ImageLoader {
private final LruCache memoryCache = new LruCache<>(maxSize);
// 使用 LifecycleObserver 或 WeakReference
}
Cursor、FileInputStream、FileOutputStream、SQLiteDatabase、Bitmap、OkHttp ResponseBody 等資源型物件持有原生記憶體或檔案描述符,僅設為 null 無法釋放底層資源。
// ❌ 錯誤:僅設為 null
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
// 使用 cursor...
cursor = null; // 底層 Cursor 物件未關閉,原生記憶體洩漏
// ✅ 正確:try-with-resources (Java 7+) 或 finally 關閉
try (Cursor cursor = db.rawQuery("SELECT * FROM users", null)) {
while (cursor.moveToNext()) { /* 處理資料 */ }
} // 自動關閉
// 或傳統寫法
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM users", null);
// 處理...
} finally {
if (cursor != null) cursor.close();
}
// 大圖片載入最佳實踐
public class BitmapUtils {
public static Bitmap decodeSampledBitmap(Resources res, int resId, int reqWidth, int reqHeight) {
// 1. 先解碼邊界資訊
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 2. 計算縮放比例
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 3. 實際解碼
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565; // 節省 50% 記憶體
return BitmapFactory.decodeResource(res, resId, options);
}
// 手動回收(僅在確定不再使用時)
public static void safeRecycle(Bitmap bitmap) {
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle(); // 釋放原生記憶體
bitmap = null; // 協助 GC
}
}
}
注意:Android 3.0+ Bitmap 像素資料放在 Java 堆,recycle() 效果有限;Android 8.0+ 建議使用 inBitmap 重用 Bitmap。
// ❌ 錯誤:每次都新建 View
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
// 綁定資料...
return view;
}
// ✅ 正確:重用 convertView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// 綁定資料
holder.bind(getItem(position));
return convertView;
}
static class ViewHolder {
TextView title, subtitle;
ImageView icon;
ViewHolder(View view) {
title = view.findViewById(R.id.title);
subtitle = view.findViewById(R.id.subtitle);
icon = view.findViewById(R.id.icon);
}
void bind(Item item) { /* 設定資料 */ }
}
// ❌ 洩漏:非靜態內部類別/匿名類別持有 Activity 引用
public class MainActivity extends Activity {
private Handler handler = new Handler() { // 匿名內部類別
@Override
public void handleMessage(Message msg) {
// 延遲訊息未處理完 Activity 銷毀 → 洩漏
}
};
private AsyncTask task = new AsyncTask<>() { // 非靜態內部類別
// 執行耗時任務,Activity 旋轉銷毀 → 洩漏
};
}
// ✅ 正確:靜態內部類別 + WeakReference
public class MainActivity extends Activity {
private static class SafeHandler extends Handler {
private final WeakReference activityRef;
SafeHandler(MainActivity activity) {
activityRef = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = activityRef.get();
if (activity != null) { /* 安全處理 */ }
}
}
private final SafeHandler handler = new SafeHandler(this);
// 使用 ViewModel + LiveData 替代 AsyncTask(已棄用)
}
HandlerLeak、StaticFieldLeak 等靜態分析// build.gradle 啟用 LeakCanary
debugImplementation "com.squareup.leakcanary:leakcanary-android:2.12"
releaseImplementation "com.squareup.leakcanary:leakcanary-android-no-op:2.12"
// Application 中安裝(LeakCanary 2.x 自動安裝,無需手動程式碼)
| 類別 | 原則 | 工具/模式 |
|---|---|---|
| 系統服務 | 註冊必配對取消,在對應生命週期 | LifecycleObserver, onDestroy/onStop |
| 靜態集合 | 避免持有 Context/View,用 WeakReference/LruCache | LruCache, WeakHashMap |
| 資源物件 | try-with-resources 或 finally 關閉 | AutoCloseable, useCloseable() |
| Bitmap | inSampleSize 縮放、inBitmap 重用、Glide/Picasso | 圖片載入庫 |
| 非靜態內部類 | 改為 static + WeakReference,或用 ViewModel/LiveData | ViewModel, LiveData, Coroutines |
| 監聽器/回調 | 生命週期感知移除,避免匿名類別持有外部引用 | Lifecycle, Disposable, CompositeDisposable |
registerXxx 是否有對應 unregisterXxx?