Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Intent 元件呼叫指南:顯式與隱式 Intent 的差異

編輯:關於 Android 程式設計

Intent 的作用

Intent 是 Android 元件之間溝通的核心,可用來啟動 Activity、Service,或傳送 Broadcast。它既能明確指定目標元件,也能描述想要執行的動作。

顯式 Intent

若直接指定要啟動的類別,例如 new Intent(this, TargetActivity.class),就是顯式 Intent。Android 會直接啟動該元件,忽略 action、category 與 data 的額外比對。

隱式 Intent

若只宣告 action,例如 ACTION_VIEW,Android 會在系統中尋找能處理此動作的 Activity。例如:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.baidu.com"));
startActivity(intent);

這會開啟可處理網址的瀏覽器。

intent-filter 與比對條件

Activity 可在 AndroidManifest.xml 中透過 intent-filter 宣告可處理的 action、category 與 data。若有多個 Activity 符合,系統會讓使用者選擇。

隱式 Intent 的比對條件包含 action、category、data 中的 host、path、scheme、mimeType 等。若要被隱式 Intent 匹配,通常必須包含 DEFAULT category。

傳遞資料:Serializable 與 Parcelable

Intent 可透過 Bundle 傳遞基本型別或物件。常見做法有兩種:

  • Serializable:實作簡單,但序列化依賴反射,效能較低。
  • Parcelable:需實作 writeToParcel 與 createFromParcel,效能較佳,適合大量資料或高頻傳遞。

效能示意:

一般小量資料可用 Serializable;若注重效能或傳遞較大物件,建議優先使用 Parcelable。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved