初學 Android 時最容易混淆:Bundle 裝數據,Intent 幹嘛用?其實關系很清晰:
// 1. 創建行李箱裝數據
Bundle bundle = new Bundle();
bundle.putString("name", "張三");
bundle.putInt("age", 25);
// 2. 創建物流單,把行李箱裝進去
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(bundle); // 或 intent.putExtra(key, value) 直接塞,內部自動建 Bundle
// 3. 發車
startActivity(intent);
// SecondActivity.onCreate()
Bundle bundle = getIntent().getExtras(); // 取出行李箱
if (bundle != null) {
String name = bundle.getString("name");
int age = bundle.getInt("age", 0); // 提供默認值防空
}
Intent.putExtra(key, value) 內部就是 if (extras == null) extras = new Bundle(); extras.putXxx(key, value);。兩者等價,Bundle 適合批量裝箱、跨方法傳遞、保存狀態 (onSaveInstanceState)。
| 屬性 | 作用 |
|---|---|
| Action | 動作類別,如 ACTION_VIEW、ACTION_SEND |
| Data (Uri) | 操作的數據地址,如 content://contacts/people/1 |
| Category | 組件分類,如 CATEGORY_LAUNCHER 顯示在桌面 |
| Type | MIME 類型,隱式意圖匹配用 |
| Flags | 啟動模式標記,如 FLAG_ACTIVITY_NEW_TASK |
| Component | 顯式指定目標組件類名 |
| Extras (Bundle) | 攜帶的業務數據 |
Bundle 是數據容器,Intent 是攜帶容器並描述「幹什麼、找誰、怎麼幹」的任務描述符。