Android广播知识复习
- 作者:朱红喜
1.广播分类
- 标准广播:完全异步的广播,广播发出后每一个广播接收器都会同一时刻接收到这条广播信息,无法被拦截。
- 有序广播:一种同步的广播,同一时刻只能由一个接收器能够接收到这条广播,接收器有顺序优先级,广播可以截断
- 全局广播:所有的应用都可以收到的广播
- 本地广播:只能够被本应用内的接收器接收到
2.动态注册广播接收器
private IntentFilter intentFilter;
private Customreceiver mReceiver;
@Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver= new Customreceiver();
registerReceiver(mReceiver,intentFilter);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mReceiver);
}
class Customreceiver extends broadcastReceiver{
@Override
public void onReceive(Context context,Intent intent){
//你的逻辑代码
}
}
3.静态注册广播(manifest文件中)
<receiver
android:name=".Customreceiver"
android:enabled="true" 启用这个广播
android:exported="true"> 是否允许接收本程序外的广播
<intent-filter>
<action android:name="你需要的action"/>
</intent-filter>
</receiver>
4.发送广播
- 发送标准广播
Intent intent = new Intent("你的广播的action")
sendbroadcast(intent);
- 发送有序广播
Intent intent = new Intent("你的广播的action")
sendOrderedbroadcast(intent);
5.使用本地广播
private IntentFilter intentFilter;
private Customreceiver mReceiver;
private LocalbroadcastManager localbroadcastManager
@Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
localbroadcastManager = LocalbroadcastManager.getInstance(this);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver= new Customreceiver();
localbroadcastManager.registerReceiver(mReceiver,intentFilter);
}
@Override
protected void onDestroy(){
super.onDestroy();
localbroadcastManager.unregisterReceiver(mReceiver);
}
class Customreceiver extends broadcastReceiver{
@Override
public void onReceive(Context context,Intent intent){
//你的逻辑代码
}
}
发送广播
private LocalbroadcastManager localbroadcastManager
...
Intent intent = new Intent("你的广播的action")
localbroadcastManager.sendbroadcast(intent);
...