广播接收器注册一共有两种形式 : 静态注册和动态注册.
两者及其接收广播的区别:
1.动态注册的广播 永远要快于 静态注册的广播,不管静态注册的优先级设置的多高,不管动态注册的优先级有多低>\
2.动态注册广播不是 常驻型广播 ,也就是说广播跟随activity的生命周期。注意: 在activity结束前,移除广播接收器。
静态注册是常驻型 ,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行。
3.同种广播如果在同一个优先级下,谁先启动的快,谁将先接收到广播。
广播的有序无序传播详见我的博客:点击打开链接
下面主要说下动态广播的注册流程。
首先动态广播是不需要在Manifest文件中进行注册的,这与静态广播有很大的区别。
<span style="font-size:12px;"><?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima.register" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.itheima.register.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.itheima.register.RegisterService"></service> </application> </manifest></span>其次动态广播通常注册在Service的onCreate方法当中,在Service销毁的时候,会解除注册。
<span style="font-size:12px;">package com.itheima.register; import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class RegisterService extends Service { private ScreenReceiver receiver; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { super.onCreate(); //1.创建广播接收者对象 receiver = new ScreenReceiver(); //2.创建intent-filter对象 IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); //3.注册广播接收者 registerReceiver(receiver, filter); } @Override public void onDestroy() { super.onDestroy(); //解除注册 unregisterReceiver(receiver); } }</span>下面是监听屏幕开关的广播;
<span style="font-size:12px;">public class ScreenReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); if(Intent.ACTION_SCREEN_OFF.equals(action)){ System.out.println("屏幕关闭"); } else if(Intent.ACTION_SCREEN_ON.equals(action)){ System.out.println("屏幕打开"); } } }</span>在Android 3.1系统之后,静态广播默认会被后台回收掉的,这部分知识详见我的博文:点击打开链接。因此,静态广播多数是不安全的,所以建议建立动态广播,并且与Service进行绑定,这样做有利于长时间的后台监听。在Activity中注册广播接收者建议在onResume()当中进行注册。在onDestroy()进行销毁。