在 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` 而定 |
// 發送方:郵遞員 準備 信封
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");
}
}
`Bundle` 不綁定 `Intent`,廣泛用於:
| 維度 | Intent | Bundle |
|---|---|---|
| 核心目的 | 組件路由與啟動 | 資料封裝與序列化 |
| 能否單獨存在 | 是 (無 extras 也能啟動組件) | 是 (但需依附 Intent/Fragment/Message 等傳輸) |
| 資料容量限制 | 受 Binder 交易緩衝區限制 (~1MB),實際由 extras 決定 | 同受 Binder 限制,大資料建議用檔案/共享記憶體/ContentProvider |
| 序列化機制 | 依賴內部 Bundle 實現 Parcelable | 原生支援 Parcelable/Serializable |
掌握「郵遞員負責送達路徑,信封負責裝載內容」的本質關係,即可在複雜的 Android 組件通訊架構中遊刃有餘,避免將路由邏輯與資料邏輯耦合混淆。