Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Activity、Intent、Intent Filter、Service 與 Broadcast 一次講清楚

編輯:Android 開發實例

Activity

在 Android 中,Activity 是所有程式的根本,程式的流程都運行在 Activity 之上。它有自己的一套生命週期,由系統控制,程式無法改變,但可以透過 onSaveInstanceState 保存狀態。

掌握 Activity 的關鍵有三:一是生命週期(那張經典的週期圖值得背下來);二是狀態的保存與還原(onSaveInstanceState / onRestoreInstanceState);三是頁面之間的跳轉與資料傳遞(靠 Intent)。

常用函式:setContentView()、findViewById()、finish()、startActivity()。生命週期相關的則有:

void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

別忘了每個 Activity 都要在 Manifest 中加上對應的 <activity> 標籤,並視需要設定屬性與 intent-filter。

Intent

Intent 機制負責協助應用之間的互動與通訊。它描述一次操作的「動作」、「涉及的資料」與「附加資料」,Android 依此找到對應元件、把 Intent 傳遞過去並完成呼叫。Intent 不僅用於跨應用,也能用於應用內 Activity 與 Service 之間的溝通。它扮演的是媒體中介的角色,讓呼叫者與被呼叫者彼此解耦。

SDK 中 Intent 的三種主要形式:

  • 以 Context.startActivity() 或 Activity.startActivityForResult() 啟動 Activity。
  • 以 Context.startService() 啟動服務,或以 Context.bindService() 與後台服務互動。
  • 以 Context.sendBroadcast()、sendOrderedBroadcast()、sendStickyBroadcast() 送給廣播接收器。

Intent 的屬性包含以下幾項(在 XML 中宣告,也可透過程式 API 設定):

(1) Action —— 要執行的動作。SDK 定義了一批標準動作:

常數目標元件說明
ACTION_CALLactivity發起一通電話
ACTION_EDITactivity顯示資料供使用者編輯
ACTION_MAINactivity作為 Task 的初始頁面啟動,無輸入也無輸出
ACTION_SYNCactivity將伺服器資料與裝置資料同步
ACTION_BATTERY_LOWbroadcast receiver電量偏低的警告
ACTION_HEADSET_PLUGbroadcast receiver耳機插入或拔出
ACTION_SCREEN_ONbroadcast receiver螢幕被點亮
ACTION_TIMEZONE_CHANGEDbroadcast receiver時區設定變更

也可以自訂動作。自訂時慣例是加上套件名稱作為前綴,例如 "com.example.project.SHOW_COLOR",並搭配一個處理該動作的 Activity。

(2) Data —— 動作作用的資料。以 URI 指向資料,例如指向某個聯絡人的 URI 可能是 content://contacts/1。不同動作對應不同 URI 形式:編輯檔案用 file URI,打電話用 tel:,上網用 http:,ContentProvider 提供的則是 content: URI。

(3) Type —— 明確指定 MIME 型別。一般情況下系統能從資料本身推導型別,但設定這個屬性可以強制採用指定型別,跳過推導。

(4) Category —— 動作的附加資訊。例如 CATEGORY_LAUNCHER 表示接收者應作為頂層應用出現在啟動器中;CATEGORY_ALTERNATIVE 表示這是同一份資料的若干可選動作之一。其他常見值:

常數含義
CATEGORY_BROWSABLE此 Activity 可安全地由瀏覽器喚起,用以顯示連結所指向的內容,例如圖片或郵件
CATEGORY_GADGET此 Activity 可嵌入到承載 gadget 的其他 Activity 中
CATEGORY_HOME此 Activity 顯示主螢幕,即裝置開機或按下 HOME 鍵後看到的第一個畫面
CATEGORY_LAUNCHER此 Activity 可作為 Task 的初始頁面,並列於頂層應用程式啟動器中
CATEGORY_PREFERENCE此 Activity 是一個設定面板

(5) Component —— 明確指定目標元件類名。正常情況下 Android 會依 action、data/type、category 去比對找出相符的元件;但一旦指定了 component,就直接使用它,不再進行比對,此時 Intent 的其他屬性全都是可選的。

(6) Extras —— 附加資訊集合。用來為元件提供擴充資料,例如執行「寄送郵件」時,把標題、內文放進 extras 一併傳給郵件程式。

顯式 Intent 與隱式 Intent

理解 Intent 的關鍵之一是分清兩種用法:顯式 Intent 在建立物件時就指定了接收者;隱式 Intent 則不關心接收者是誰,有助降低耦合。

顯式 Intent 不需要解析,因為目標已經明確。需要解析的是隱式 Intent:系統拿它去比對 Manifest 中已註冊的所有 Intent Filter,找出能處理它的 Activity、BroadcastReceiver 或 Service。比對依據是 action、type、category 三個屬性:

  • 若 Intent 指定了 action,目標元件的 filter 中就必須包含這個 action,否則不匹配。
  • 若 Intent 未提供 type,系統會從 data 推導。目標元件的資料型別清單必須包含它。
  • 若資料不是 content: 型別的 URI 且未明確指定 type,則依 URI 的 scheme(如 http:、mailto:)比對,該 scheme 必須出現在目標元件的清單中。
  • 若 Intent 指定了一或多個 category,這些 category 必須全部出現在目標元件的清單中。

屬性設定的寫法範例:

<action android:name="com.example.project.SHOW_CURRENT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="video/mpeg" android:scheme="http" ... />
<data android:mimeType="image/*" />
<data android:scheme="http" android:type="video/*" />

