广播的类型主要分为5类:
普通广播(Normal Broadcast)
系统广播(System Broadcast)
有序广播(Ordered Broadcast)
粘性广播(Sticky Broadcast)
App应用内广播(Local Broadcast)
发送普通广播使用步骤
①自定义一个关播接收者继承BroadcastReceivre
②注册 静态注册 动态注册
③通过intent发送广播
- 静态注册 在在AndroidManifest.xml里通过<receive>标签声明
<receiver android:name=".StaticalReceiver">
<intent-filter>
<action android:name="com.example.broadcastreceiver.StaticalReceiver"/>
</intent-filter>
</receiver>
- 动态注册 在onResume调用 registerReceiver方法
@Override
protected void onResume() {
super.onResume();
//获取广播接收者的对象
dynamicReceiver = new DynamicReceiver();
//添加intentFilter
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcastreceiver.StaticalReceiver");
//注册广播
registerReceiver(dynamicReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
//销毁广播
unregisterReceiver(dynamicReceiver);
}
- 顺序广播
①动态注册
②通过intentFilter.setPriority();决定接收广播的先后顺序
③销毁广播
private void order() {
Intent intent = new Intent("com.example.broadcastreceiver.StaticalReceiver");
sendOrderedBroadcast(intent, null);
}
- 本地广播
//注册应用内广播接收器
//步骤1:实例化BroadcastReceiver子类 & IntentFilter mBroadcastReceiver
localReceiver= new LocalReceiver();
IntentFilter intentFilter = new IntentFilter();
//步骤2:实例化LocalBroadcastManager的实例
localBroadcastManager = LocalBroadcastManager.getInstance(this);
//步骤3:设置接收广播的类型
intentFilter.addAction("com.example.broadcastreceiver.LocalReceiver");
//步骤4:调用LocalBroadcastManager单一实例的registerReceiver()方法进行动态注册
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
//取消注册应用内广播接收器
localBroadcastManager.unregisterReceiver(localReceiver);
//发送应用内广播
Intent intent = new Intent();
intent.setAction("com.example.broadcastreceiver.LocalReceiver");
localBroadcastManager.sendBroadcast(intent);