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

Android Intent 與 Bundle 關系圖解:誰裝數據、誰負責傳輸?

     編輯:程式設計綜合問答

初學 Android 時最容易混淆:Bundle 裝數據,Intent 幹嘛用?其實關系很清晰:

核心隱喻

  • Bundle = 行李箱:專門裝載鍵值對數據(基本類型、String、Parcelable、Serializable)。
  • 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?

Intent.putExtra(key, value) 內部就是 if (extras == null) extras = new Bundle(); extras.putXxx(key, value);。兩者等價,Bundle 適合批量裝箱、跨方法傳遞、保存狀態 (onSaveInstanceState)。

進階:Intent 還攜帶什麼「元數據」?

屬性作用
Action動作類別,如 ACTION_VIEW、ACTION_SEND
Data (Uri)操作的數據地址,如 content://contacts/people/1
Category組件分類,如 CATEGORY_LAUNCHER 顯示在桌面
TypeMIME 類型,隱式意圖匹配用
Flags啟動模式標記,如 FLAG_ACTIVITY_NEW_TASK
Component顯式指定目標組件類名
Extras (Bundle)攜帶的業務數據

一句話記住

Bundle 是數據容器,Intent 是攜帶容器並描述「幹什麼、找誰、怎麼幹」的任務描述符。

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