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

Android 學習筆記:廣播機制(Broadcast)入門到實作

編輯:Android 開發實例

一聽到「廣播」,多數人腦中浮現的是收音機:想聽哪一台,把頻率調過去就對了。Android 的廣播機制與此非常神似,只不過它沒有頻率,而是由系統(或某個程式)發出一個事件,凡是符合條件的接收器都能收到並處理。

實作廣播需要的三件事

  1. 在 AndroidManifest.xml 註冊 <receiver/>:這個標籤必須帶 android:name,值為繼承 BroadcastReceiver 的類別名稱。
  2. 用 <intent-filter/> 指定要收哪一種廣播:它是 receiver 的子標籤,裡頭用 <action> 宣告感興趣的 action。這個標籤非常重要,寫錯或漏掉,接收器永遠不會被觸發。
  3. 必要時宣告權限 <uses-permission/>:例如想攔截簡訊,就得加上 android.permission.RECEIVE_SMS,具體可用的權限名稱建議查官方 API 文件。

程式碼方面,只要寫一個類別繼承 BroadcastReceiver 並覆寫 onReceive(),把收到廣播後要處理的事情寫在裡面即可。

動手做:一個最小的廣播範例

UI 很簡單:一個按鈕,按下去發送廣播;接收器收到後在終端機印一句話。

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BroadCast"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyBroadCastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.EDIT"></action>
            </intent-filter>
        </receiver>
    </application>

    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>

這裡自訂了一個 action android.intent.action.EDIT 當作比對依據;同時也預先宣告了簡訊接收權限,示範權限的寫法。

Activity:發送廣播,以及動態註冊/反註冊

package com.gufengxiachen.broadcast;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BroadCast extends Activity {

    private Button bound = null;
    private Button unbound = null;
    private Button sendBroadCast = null;
    private SecondBroadCastReceiver sbr = null;

    public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEVIER";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bound = (Button) findViewById(R.id.bound);
        unbound = (Button) findViewById(R.id.unbound);
        sendBroadCast = (Button) findViewById(R.id.sendBroadCast);

        bound.setOnClickListener(new BoundListener());
        unbound.setOnClickListener(new UnboundListener());
        sendBroadCast.setOnClickListener(new SendBroadCast());
    }

    // 發送廣播
    class SendBroadCast implements OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_EDIT);
            BroadCast.this.sendBroadcast(intent);
        }
    }

    // 程式碼動態註冊接收器(不需要寫在 Manifest 裡)
    class BoundListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            sbr = new SecondBroadCastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(SMS_ACTION);
            BroadCast.this.registerReceiver(sbr, filter);
        }
    }

    // 反註冊,避免接收器洩漏
    class UnboundListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            BroadCast.this.unregisterReceiver(sbr);
        }
    }
}

接收器類別

package com.gufengxiachen.broadcast;

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

public class MyBroadCastReceiver extends BroadcastReceiver {

    public MyBroadCastReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("message receiver");
    }
}

補充:靜態註冊與動態註冊的差別

上面示範了兩種寫法,實務上要分清楚:

  • 靜態註冊(Manifest):寫在 <receiver/> 裡,App 沒在執行時也能收到廣播,適合攔系統事件(開機完成、簡訊、來電、電量變化等)。缺點是必須搭配 intent-filter,且無法在執行期動態改變條件。
  • 動態註冊(registerReceiver):在程式碼中註冊,只有元件存活期間有效,適合接收 App 自己發出的內部事件。用完務必呼叫 unregisterReceiver(),否則會造成記憶體洩漏,通常放在 onDestroy() 或對應的生命週期結束點處理。

另外提醒兩點:onReceive() 執行在主執行緒上,因此裡面不能做耗時運算,需要長時間處理請轉交 Service;而 onReceive() 返回後,接收器實例就可能被系統回收,別依賴它把狀態存下來。

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