編輯:Android 開發實例
近來處理了一些內存洩露問題,過程中我特別注意到:反而是最「理所當然」的基本功最容易被忽略——靜態變量、Cursor 未關閉、線程、定時器、忘記反註冊、Bitmap 等等。
這些名詞講起來都很籠統,所以接下來我會逐項貼出實例代碼,在具體場景中找出洩露的根本原因並給出解法。第一篇就從 Cursor 開始。
Cursor cursor = db.query(); List<String> list = convertToList(cursor); cursor.close();
這是最簡單的用法,忘記關閉大概會被罵到臭頭。但真實場景往往沒這麼理想,至少有兩種情況會導致 Cursor 沒被關掉。
1. cursor.close() 之前就拋出異常了。
2. Cursor 還要繼續使用、不能立刻關閉,而後面忘了關。
這是初學者最常碰到的:
try {
Cursor c = queryCursor();
int a = c.getInt(1);
...... // 這裡一旦出錯,後面的 close() 就不會執行
c.close();
} catch (Exception e) {
}
正確寫法是把 close 放進 finally:
Cursor c = null;
try {
c = queryCursor();
int a = c.getInt(1);
......
} catch (Exception e) {
} finally {
if (c != null) {
c.close();
}
}
很簡單,但需要時刻記得。如果你使用的 SDK 支援 try-with-resources(Android 上需 API 19 且 Cursor 實作 AutoCloseable 的情況有限),也可考慮改用 that 語法。
這種情況確實存在,CursorAdapter 就是最典型的例子:
mCursor = getContentResolver().query(CONTENT_URI, PROJECTION, null, null, null); mAdapter = new MyCursorAdapter(this, R.layout.list_item, mCursor); setListAdapter(mAdapter); // 這裡不能 mCursor.close(),否則列表會變成空白
答案是:在 Cursor 不再被使用時關閉。以本例來說,通常每次進入或 resume 時才需要重新查詢——畢竟很少有需要「看不見畫面時還持續更新查詢結果」的需求(若真有,記得最終仍要關掉)。
因此一般可以在 onStop() 中收尾:
@Override
protected void onStop() {
super.onStop();
// changeCursor(null) 會釋放先前的 cursor,等效於關閉
mCursorAdapter.changeCursor(null);
}
附上 CursorAdapter 的源碼,讓大家看清楚 changeCursor(null) 為何能達到關閉效果:
/**
* Change the underlying cursor to a new cursor. If there is an existing
* cursor it will be closed.
*/
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close(); // 舊的 cursor 就在這裡被關閉
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike changeCursor(),
* the returned old Cursor is NOT closed.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
Cursor oldCursor = mCursor;
if (oldCursor != null) {
if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (newCursor != null) {
if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
notifyDataSetChanged();
} else {
mRowIDColumn = -1;
mDataValid = false;
notifyDataSetInvalidated();
}
return oldCursor;
}
差別很明確:swapCursor() 只換不關,changeCursor() 換完順手把舊的關掉。所以傳 null 給 changeCursor(),效果就是關閉。
AsyncQueryHandler 是分析 Cursor 洩露最經典的案例,不但一針見血、能舉一反三,而且非常常見。
文件參考:
https://developer.android.com/reference/android/content/AsyncQueryHandler.html
下面是 Android 2.3 系統中 Mms 主頁面 ConversationList 源碼的一部分,看看 Cursor 關對了嗎:
private final class ThreadListQueryHandler extends AsyncQueryHandler {
public ThreadListQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
case THREAD_LIST_QUERY_TOKEN:
mListAdapter.changeCursor(cursor);
setTitle(mTitle);
break;
case HAVE_LOCKED_MESSAGES_TOKEN:
long threadId = (Long) cookie;
confirmDeleteThreadDialog(
new DeleteThreadListener(threadId, mQueryHandler,
ConversationList.this),
threadId == -1,
cursor != null && cursor.getCount() > 0,
ConversationList.this);
break; // 注意:這裡沒有關閉 cursor
default:
Log.e(TAG, "onQueryComplete called with unknown token " + token);
}
}
}
@Override
protected void onStop() {
super.onStop();
mListAdapter.changeCursor(null);
}
1. THREAD_LIST_QUERY_TOKEN:cursor 被交給了 mListAdapter,而 mListAdapter 在 onStop() 中呼叫 changeCursor(null)。使用者離開 Activity 時,這個 Cursor 被正確釋放,不會洩露。
2. HAVE_LOCKED_MESSAGES_TOKEN:cursor 只用來當一個「有沒有資料」的判斷條件,用完之後既沒交給誰,也沒關掉——洩露。
在 StrictMode 監控下,只要跑到這一段就會拋出:
E/StrictMode(639): A resource was acquired at attached stack trace but never released. E/StrictMode(639): java.lang.Throwable: Explicit termination method 'close' not called E/StrictMode(639): at dalvik.system.CloseGuard.open(CloseGuard.java:184)
在 Android 4.0 JellyBean 中,這個洩露被修正了:
private final class ThreadListQueryHandler extends ConversationQueryHandler {
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
case THREAD_LIST_QUERY_TOKEN:
mListAdapter.changeCursor(cursor);
break;
case UNREAD_THREADS_QUERY_TOKEN:
int count = 0;
if (cursor != null) {
count = cursor.getCount();
cursor.close(); // 用目的就是取 count,取完立刻關
}
mUnreadConvCount.setText(count > 0 ? Integer.toString(count) : null);
break;
case HAVE_LOCKED_MESSAGES_TOKEN:
Collection<Long> threadIds = (Collection<Long>) cookie;
confirmDeleteThreadDialog(
new DeleteThreadListener(threadIds, mQueryHandler,
ConversationList.this),
threadIds,
cursor != null && cursor.getCount() > 0,
ConversationList.this);
if (cursor != null) {
cursor.close(); // 補上這一段
}
break;
default:
Log.e(TAG, "onQueryComplete called with unknown token " + token);
}
}
}
連 Google 自己在早期版本裡都寫錯了,更何況平時沒那麼仔細的我們。網路上大量 AsyncQueryHandler 的教學範例其實都犯了同樣的錯。看完這篇之後,再遇到後台 StrictMode 報「cursor not close」,應該就知道該往哪裡找了。
Cursor 未關閉的情境遠不止這幾種,但根本原則只有一句:不再使用時,就要及時且正確地關閉。判斷的關鍵在於「這個 Cursor 的擁有權交給了誰」——如果交給了 Adapter,就由 Adapter 負責;如果只是自己臨時用來取個 count,那就在取完的當下關掉。
把複雜的問題還原成本質,事情其實很簡單。
Eclipse 中 aapt.exe 停止工作的排查方式
問題現象 在 Eclipse 開發 Android 專案時,若版面配置或 XML 檔有錯誤,可能會突然出現 aapt.exe 停止工作的提示。這類錯誤不一定伴隨明確訊息,
Android 應用國際化入門:依地區切換字串資源
國際化應用的第一步,是把畫面文字從程式碼中抽出,改放進資源檔。這樣一來,新增語言時不必修改程式邏輯。 資源資料夾命名 Android 使用 values 加上語言代碼的方
Android 載入 Spinner 進度轉圈動畫教學
在 Android 中,想向使用者呈現某項工作正在進行,可以透過進度條來表達。進度條大致分成兩種樣式:一種是帶有進度的水平進度列,另一種則是不斷旋轉的載入轉圈(Spinn
修正圖片方向:讀取 EXIF 資訊並自動旋轉顯示
用 ImageView 顯示從相機或網路取得的照片時,常會遇到一個惱人的狀況:圖是對的,方向卻歪了,甚至有時候整個倒過來。這不是你的 Bitmap 出了問題,而是方向資訊