編輯:進階開發
廣播接收器(Broadcast Receiver)負責回應來自其他應用程式或系統的廣播訊息,這些訊息也常被稱為事件或意圖。舉例來說,某個 App 可以發出廣播,告知其他 App「資料已下載完成,可以取用了」,而廣播接收器就是攔截這類訊息並做出適當反應的那一端。
要讓 App 具備接收廣播的能力,基本上有兩個必要步驟:建立廣播接收器,以及註冊廣播接收器。如果你打算收 ourselves 定義的自訂訊息,還要多一步——建立並送出那個自訂意圖。
做法很直接:繼承 BroadcastReceiver 類別,並覆寫 onReceive() 方法。每收到一則訊息,它就會以 Intent 物件作為參數傳入:
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); } }
App 要監聽哪些廣播,是透過 AndroidManifest.xml 註冊的。以下範例讓 MyReceiver 攔截 ACTION_BOOT_COMPLETED——這個訊息在 Android 完成開機流程後由系統發出:
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> </application>
這樣一來,裝置每次開機完成時,MyReceiver 的 onReceive() 就會被呼叫並執行裡面的邏輯。
系統預先定義了許多事件常數,都放在 Intent 類別的靜態欄位中。以下列出幾個常用的:
| 事件常數 | 說明 |
|---|---|
| android.intent.action.BATTERY_CHANGED | 持久的電池資訊廣播,包含充電狀態、電量等。 |
| android.intent.action.BATTERY_LOW | 裝置電池電量過低。 |
| android.intent.action.BATTERY_OKAY | 電池已脫離低電量狀態,恢復正常。 |
| android.intent.action.BOOT_COMPLETED | 系統開機完成後發出。 |
| android.intent.action.BUG_REPORT | 回報錯誤/問題報告的活動。 |
| android.intent.action.CALL | 依指定資料撥打電話。 |
| android.intent.action.CALL_BUTTON | 使用者按下「通話」鈕,開啟撥號介面。 |
| android.intent.action.DATE_CHANGED | 系統日期被變更。 |
| android.intent.action.REBOOT | 裝置重新開機。 |
如果想讓自己的 App 產生並送出專屬訊息,可以在 Activity 中呼叫 sendBroadcast()。若希望訊息在廣播結束後仍然保留(也就是所謂的 sticky broadcast),則改用 sendStickyBroadcast():
public void broadcastIntent(View view) { Intent intent = new Intent(); intent.setAction("com.yiibai.CUSTOM_INTENT"); sendBroadcast(intent); }
自訂意圖的註冊方式與系統意圖完全相同,只要把 action 名稱換成自己的即可:
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.yiibai.CUSTOM_INTENT"> </action> </intent-filter> </receiver> </application>
這個範例示範如何建立一個 BroadcastReceiver 來攔截自訂意圖。熟悉自訂意圖之後,改成攔截系統訊息只是替換 action 名稱的差別。請沿用先前建立的 Hello World 專案:
| 步驟 | 說明 |
|---|---|
| 1 | 用 Eclipse IDE 建立 Android 專案,命名 HelloWorld,套件 com.example.helloworld。 |
| 2 | 修改 MainActivity.java,加入 broadcastIntent() 方法。 |
| 3 | 在 com.example.helloworld 下新增 MyReceiver.java,定義 BroadcastReceiver。 |
| 4 | 在 AndroidManifest.xml 中以 <receiver.../> 標籤註冊要攔截的意圖,數量不限。 |
| 5 | 修改 res/layout/activity_main.xml,加入一個用來送出廣播的按鈕。 |
| 6 | 在 res/values/strings.xml 定義 broadcast_intent 字串常數。 |
| 7 | 執行應用程式並在模擬器上驗證。 |
以下是修改後 MainActivity.java 的內容:
package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.content.Intent; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // broadcast a custom intent. public void broadcastIntent(View view) { Intent intent = new Intent(); intent.setAction("com.yiibai.CUSTOM_INTENT"); sendBroadcast(intent); } }
接著是 src/com.example.helloworld/MyReceiver.java:
package com.example.helloworld; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); } }
在 AndroidManifest.xml 中註冊這個接收器:
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.yiibai.CUSTOM_INTENT"> </action> </intent-filter> </receiver> </application> </manifest>
版面配置只需一顆按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnStartService" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/broadcast_intent" android:onClick="broadcastIntent"/> </LinearLayout>
並在 res/values/strings.xml 中定義按鈕文字:
<resources> <string name="app_name">HelloWorld</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> <string name="broadcast_intent">Broadcast Intent</string> </resources>
執行修改後的 Hello World。請確認 AVD 與環境設定完成,開啟專案 Activity 檔並點擊工具列上的「Run」
圖示。若一切正常,模擬器畫面如下:
按下「Broadcast Intent」按鈕,App 就會送出一個 action 為「com.yiibai.CUSTOM_INTENT」的廣播,MyReceiver 攔截到之後執行 onReceive(),畫面底部會跳出提示:
接下來你可以試著讓同一個接收器攔截系統訊息,例如開機完成、日期變更、電池電量過低等等,只要替換 action 名稱即可。要提醒的是,Android 8.0 之後對背景應用限制收緊,多數隱式廣播已無法再透過 manifest 靜態註冊接收,實作時應改用 JobScheduler、WorkManager 或動態註冊(registerReceiver)等作法。
Android 版本發展與 Firefox 上機的可能性觀察
曾經,我們暢想過 Android 版本的 Firefox。從技術層面看已經沒有障礙,而近日 Mozilla 執行長 John Lilly 與 Mozilla Mobile
快速上手Android指令:TestSuite、TestCase與adb實作
Android是個以Linux核心為基礎的軟體平台與作業系統,最早由Google發起。要靈活操作它,命令列幾乎是繞不開的一關,以下就從測試結構談到實際指令,希望讀完能替你
Android 開發經驗分享(3):好用的產品,永遠勝過功能堆疊
好的使用者體驗能讓產品達到事半功倍的效果。在一堆同類軟體裡,下載量最高的那一個,往往就是讓人用起來最舒服的,哪怕它的功能並不比對手出色,甚至略遜一籌。 我看過不少開發者把
Activity 的四種啟動模式(1):先弄懂生命週期
建議先讀過下面兩篇,才能比較好地理解啟動模式: Android 的行程與執行緒模型(cnblogs.com/ghj1976)——其中對「Android 單執行緒模型」的描