转载请注明出处:http://blog.csdn.net/u011569040/article/details/45952693
priority的值越大,优先级越高。
程序:打开activity就发送 一个 有序广播,一共有三个广播接受者,FirstReceive,SecondReceive和ThirdReceive,优先级别分别为800,700,600,FirstReceive得到广播中的字符串后打印出来:hello java,自己再发送一个字符串A给优先级别低的SecondReceive,SecondReceive接收到 hello java和 A后打印出来,并终止广播,ThirdReceive就接收不到广播。
A字符串即"来源于FirstReceiver的文本"。
public class MainActivity extends Activity {
ThirdReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registgerReceiver();
Intent intent=new Intent("com.sxt.day07_06.order_broadcast");
intent.putExtra("key", "hello java");
sendOrderedBroadcast(intent, null);
}
private void registgerReceiver() {
mReceiver=new ThirdReceiver();
IntentFilter filter=new IntentFilter("com.sxt.day07_06.order_broadcast");
filter.setPriority(600);
registerReceiver(mReceiver, filter);
}
class ThirdReceiver extends BroadcastReceiver{
public void onReceive(Context context, android.content.Intent intent) {
Log.i("main","ThirdReceiver.onReceive()");
};
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
public class FirstReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String value=intent.getStringExtra("key");
Log.i("main","FirstReceiver.onReceive():"+value);
setResultData("来源于FirstReceiver的文本");
}
}
public class SecondReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String value=intent.getStringExtra("key");
String text=getResultData();
Log.i("main","SecondReceiver.onReceive(),intent中携带的文本:"+value+","+text);
if(isOrderedBroadcast()){
abortBroadcast();//终止广播
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sxt.day07_06"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.sxt.day07_06.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.sxt.day07_06.FirstReceiver">
<intent-filter android:priority="800">
<action android:name="com.sxt.day07_06.order_broadcast"/>
</intent-filter>
</receiver>
<receiver android:name="com.sxt.day07_06.SecondReceiver">
<intent-filter android:priority="700">
<action android:name="com.sxt.day07_06.order_broadcast"/>
</intent-filter>
</receiver>
</application>
</manifest>