微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android基础复习之广播Broadcast

Android广播知识复习

  • 作者:朱红喜

1.广播分类

  • 按通信方式分类
    • 标准广播 (normal broadcast)
    • 有序广播 (ordered broadcast)
  • 按广播区域分类
    • 全局广播
    • 本地广播(Localbrodcast)
  1. 标准广播:完全异步的广播,广播发出后每一个广播接收器都会同一时刻接收到这条广播信息,无法被拦截
  2. 有序广播:一种同步的广播,同一时刻只能由一个接收器能够接收到这条广播,接收器有顺序优先级,广播可以截断
  3. 全局广播:所有的应用都可以收到的广播
  4. 本地广播:只能够被本应用内的接收器接收到

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);
...

6.不要滥用广播

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