Android 開發看似簡單,實則暗藏無數坑。本文針對生產環境高頻 Crash 場景,深度解析 Cursor 生命週期、組件註冊遺漏、Parcelable 序列化三大核心陷阱,附帶防護代碼範本。
Cursor 是 SQLite 查詢結果的游標,誤用極易導致 NullPointerException、CursorIndexOutOfBoundsException 或記憶體洩漏。
// ❌ 危險:query 可能回傳 null
Cursor c = db.query(...);
c.moveToFirst(); // NPE
// ✅ 防護模式
Cursor c = db.query(...);
if (c != null) {
try {
if (c.moveToFirst()) {
// 安全處理
}
} finally {
c.close(); // 保證關閉
}
}
// ❌ 危險:getCount() == 0 時 moveToFirst() 回傳 false,後續取值拋異常
if (c != null && c.moveToFirst()) { ... }
// ✅ 正確:雙重檢查
if (c != null && c.getCount() > 0 && c.moveToFirst()) { ... }
// ❌ 危險:游標位置不確定
while (c.moveToNext()) { ... }
// ✅ 正確:先歸位
if (c.moveToFirst()) {
do {
// 處理當前行
} while (c.moveToNext());
}
Closeable,持有底層 SQLiteStatement 與視窗緩衝區SQLiteCursor 物件try-with-resources (API 19+) 或 finally 區塊強制 close()SQLite 無 Boolean 型別,INTEGER 儲存 0/1;Long/Int 混用會截斷。
// 安全取值模板
int intVal = c.getInt(c.getColumnIndexOrThrow("int_col"));
long longVal = c.getLong(c.getColumnIndexOrThrow("long_col"));
boolean boolVal = c.getInt(c.getColumnIndexOrThrow("bool_col")) == 1;
String strVal = c.getString(c.getColumnIndexOrThrow("str_col"));
| 組件 | 註冊位置 | 常見錯誤 | 後果 |
|---|---|---|---|
| Activity | <activity> | 拼寫錯誤、缺少匯出屬性 | ActivityNotFoundException |
| Service | <service> | 跨進程未指定 android:process、Package 名不一致 | Service 不啟動、ANR |
| BroadcastReceiver | <receiver> 或動態註冊 | 靜態註冊缺少 android:exported (Android 12+ 強制) | 接收不到廣播、SecurityException |
| ContentProvider | <provider> | authorities 衝突、未設 android:grantUriPermissions | 跨應用存取失敗 |
<service
android:name=".remote.RemoteService"
android:process=":remote"
android:exported="true">
<intent-filter>
<action android:name="com.example.ACTION_REMOTE"/>
</intent-filter>
</service>
Parcelable 比 Serializable 高效,但手寫代碼極易出錯。
// ❌ 危險:內部類隱含外部類引用
public class Wrapper {
public class Inner implements Parcelable { ... }
}
// ✅ 正確:static 內部類或獨立類
public static class Inner implements Parcelable { ... }
TransactionTooLargeExceptionBitmap.compress() 壓縮後存 byte[]// 寫入順序必須與讀取順序完全一致
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeLong(timestamp);
}
protected Model(Parcel in) {
id = in.readInt();
name = in.readString();
timestamp = in.readLong(); // 順序錯誤會導致資料錯亂
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
@Override public Model createFromParcel(Parcel in) { return new Model(in); }
@Override public Model[] newArray(int size) { return new Model[size]; }
};
try-finally 或 use { close() } 中android:exported@Parcelize (Kotlin) 或 AS 插件自動生成,人工檢查順序StrictMode 檢測 Cursor 洩漏將這三大陷阱內化為編碼習慣,能消除 90% 以上的基礎 Crash,讓你專注於業務邏輯創新。