首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 核心組件解析:Intent 與 Bundle 的「郵遞員與信封」關係

     編輯:程式設計疑難解答

在 Android 開發中,`Intent`(意圖)與 `Bundle`(包裹)是組件間通訊的雙子星。初學者常混淆兩者職責,資深開發者則用一句話精準比喻:「Intent 是郵遞員,Bundle 是信封。郵遞員可以用信封傳遞信息,也可以憑自己(內置的 Bundle)來傳遞信息。」

角色定位

組件核心職責關鍵特性
Intent (郵遞員) 負責**啟動組件**(Activity、Service、BroadcastReceiver)及**描述動作意圖** 攜帶 `action`、`data (Uri)`、`category`、`type` 等路由資訊;內部持有一個 `Bundle` (via `extras`) 存放額外資料
Bundle (信封) 純粹的**鍵值對資料容器**,序列化載體 支援基本型別、`String`、`Parcelable`、`Serializable`、`ArrayList` 等;生命週期隨攜帶它的 `Intent`/`Message`/`Fragment` 而定

啟動 Activity 時的協作流程

// 發送方:郵遞員 準備 信封
Intent intent = new Intent(this, TargetActivity.class); // 僱傭郵遞員,指定目的地
Bundle bundle = new Bundle(); // 準備信封
bundle.putString("key_name", "張三"); // 裝入信件
bundle.putInt("key_age", 25);
intent.putExtras(bundle); // 郵遞員攜帶信封 (或 intent.putExtra(...) 直接用內置信封)
startActivity(intent); // 郵遞員出發

// 接收方:拆閱信件
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras(); // 從郵遞員手中取出信封
    if (extras != null) {
        String name = extras.getString("key_name");
        int age = extras.getInt("key_age");
    }
}

「內置信封」vs「外部信封」

  • 內置信封:`Intent` 內部預設持有 `Bundle mExtras`。調用 `intent.putExtra("k", v)` 實際是向內置 `Bundle` 寫入。**適用於簡單、少量資料傳遞。**
  • 外部信封:自行 `new Bundle()` 填充後,透過 `intent.putExtras(bundle)` 或 `intent.replaceExtras(bundle)` 交給 `Intent`。**適用於預先組裝複雜資料結構、跨多處復用、或需完整替換資料包場景。**

進階場景:非 Activity 通訊

`Bundle` 不綁定 `Intent`,廣泛用於:

  • Fragment 參數傳遞:`setArguments(Bundle)` / `getArguments()`。
  • Message 機制:`msg.setData(Bundle)` / `msg.getData()` (Handler 線程間通訊)。
  • 狀態保存/恢復:`onSaveInstanceState(Bundle)` / `onRestoreInstanceState(Bundle)`。
  • App Widget / Notification PendingIntent 附帶資料。

核心區別速查表

維度IntentBundle
核心目的組件路由與啟動資料封裝與序列化
能否單獨存在是 (無 extras 也能啟動組件)是 (但需依附 Intent/Fragment/Message 等傳輸)
資料容量限制受 Binder 交易緩衝區限制 (~1MB),實際由 extras 決定同受 Binder 限制,大資料建議用檔案/共享記憶體/ContentProvider
序列化機制依賴內部 Bundle 實現 Parcelable原生支援 Parcelable/Serializable

掌握「郵遞員負責送達路徑,信封負責裝載內容」的本質關係,即可在複雜的 Android 組件通訊架構中遊刃有餘,避免將路由邏輯與資料邏輯耦合混淆。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved