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

在 AndroidManifest.xml 中靜態註冊廣播接收器的完整實作

編輯:關於 Android 程式設計

上一篇談的是動態註冊,這次換個角度,看看如何把廣播接收器寫死在 AndroidManifest.xml 裡。靜態註冊的好處很直接:即使 Activity 尚未啟動,甚至應用程式還在後台,系統也能把廣播送進來,因此特別適合那些必須隨時待命的監聽場景。

一、發送端:MainActivity

發送廣播本身非常直覺——建立一個 Intent,指定 Action,用 putExtra 掛上要傳遞的資料,最後呼叫 sendBroadcast() 拋出去即可。

package cc.testbroadcasta;

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

/**
 * Demo 說明:透過 AndroidManifest.xml 註冊廣播接收者
 */
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent = new Intent();
        intent.setAction("cc.test");        // 設定 Action
        intent.putExtra("name", "周星馳");   // 攜帶字串資料
        intent.putExtra("number", 9527);    // 攜帶整數資料

        sendBroadcast(intent);              // 送出廣播
    }
}

二、接收端:BroadcastReceiverTest

接收器的重點在 onReceive()。這個方法的執行緒生命週期極短,不建議在裡面做耗時工作或啟動長時間的 Background Thread;合理的做法是快速取資料、快速處理,或轉交給 Service。

package cc.testbroadcasta;

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

public class BroadcastReceiverTest extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String name = intent.getStringExtra("name");
        int number = intent.getIntExtra("number", 0);
        System.out.println("接收到廣播 name=" + name + ", number=" + number);
    }
}

三、版面配置:main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="利用 AndroidManifest.xml 註冊廣播接收者" />
</RelativeLayout>

四、關鍵步驟:AndroidManifest.xml

靜態註冊的核心就是 <receiver> 標籤,而真正決定「能不能收到」的,是它內部 <intent-filter> 的 Action 是否與發送端一致。Action 對不上,接收器永遠不會被觸發——這是初學者最常踩的坑。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="cc.testbroadcasta"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" />

    <application android:label="TestBroadcast">
        <activity
            android:name=".MainActivity"
            android:label="TestBroadcast">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 靜態註冊一個廣播接收者 -->
        <receiver android:name="cc.testbroadcasta.BroadcastReceiverTest">
            <intent-filter>
                <action android:name="cc.test" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

五、靜態與動態註冊該怎麼選

動態註冊的生命週期跟著元件走,Activity 一被回收,接收器就跟著失效,適合只在畫面存在期間有意義的監聽;靜態註冊則依附在 manifest 上,應用未啟動也能接收,代價是系統需要為此維持一定的資源調度。實務上兩者常並用:全域性的系統事件走靜態,跟 UI 狀態高度耦合的事件走動態。

另外提醒一點,Android 8.0 之後對隱式廣播的靜態接收有明顯收緊,多數商業廣播已不再允許在 manifest 中攔截,需要改用 JobScheduler、WorkManager 或前台 Service 等方案搭配。上面這套寫法在理解機制與自訂 Action 的內部通訊上仍然完全適用。

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