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

Android 廣播機制(Broadcast)完整解析與實作範例

編輯:關於 Android 程式設計

廣播是 Android 四大元件裡最靈活的一塊,系統事件(來電、簡訊、電量、螢幕狀態)與自訂事件都能透過它傳遞。本文從接收器的撰寫、兩種註冊方式的差異,一路寫到可直接跑起來的完整範例。

一、撰寫廣播接收器

第一步是繼承 BroadcastReceiver,並覆寫 onReceive():

class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 從 Intent 中取出 action 與其他附加資料
        ...
    }
}

二、靜態註冊(AndroidManifest.xml)

光定義好接收器還不夠,必須讓系統知道它能處理哪些事件。最常見的做法是在 <application> 節點下加入 <receiver>,並用 intent-filter 指定感興趣的 action(可以是系統的,也可以是自訂的):

<application>
    <receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.app.bc.test"/>
        </intent-filter>
    </receiver>
</application>

接著就能送出廣播:

Intent intent = new Intent("com.app.bc.test");
sendBroadcast(intent);

三、動態註冊(程式碼)

在 Activity 中用程式碼註冊同樣可行,以攔截簡訊為例:

SMSReceiver smsReceiver = new SMSReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
TestBC1Activity.this.registerReceiver(smsReceiver, filter);

四、靜態與動態註冊的差別

  • 靜態註冊:寫在 Manifest 中,Android 不會自動銷毀接收器。也就是說應用程式關掉之後,它仍然會收到廣播。
  • 動態註冊:透過 registerReceiver() 在程式碼中註冊,生命週期跟著元件走,程式關閉時接收器一併銷毀;也可以主動呼叫 unregisterReceiver() 解除。

五、操作流程小結

靜態註冊三步驟:

  1. 自訂類別繼承 BroadcastReceiver,覆寫 onReceive()。
  2. 在 XML 中註冊,於 Intent-Filter 宣告要攔的 action。
  3. 用 sendBroadcast() 送出廣播。

動態註冊三步驟:

  1. 建立接收器物件與 IntentFilter,加入 action。
  2. 呼叫 registerReceiver(receiver, filter)。
  3. 不需要在 Manifest 中宣告。

六、實作範例

以下範例用三顆按鈕分別示範靜態註冊、動態註冊與解除註冊。

Activity

public class BroadCastActivity1 extends Activity {
    Intent intent = new Intent();
    BroadCastTest1 bCastTest1 = new BroadCastTest1();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bc1);

        // 靜態註冊的廣播
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.setAction("bc.test101");
                intent.putExtra("name", "靜態的");
                sendBroadcast(intent);
            }
        });

        // 動態註冊的廣播
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("bc.test102");
                BroadCastActivity1.this.registerReceiver(bCastTest1, intentFilter);

                intent.setAction("bc.test102");
                intent.putExtra("name", "動態的");
                sendBroadcast(intent);
            }
        });

        // 解除註冊並離開
        findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                unregisterReceiver(bCastTest1);
                finish();
            }
        });
    }
}

廣播接收類別

public class BroadCastTest1 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String name = intent.getStringExtra("name");
        Toast.makeText(context, "廣播1:" + name, 1000).show();
    }
}

Manifest 宣告

<receiver android:name=".BroadCastTest1">
    <intent-filter android:priority="3">
        <action android:name="bc.test101"/>
    </intent-filter>
</receiver>

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#fff"
    android:padding="10dp">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="靜態註冊廣播" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="動態註冊廣播" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="退出" />
</LinearLayout>

實務提醒

動態註冊的接收器若沒有在 onDestroy() 或對應的生命週期點解除,容易造成記憶體洩漏,也可能出現重複接收。另外,若要在 onReceive() 中做耗時工作,記得它跑在主執行緒上,稍一卡住就會觸發 ANR,長時間任務應該轉交 Service 處理。

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