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

自學 Android 筆記:Activity 裡的 Intent 到底怎麼用

編輯:關於 Android 程式設計

Intent 是什麼

Intent 的字面意思是「意圖」。在 Android 的設計裡,它被當成元件之間溝通的橋樑:一次操作要做什麼動作、涉及哪些資料、需要附帶什麼額外資訊,全部由 Intent 描述清楚;系統讀完這份描述後,會找出最合適的元件並把 Intent 遞交過去,完成呼叫。

它並不是跨應用才用得到的東西。同一個 App 內部 Activity 與 Service 之間的互動,一樣靠 Intent 串起來。理解它的最快方式,就是把 Intent 想成元件互相呼叫時所使用的「聯絡單」。

Intent 能啟動哪些元件

Activity:使用 startActivity()。

Service:使用 startService() 或 bindService()。

廣播:使用 sendBroadcast()、sendOrderedBroadcast()、sendStickyBroadcast()。

顯式 Intent 與隱式 Intent

Intent 最常被提到的分類就是這兩種,差別在於「有沒有指名要交給誰」。

顯式 Intent:呼叫 setComponent() 或 setClass(),明確指定目標元件。因為目標清楚,通常用來在自己應用的頁面之間跳轉與傳值。

隱式 Intent:不指定元件,只宣告想做的動作(action)、類別(category)與資料(URI 及型別)。系統會拿這些條件去比對所有已安裝的元件,挑出最適合的來處理。跨應用的操作,例如打電話、開相機、分享內容,大多走這條路。

實作:用隱式 Intent 打開系統相機

版面配置放一顆按鈕即可:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/opencamera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="打開照相機" />
</RelativeLayout>

程式碼的關鍵只有三行:建立 Intent、設定 action、加上預設 category,然後交給系統。

public class OpenCameraActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_opencamera);

        Button button = (Button) findViewById(R.id.opencamera);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(android.media.action.IMAGE_CAPTURE);
                intent.addCategory(android.intent.category.DEFAULT);
                startActivity(intent);
            }
        });
    }
}

這裡完全沒有提到目標元件,系統會自己找出裝置上的相機程式。如果某支 action 對應到多個 App,Android 會跳出選擇清單讓使用者挑,這正是隱式 Intent 的價值所在。

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