普通廣播(normal broadcast):
一,優缺點:和有序廣播的優缺點相反!
二,發送廣播的方法:sendbroadcast()
有序廣播(ordered broadcast):
一,優缺點
優點:1,按優先級的不同,優先receiver可對資料進行處理,并傳給下一個receiver
2,通過abortbroadcast可終止廣播的傳播
缺點:效率低
二,發送廣播的方法:sendorderedbroadcast()
三,優先接收到broadcast的receiver可通過setresultextras(bundle)方法将處理結果存入broadcast中,
下一個receiver 通過 bundle bundle=getresultextras(true)方法擷取上一個 receiver傳來的資料
程式效果:點選按鈕,兩個receiver接收同一條廣播,在logcat中列印出資料(按照receiver的優先順序,receiver2先,receiver1後)
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.song"
android:versioncode="1"
android:versionname="1.0" >
<uses-sdk android:minsdkversion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".c48_broadcastactivity" >
<intent-filter >
<action android:name="android.intent.action.main" />
<category android:name="android.intent.category.launcher" />
</intent-filter>
<!--優先級的設定 myreceiver2大于myreceiver1,優先級的範圍-1000~1000 -->
</activity>
<receiver android:name=".myreceiver1">
<intent-filter android:priority="200">
<action android:name="com.song.123"/>
</receiver>
<receiver android:name=".myreceiver2">
<intent-filter android:priority="1000">
</application>
</manifest>
主activity
package com.song;
//發送廣播,bundle綁上key為a的資料
import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
public class c48_broadcastactivity extends activity {
/** called when the activity is first created. */
button button;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
button=(button)findviewbyid(r.id.button);
button.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
// todo auto-generated method stub
intent intent=new intent("com.song.123");
bundle bundle=new bundle();
bundle.putstring("a", "aaa");
intent.putextras(bundle);
//有序廣播
sendorderedbroadcast(intent, null);
}
});
}
}
receiver2
//優先接到廣播,bundle綁上key為b的資料
import android.content.broadcastreceiver;
import android.content.context;
public class myreceiver2 extends broadcastreceiver{
public void onreceive(context context, intent intent) {
// todo auto-generated method stub
system.out.println("receiver2");
// context.getsystemservice(name);
bundle bundle=intent.getextras();
bundle.putstring("b", "bbb");
system.out.println("a="+bundle.get("a"));
setresultextras(bundle);
//切斷廣播
// abortbroadcast();
receiver1
//接收從receiver2傳來的廣播,包含key為a和b的資料
public class myreceiver1 extends broadcastreceiver{
system.out.println("receiver1");
//要不要接受上一個廣播接收器receiver2傳來的的資料
bundle bundle=getresultextras(true);
system.out.println("a="+bundle.getstring("a")+",b="+bundle.getstring("b"));
程式效果