广播被分为两种不同的类型:“普通广播(Normal broadcasts)”和“有序广播(Ordered broadcasts)”。
?
普通广播是完全异步的,所有接收者(逻辑上)都在同一时刻运行,对消息传递的效率而言这是很好的做法,但缺点是:接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播;
?
有序广播是逐个执行接收者——系统会按照接收者声明的优先级别(声明在intent-filter元素的android:priority属性中,数越大优先级别越高,取值范围:-1000到1000。也可以调用IntentFilter对象的setPriority()进行设置),按顺序逐次执行。
?
如何发送广播:
*第一步:
// 广播意图,该广播只能被定义了该意图的广播接收者才能接收
//意图还能加入需要被广播接收者处理的数据
Intent intent=new Intent();
// 广播的唯一识别码,类似于广播电台的频率,接收者需要在意图过滤器中指定
intent.setAction("con.cgc.aaa");
intent.putExtra("msg", str);
? ?
//发送一个普通广播
this.sendBroadcast(intent);
?
如何接收广播
*第二步
1:写一个类必须继承BroadcaseBeceiver,并重写onReceiver()方法。
?
public class MyBroadCast extends BroadcastReceiver{
//当受到广播之后自动调用
@Override
public void onReceive(Context context, Intent intent) {
String str=intent.getStringExtra("msg");
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
?
如何如何定义广播(两种方法)
*第三步
第一种:在AndroidManifest.xml文件中的<application>节点里进行订阅。
?
? ? ? ? <receiver android:name=".MyBroadCast">
? ? ? ? ? ? <intent-filter>
//这个就是广播的唯一识别码要想订阅这个广播就把action的name设置成一直就是
? ? ? ? ? ? ? ? <action android:name="con.cgc.aaa" >
? ? ? ? ? ? ? ? </action>
? ? ? ? ? ? </intent-filter>
? ? ? ? </receiver>
?
第二种:使用代码进行订阅。
//定义意图过滤器
intentFilter filter=new IntentFilter();
//添加过滤器的动作
filter.action("com.chc.aaa");
//创建广播接收者对象
? ? ? ?MyBroadCastReceiver receiver = new MyBroadCastReceiver();
//注册接收者
registerReceiver(receiver, filter);
?
原文:http://hit-me.iteye.com/blog/2188406