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

Android 廣播接收器:攔截系統與自訂廣播

編輯:進階開發

廣播接收器(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)等作法。

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