• Android Video Tutorials

Android - 廣播接收器



廣播接收器簡單來說就是響應來自其他應用程式或系統本身的廣播訊息。這些訊息有時被稱為事件或意圖。例如,應用程式也可以啟動廣播來讓其他應用程式知道一些資料已被下載到裝置上,並且可供它們使用,所以廣播接收器會攔截此通訊並啟動相應的操作。

要使廣播接收器能夠處理系統廣播的意圖,需要執行以下兩個重要步驟:

  • 建立廣播接收器。

  • 註冊廣播接收器

如果您要實現自定義意圖,則還需要建立一個額外的步驟來建立和廣播這些意圖。

建立廣播接收器

廣播接收器實現為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();
   }
}

註冊廣播接收器

應用程式透過在AndroidManifest.xml檔案中註冊廣播接收器來監聽特定的廣播意圖。假設我們要為系統生成的事件ACTION_BOOT_COMPLETED註冊MyReceiver,該事件在Android系統完成引導過程後由系統觸發。

broadcast

廣播接收器

<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>

現在,每當您的Android裝置啟動時,它都會被廣播接收器MyReceiver攔截,並且onReceive()中實現的邏輯將被執行。

Intent類中,有幾個系統生成的事件被定義為最終靜態欄位。下表列出了一些重要的系統事件。

序號 事件常量及描述
1

android.intent.action.BATTERY_CHANGED

包含電池充電狀態、電量和其他資訊的粘性廣播。

2

android.intent.action.BATTERY_LOW

指示裝置電量低。

3

android.intent.action.BATTERY_OKAY

指示電池電量在低電量後恢復正常。

4

android.intent.action.BOOT_COMPLETED

系統完成啟動後廣播一次。

5

android.intent.action.BUG_REPORT

顯示報告錯誤的活動。

6

android.intent.action.CALL

執行對由資料指定的某人的呼叫。

7

android.intent.action.CALL_BUTTON

使用者按下“呼叫”按鈕以進入撥號器或其他合適的UI進行呼叫。

8

android.intent.action.DATE_CHANGED

日期已更改。

9

android.intent.action.REBOOT

重啟裝置。

廣播自定義意圖

如果您希望應用程式本身生成和傳送自定義意圖,則必須使用活動類中的sendBroadcast()方法建立和傳送這些意圖。如果您使用sendStickyBroadcast(Intent)方法,則意圖是粘性的,這意味著您傳送的Intent在廣播完成之後仍然存在。

public void broadcastIntent(View view) {
   Intent intent = new Intent();
   intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
   sendBroadcast(intent);
}

此意圖com.tutorialspoint.CUSTOM_INTENT也可以像我們註冊系統生成的意圖一樣註冊。

<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.tutorialspoint.CUSTOM_INTENT">
         </action>
      </intent-filter>
   
   </receiver>
</application>

示例

此示例將向您解釋如何建立BroadcastReceiver來攔截自定義意圖。一旦您熟悉了自定義意圖,您就可以對應用程式進行程式設計以攔截系統生成的意圖。因此,讓我們按照以下步驟修改我們在Hello World 示例章節中建立的Android應用程式:

步驟 描述
1 您將使用Android Studio建立一個Android應用程式,並將其命名為My Application,包名為com.example.tutorialspoint7.myapplication,這在Hello World 示例章節中有解釋。
2 修改主活動檔案MainActivity.java以新增broadcastIntent()方法。
3 在包com.example.tutorialspoint7.myapplication下建立一個名為MyReceiver.java的新Java檔案以定義BroadcastReceiver。
4 應用程式可以處理一個或多個自定義和系統意圖,沒有任何限制。您要攔截的每個意圖都必須使用<receiver.../>標籤在您的AndroidManifest.xml檔案中註冊
5 修改res/layout/activity_main.xml檔案的預設內容,以包含一個用於廣播意圖的按鈕。
6 無需修改字串檔案,Android Studio會處理string.xml檔案。
7 執行應用程式以啟動Android模擬器並驗證對應用程式所做的更改的結果。

以下是修改後的主活動檔案MainActivity.java的內容。此檔案可以包含每個基本生命週期方法。我們添加了broadcastIntent()方法來廣播自定義意圖。

package com.example.tutorialspoint7.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

   /** Called when the activity is first created. */
   @Override
   
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }


   // broadcast a custom intent.
      
   public void broadcastIntent(View view){
      Intent intent = new Intent();
      intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent);
   }
}

以下是MyReceiver.java的內容

package com.example.tutorialspoint7.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by TutorialsPoint7 on 8/23/2016.
 */
public class MyReceiver extends BroadcastReceiver{
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}

以下是修改後的AndroidManifest.xml檔案的內容。在這裡,我們添加了<receiver.../>標籤來包含我們的服務

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint7.myapplication">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
		
      <activity android:name=".MainActivity">
         <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.tutorialspoint.CUSTOM_INTENT">
            </action>
         </intent-filter>

      </receiver>
   </application>

</manifest>

以下是包含一個按鈕來廣播我們的自定義意圖的res/layout/activity_main.xml檔案的內容:

<RelativeLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" 
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Example of Broadcast"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="40dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/button2"
      android:text="Broadcast Intent"
      android:onClick="broadcastIntent"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />

</RelativeLayout>

讓我們嘗試執行我們剛剛修改的Hello World!應用程式。我假設您在進行環境設定時建立了您的AVD。要從Android Studio執行應用程式,請開啟專案中的一個活動檔案,然後單擊工具欄中的執行Eclipse Run Icon圖示。Android Studio將應用程式安裝到您的AVD並啟動它,如果您的設定和應用程式一切正常,它將顯示以下模擬器視窗:

Android Broadcast Demo

現在要廣播我們的自定義意圖,讓我們單擊廣播意圖按鈕,這將廣播我們的自定義意圖"com.tutorialspoint.CUSTOM_INTENT",該意圖將被我們註冊的BroadcastReceiver(即MyReceiver)攔截,根據我們實現的邏輯,一個吐司將出現在模擬器的底部,如下所示:

Android Broadcast Intent

您可以嘗試實現其他BroadcastReceiver來攔截系統生成的意圖,例如系統啟動、日期更改、低電量等。

廣告