萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 開發高頻踩坑指南:Cursor、組件註冊、Parcelable 三大核心陷阱

Android 開發看似簡單,實則暗藏無數坑。本文針對生產環境高頻 Crash 場景,深度解析 Cursor 生命週期、組件註冊遺漏、Parcelable 序列化三大核心陷阱,附帶防護代碼範本。

陷阱一:Cursor 操作的五大死穴

Cursor 是 SQLite 查詢結果的游標,誤用極易導致 NullPointerException、CursorIndexOutOfBoundsException 或記憶體洩漏。

1. 未判空直接使用

// ❌ 危險:query 可能回傳 null
Cursor c = db.query(...);
c.moveToFirst(); // NPE

// ✅ 防護模式
Cursor c = db.query(...);
if (c != null) {
    try {
        if (c.moveToFirst()) {
            // 安全處理
        }
    } finally {
        c.close(); // 保證關閉
    }
}

2. 忽略零資料集

// ❌ 危險:getCount() == 0 時 moveToFirst() 回傳 false,後續取值拋異常
if (c != null && c.moveToFirst()) { ... }

// ✅ 正確:雙重檢查
if (c != null && c.getCount() > 0 && c.moveToFirst()) { ... }

3. 遍歷前未重置游標位置

// ❌ 危險:游標位置不確定
while (c.moveToNext()) { ... }

// ✅ 正確:先歸位
if (c.moveToFirst()) {
    do {
        // 處理當前行
    } while (c.moveToNext());
}

4. 忘記關閉導致記憶體洩漏

  • Cursor 實作 Closeable,持有底層 SQLiteStatement 與視窗緩衝區
  • Activity 銷毀時未關閉會洩漏 SQLiteCursor 物件
  • 最佳實踐:try-with-resources (API 19+) 或 finally 區塊強制 close()

5. 型別轉換錯誤

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 註冊範本

<service
    android:name=".remote.RemoteService"
    android:process=":remote"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.ACTION_REMOTE"/>
    </intent-filter>
</service>

陷阱三:Parcelable 序列化陷阱

Parcelable 比 Serializable 高效,但手寫代碼極易出錯。

1. 內部類非 static 導致外部類引用序列化失敗

// ❌ 危險:內部類隱含外部類引用
public class Wrapper {
    public class Inner implements Parcelable { ... }
}

// ✅ 正確:static 內部類或獨立類
public static class Inner implements Parcelable { ... }

2. Bitmap 等大物件直接寫入 Parcel

  • Parcel 單次傳輸限制 ~1MB,Bitmap 極易超限導致 TransactionTooLargeException
  • 方案:存檔案/快取路徑,Parcel 傳路徑字串;或用 Bitmap.compress() 壓縮後存 byte[]

3. 讀寫順序不一致

// 寫入順序必須與讀取順序完全一致
@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(); // 順序錯誤會導致資料錯亂
}

4. CREATOR 靜態常數缺失

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]; }
};

防坑檢查清單

  • [ ] 所有 Cursor 操作包裝在 try-finally 或 use { close() } 中
  • [ ] Manifest 所有組件完整註冊,Android 12+ 明確聲明 android:exported
  • [ ] Parcelable 類別用 @Parcelize (Kotlin) 或 AS 插件自動生成,人工檢查順序
  • [ ] 大型物件(Bitmap、大陣列)禁止直接進 Parcel
  • [ ] 釋出前用 StrictMode 檢測 Cursor 洩漏

將這三大陷阱內化為編碼習慣,能消除 90% 以上的基礎 Crash,讓你專注於業務邏輯創新。

copyright © 萬盛學電腦網 all rights reserved