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

Android 學習筆記(三):Intent 意圖完整解析

編輯:關於 Android 程式設計

前面的文章我們介紹了 Activity,不過相信不少朋友還覺得意猶未盡。所以這次我們來認識 Android 的「信使」——Intent,它能夠在不同元件之間傳遞訊息、彼此溝通。本文仍延續前面的範例基礎做修改,避免鋪陳過多無關內容;如果還沒看過前一篇 Activity 的介紹,建議先補一下再回來。

一、顯式 Intent 的基本用法

首先在原本的 ActivityTest 專案裡新增一個名為 second_layout.xml 的布局檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button 2" />
</LinearLayout>

接著建立一個新的活動 SecondActivity:

package com.wj.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.second_layout);
    }
}

別忘了到 AndroidManifest.xml 中註冊這個活動。完成後,改寫 FirstActivity 中的按鈕事件,用顯式 Intent 直接指定要啟動的目標類別:

button1.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // 顯式 Intent:明確指定要啟動的目標活動
        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
    }
});

Intent 有多個建構子,這裡使用的這一個接收兩個參數:第一個是啟動活動所需的上下文 Context,第二個則是指定要啟動的目標活動 Class。透過 startActivity(intent) 便能跳轉到 SecondActivity。

所謂顯式 Intent,是因為我們明確指明了要跳轉到哪一個類別。接下來看看隱式 Intent 怎麼用。

二、隱式 Intent 與意圖過濾器

隱式 Intent 不直接指定元件名稱,而是宣告一組 action 與 category,交由系統去尋找最合適的元件來處理。首先要在 SecondActivity 的 <intent-filter> 中配置可回應的 action 與 category:

<intent-filter>
    <action android:name="com.wj.test.activitytest.ACTION_START" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

這裡的 android:name 可以自訂,只要在建立 Intent 時字串保持一致即可。action 標籤說明當前活動能回應的動作,category 則提供更精確的附加資訊。只有當 Intent 中指定的 action 與 category 同時與過濾器匹配,活動才會被觸發。

然後改寫按鈕事件,改用隱式 Intent:

button1.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // 使用隱式 Intent,直接傳入 action 字串
        Intent intent = new Intent("com.wj.test.activitytest.ACTION_START");
        startActivity(intent);
    }
});

android.intent.category.DEFAULT 是一種預設 category,在呼叫 startActivity 時系統會自動將它加入 Intent。要特別注意的是:每個 Intent 只能指定一個 action,但可以指定多個 category。

如果我們加上自訂的 category:

Intent intent = new Intent("com.wj.test.activitytest.ACTION_START");
intent.addCategory("com.wj.activitytest.MY_CATEGORY");
startActivity(intent);

此時若 SecondActivity 的過濾器中沒有宣告這個 category,程式就會崩潰並拋出 ActivityNotFoundException。解法很簡單,把 category 一併宣告進去即可:

<intent-filter>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="com.wj.activitytest.MY_CATEGORY"/>
</intent-filter>

三、更多隱式 Intent 的應用

透過系統內建的 action,隱式 Intent 能實現許多實用功能。例如用系統瀏覽器打開網頁:

// 指定 ACTION_VIEW,並透過 Uri.parse 將網址字串解析為 Uri 物件
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.baidu.com"));
startActivity(intent);

與此對應,<intent-filter> 中還可以透過 <data> 標籤更精確地描述能處理的資料型別,主要包含:

· android:scheme:指定資料的協議部分,如 http
· android:host:指定主機名,如 www.baidu.com
· android:port:指定連接埠
· android:path:指定主機名與連接埠之後的路徑部分
· android:mimeType:指定可處理的資料類型,支援萬用字元

只有當 <data> 標籤指定的內容與 Intent 攜帶的 Data 完全一致時,該活動才能回應。例如新增一個 ThirdActivity,讓它也能回應打開網頁的 Intent,其過濾器可寫成:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:scheme="http"/>
</intent-filter>

如此一來,ThirdActivity 就像瀏覽器一樣能回應打開網頁的 Intent,點擊時系統會跳出選擇提示。

同樣的,撥打電話也可以交給 Intent 處理:

Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);

四、在活動之間傳遞數據

Intent 除了啟動元件,還能在活動之間傳遞資料。

1. 向下一個活動傳遞數據

Intent 提供了一系列 putExtra() 重載方法,可將資料暫存在 Intent 中:

String data = "Hello SecondActivity";
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("extra_data", data);
startActivity(intent);

putExtra() 的第一個參數是鍵(key),第二個才是真正的資料。在 SecondActivity 中,透過 getIntent() 取得 Intent,再用 getStringExtra() 傳入對應的鍵即可取出資料:

Intent intent = getIntent();
String data = intent.getStringExtra("extra_data");
Log.d("SecondActivity", data);

2. 返回數據給上一個活動

若要將結果回傳,出發的活動需改用 startActivityForResult():

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
// 第二個參數是請求碼,用於後續回調中辨識資料來源
startActivityForResult(intent, 1);

在 SecondActivity 中,透過 setResult() 攜帶回傳資料並關閉當前活動:

Intent intent = new Intent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();

最後在 FirstActivity 重寫 onActivityResult() 接收結果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                String returnedData = data.getStringExtra("data_return");
                Log.d("FirstActivity", returnedData);
            }
            break;
        default: break;
    }
}

執行後點擊 button1 再點擊 button2,Log 便會輸出 Hello FirstActivity。需要注意的是,若在同一活動中多次呼叫 startActivityForResult() 啟動不同活動,每個活動返回時都會觸發 onActivityResult(),因此要透過 requestCode 加以區分。

如果不點擊 button2 而是按返回鍵,只要重寫 SecondActivity 的 onBackPressed() 方法,同樣能攜帶資料返回。

總結來說,Intent 就像意圖與信使的結合:你可以把資料放進 Bundle,再把 Bundle 塞進 Intent 中傳遞。使用時多加舉一反三,遇到不清楚的地方多查 API 與原始碼,就能靈活應對各種場景。下一篇我們將談論 Activity 的生命週期。

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