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

Android Intent 用法總整理

編輯:關於 Android 程式設計

Intent 的角色

Intent 是 Android 中用來表達「啟動意圖」的物件。無論要啟動 Activity、Service,還是送出 Broadcast,都可以透過 Intent 封裝。它讓元件之間不必直接耦合,也能完成導向與資料傳遞。

Intent 常見屬性包含 Component、Action、Category、Data、Type、Extra 與 Flag。其中 Component 用於明確指定目標元件,Extra 則用於攜帶資料。

Component

若明確知道要啟動哪個 Activity,可以直接建立 Intent 並指定目標類別。

Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

被啟動的 Activity 可以用 getIntent 取得這個 Intent,再讀取其中的資料。

Action 與 Category

Action 是字串,用來描述要執行的動作。Category 則用來補充說明執行的環境。若在 AndroidManifest.xml 中為 Activity 設定 intent-filter,系統就能依 Action 與 Category 找到合適的元件。

intent.setAction("org.someaction.SOME_ACTION");
startActivity(intent);

這種寫法沒有指定具體 Activity,而是讓系統依 filter 決定要啟動哪一個。

Data 與 Type

Data 通常以 Uri 表示,例如網址、電話號碼或內容提供者 URI。

Uri uri = Uri.parse("https://3g.renren.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Type 則用來描述資料的 MIME 類型,常與 ACTION_SEND 搭配使用。

Extra

Intent 可以透過 Bundle 或 putExtra 攜帶鍵值資料。

intent.putExtra("user_name", "小明");
String name = getIntent().getStringExtra("user_name");

常用 Action

Android 內建許多 Action,例如 ACTION_MAIN 作為應用程式入口、ACTION_VIEW 用來檢視資料、ACTION_SEND 用來分享內容、ACTION_DIAL 用來開啟撥號面板。開發時可依需求選擇系統提供的常數,也能自行定義 Action。

使用 Intent 時,最需要注意的是 intent-filter 的設定。若 filter 中有多餘空白或筆誤,可能導致 Activity 無法被啟動。建議使用 IDE 工具協助產生與檢查設定。

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