您的位置:首页 > 移动开发 > Android开发

Android BroadcastReceiver组件

2014-07-30 15:21 357 查看
这个组件就是一个系统级的监听器,发送广播之后,找出专门的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();
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: