Android BroadcastReceiver组件

这个组件就是一个系统级的监听器,发送广播之后,找出专门的Receiver接受,并且调用onReceive()函数处理。

整个过程是这样的:

(1)创建自己的Receiver

public class MyReceiver extends BroadcastReceiver
{

	@Override
	public void onReceive(Context arg0, Intent arg1)
	{
		// TODO Auto-generated method stub
		String string=arg1.getStringExtra("message");
		Toast toast=Toast.makeText(arg0, "我收到的消息是:"+string, Toast.LENGTH_LONG);
		toast.show();
	}

}
在AndroidManifest.xml那里配置注册:

<receiver 
       android:name=".MyReceiver">
       <intent-filter android:priority="20">
           <action android:name="hello"/>
       </intent-filter>
</receiver>
这样就有了一个专门接受"hello"Action的接收器了

public void onClick(View arg0)
{
	// TODO Auto-generated method stub
	Intent intent=new Intent();
	intent.putExtra("message", "收到么?");
	intent.setAction("hello");
	MainActivity.this.sendBroadcast(intent);
}
发送"hello"Action的广播

除了这种普通广播之外,还有有序广播:

有序广播就是发出广播之后,有好几个Receiver能接收处理这个广播,但是不像普通广播同时接受处理,这几个Receiver在intent-filter那里声明了优先权,优先权大的先处理,处理完了再传给下一个Receiver,同时还能利用setResultExtra()和getResultExtra()添加额外的信息,再继续传下去,也可以用abortBroadcast()终止传下去。

<receiver 
      android:name=".MyReceiver">
      <intent-filter android:priority="20">
            <action android:name="hello"/>
      </intent-filter>
</receiver>
<receiver 
      android:name=".MyReceiver2">
      <intent-filter android:priority="0">
           <action android:name="hello"/>
      </intent-filter>
</receiver>
先声明了2个Receiver,他们都能接受hello这个Action的,其中MyReceiver优先级大,先接收到广播

public void onClick(View arg0)
{
	// TODO Auto-generated method stub
	Intent intent=new Intent();
	intent.putExtra("message", "收到么?");
	intent.setAction("hello");
	MainActivity.this.sendOrderedBroadcast(intent,null);
}
发出有序广播,先执行的函数是:

public class MyReceiver extends BroadcastReceiver
{

	@Override
	public void onReceive(Context arg0, Intent arg1)
	{
		// TODO Auto-generated method stub
		String string=arg1.getStringExtra("message");
		Toast toast=Toast.makeText(arg0, "我收到的消息是:"+string, Toast.LENGTH_LONG);
		toast.show();
		Bundle bundle=new Bundle();
		bundle.putString("first", "第一级Receive加的信息");
		setResultExtras(bundle);
	}

}
再来就是:

public class MyReceiver2 extends BroadcastReceiver
{

	@Override
	public void onReceive(Context arg0, Intent arg1)
	{
		// TODO Auto-generated method stub
		Bundle bundle=getResultExtras(true);
		String string=bundle.getString("first");
		Toast toast=Toast.makeText(arg0, "上一级Receiver加的信息:\n"+string, Toast.LENGTH_LONG);
		toast.show();
	}

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值