动态注册
特点:动态注册的广播的有效期与Activity或Service相同,当Activity或Service销毁后,动态注册的广播将不在存在。
注意:动态注册的广播一定要在Activity或Service内取消注册广播,如果不取消,Activity会保持引用,无法释放资源。
动态注册的方法
public abstract Intent registerReceiver (BroadcastReceiver receiver,IntentFilter filter)
Parameters
receiver | The BroadcastReceiver to handle the broadcast. |
---|---|
filter | Selects the Intent broadcasts to be received. |
Returns
- The first sticky intent found that matches filter, or null if there are none.
public abstract Intent registerReceiver (BroadcastReceiver receiver,IntentFilter filter, String broadcastPermission, Handler scheduler)
Parameters
receiver | The BroadcastReceiver to handle the broadcast. |
---|---|
filter | Selects the Intent broadcasts to be received. |
broadcastPermission | String naming a permissions that a broadcaster must hold in order to send an Intent to you. If null, no permission is required. |
scheduler | Handler identifying the thread that will receive the Intent. If null, the main thread of the process will be used. |
Returns
- The first sticky intent found that matches filter, or null if there are none.
动态注册取消的方法:
public abstract void unregisterReceiver (BroadcastReceiver receiver)
Parameters
receiver | The BroadcastReceiver to unregister |
---|
事例代码:
//onResum中注册
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);
//onStop中取消注册
unregisterReceiver(sdcardStateReceiver);
}
静态注册
特点:永久存在,即使Application已经退出,注册也会有效。
注意:android3.1以后,首次安装未启动或者用户强制force stop后,应用无法监听到
实例代码:
<receiver android:name=".receiver.BootCompleteReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>