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

Android 靜態與動態廣播註冊的差別一次講清楚

編輯:關於 Android 程式設計

常駐型廣播(靜態註冊)

常駐型廣播的特性是:即使你的應用程式已經關閉,只要有廣播送來,你寫的廣播接收器一樣收得到。註冊位置在 AndroidManifest.xml 中,因此被稱為靜態註冊。可以這樣理解——寫在清單檔裡的廣播是交由作業系統代管的,應用不在 alive 也無妨。

<!-- 訂閱開機完成廣播 -->
<receiver android:name=".receiver.BootCompleteReceiver">
    <intent-filter android:priority="1000">
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

非常駐型廣播(動態註冊)

非常駐型廣播的生命週期跟註冊者綁在一起:應用一結束,廣播就跟著失效。典型做法是在 Activity 的 onCreate 或 onResume 中註冊,並在 onDestroy 中解除註冊,這種方式稱為動態註冊。

以下示範一個監聽 SD 卡狀態的接收器:

package cn.sunzn.mosecurity.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;

public class SDcard extends Activity {
    SdcardStateChanageReceiver sdcardStateReceiver;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sdcardStateReceiver = new SdcardStateChanageReceiver();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addDataScheme("file");
        registerReceiver(sdcardStateReceiver, filter);
    }

    protected void onDestroy() {
        unregisterReceiver(sdcardStateReceiver);
    }

    class SdcardStateChanageReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            checkSDCard();
        }

        public void checkSDCard() {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_REMOVED)
                    || state.equals(Environment.MEDIA_UNMOUNTED)) {
                System.out.println("SDCard 已卸載!");
            }
        }
    }
}

怎麼選

判斷依據很單純:需要「應用沒開也要收到」的訊息(例如開機完成、系統時區變更),用靜態註冊;只是「畫面存在期間需要關注」的狀態(例如本例的 SD 卡插拔),用動態註冊即可,而且務必記得解除註冊,否則容易造成物件無法回收與資料外洩。

另外要留意,Android 8.0 之後對背景應用限制收緊,多數隱式廣播已無法再以靜態方式接收,這是在新版本上設計廣播時必須先確認的前提。

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