完整範例:

<activity android:name="NotesList" android:label="@string/title_notes_list">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.EDIT" />
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
    </intent-filter>
</activity>

Intent 常用寫法

1. 無參數跳轉:

Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);

2. 向下頁傳遞資料(Bundle + putExtras):

Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle);
startActivity(it);

接收端:

Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");

3. 向上頁回傳結果(搭配 startActivityForResult 與 setResult):

Intent intent = getIntent();
Bundle bundle2 = new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);

4. 在 onActivityResult 中處理回傳:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE) {
        if (resultCode == RESULT_CANCELED) {
            setTitle("cancle");
        } else if (resultCode == RESULT_OK) {
            String temp = null;
            Bundle bundle = data.getExtras();
            if (bundle != null) temp = bundle.getString("name");
            setTitle(temp);
        }
    }
}

以下為其他常見的系統功能呼叫寫法:

開啟網頁

Uri uri = Uri.parse("https://google.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

顯示地圖

Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// 其他 geo URI 形式:
// geo:latitude,longitude
// geo:latitude,longitude?z=zoom
// geo:0,0?q=my+street+address
// geo:0,0?q=business+near+city

路徑規劃

Uri uri = Uri.parse("https://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// startLat、startLng、endLat、endLng 為小數點後六位的數字,例如 50.123456

打電話

// 叫出撥號程式
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);

// 直接撥出(需在 Manifest 加入 android.permission.CALL_PHONE)
Uri uri2 = Uri.parse("tel:0800000123");
Intent it2 = new Intent(Intent.ACTION_CALL, uri2);
startActivity(it2);

傳送 SMS / MMS

// 叫出簡訊程式
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);

// 傳送簡訊
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
startActivity(it);

// 傳送 MMS
Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);

傳送 Email

Uri uri = Uri.parse("mailto:someone@example.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, "someone@example.com");
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// 收件人與副本用陣列
Intent it = new Intent(Intent.ACTION_SEND);
String[] tos = {"a@example.com"};
String[] ccs = {"b@example.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// 夾帶附件
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
it.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

播放多媒體

Uri uri = Uri.parse("file:///sdcard/song.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setType("audio/mp3");
startActivity(it);

Uri uri2 = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it2 = new Intent(Intent.ACTION_VIEW, uri2);
startActivity(it2);

Market 相關

// 搜尋某個應用(pkg_name 為完整套件路徑)
Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

// 顯示某應用的詳細資訊(app_id 可在 Market 網址列中取得)
Uri uri = Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

解除安裝

Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);

Service

Service 是沒有使用者介面的長生命週期程式碼。最典型的例子是音樂播放器:使用者會透過若干 Activity 選歌,但音樂不能隨頁面切換而中斷,因此播放器 Activity 要用 Context.startService() 啟動一個服務在後台維持播放,系統會讓它一直運行到工作結束。

另一種用法是 Context.bindService() 把 Activity 連上服務(若服務尚未運行則先啟動)。綁定之後,可以透過服務對外暴露的介面與它溝通——對音樂服務而言,就是暫停、倒帶這類操作。

Broadcast 與 BroadcastReceiver

Android 中的四類主要元件分工如下:

  • Activity:負責呈現功能畫面
  • Service:等同在後台運行的 Activity
  • Broadcast:負責發送廣播
  • BroadcastReceiver:負責接收廣播
  • Intent:把上述元件串接起來並在其間傳遞訊息

Broadcast 是 Android 中廣泛使用的跨應用資訊傳遞機制,而 BroadcastReceiver 則是對送出的 Broadcast 進行過濾、接收並回應的元件。流程是:先在需要發送訊息的地方,把要傳的資料與用於過濾的資訊(Action、Category)裝進一個 Intent,再呼叫 Context.sendBroadcast()、sendOrderedBroadcast() 或 sendStickyBroadcast() 發射出去。

Intent 送出後,所有已註冊的 BroadcastReceiver 都會檢查自己註冊時的 IntentFilter 是否與這個 Intent 相符;相符就會呼叫它的 onReceive() 方法。所以定義 BroadcastReceiver 時,一定要實作 onReceive()。

註冊方式有兩種:

靜態註冊——在 AndroidManifest.xml 中用 <receiver> 標籤宣告,並在內部以 <intent-filter> 設定過濾條件。

動態註冊——在程式碼中先建立並設定好 IntentFilter,在需要的位置呼叫 Context.registerReceiver(),不再需要時呼叫 Context.unregisterReceiver() 取消。慣例是在 onStart(或 onResume)註冊、在 onStop 取消。

無論靜態或動態,程式結束時若無特殊需求都應該取消註冊,否則下次啟動可能出現多個重複的接收器。

權限方面:若呼叫 sendBroadcast() 時指定了接收權限,則只有在 Manifest 中以 <uses-permission> 宣告了該權限的 BroadcastReceiver 才可能收到;反之,註冊時若指定了可接收的權限,也只有持有該權限的 Context 所送出的 Broadcast 才能被它接收。

動態註冊與發送的骨架:

// 註冊
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(actionString);   // 指定要接收的 action
registerReceiver(broadcastReceiver, intentFilter);

// 發送
Intent intent = new Intent(actionString);   // 指定目標 action
intent.putExtra(key, value);                // 需傳遞的參數(可選)
sendBroadcast(intent);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved