标签:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SortedBroadcast extends Activity {
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sorted_broadcast);
//获取程序中的send按钮
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent对象
Intent intent = new Intent();
intent.setAction(broadcasttest.action.CRAZY_BROADCAST");
intent.putExtra("msg", "简单的消息");
//发送有序广播
sendOrderedBroadcast(intent, null);
}
});
}
}
对于有序广播而言,它会按优先级依次触发每个BroadcastReceiver的onReceive()方法。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MyReceiver1 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "接收到的Intent的Action为:"+
intent.getAction()+"\n消息内容是:"+intent.getStringExtra("msg"),
5000).show();
//创建一个Bundle对象,并存入数据
Bundle bundle = new Bundle();
bundle.putString("first", "第一个BroadcastReceiver存入的信息");
//将Bundle放入结果中
setResultExtras(bundle);
//取消Broadcast的继续传播
abortBroadcast();
}
}
上面的BroadcastReceiver不仅处理了它接收到的消息,而且向处理结果中存入了key为first的消息,这个消息将可以被第二个BroadcastReceiver解析出来。,不过最后一行代码用于取消广播,如果保持这条代码生效,那么优先级比MyReceiver1低的BroadcastReceiver都将不会被触发。
在AndroidManifest.xml文件中部署该BroadcastReceiver,并指定其优先级为20,配置片段如下:
<receiver android:name=".MyReceiver1">
<intent-filter android:priority="20">
<action android:name="broadcasttest.action.CRAZY_BROADCAST"/>
</intent-filter>
</receiver>
接下来再为程序提供第二个BroadcastReceiver,这个BroadcastReceiver将会解析前一个BroadcastReceiver所存入的key为first的消息,
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MyReceiver2 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = getResultExtras(true);
//解析前一个BroadcastReceiver所存入的key为first的消息
String first = bundle.getString("first");
Toast.makeText(context, "第一个Broadcast存入的消息为:"+first,5000).show();
}
}
在AndroidManifest.xml文件中部署该BroadcastReceiver,并指定其优先级为0,配置片段如下:
<receiver android:name=".MyReceiver2">
<intent-filter android:priority="0">
<action android:name="broadcasttest.action.CRAZY_BROADCAST"/>
</intent-filter>
</receiver>
标签:
原文地址:http://www.cnblogs.com/jiww/p/5613621.html