1 public class Receiver extends BroadcastReceiver { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 // TODO Auto-generated method stub 5 Bundle bundle=intent.getExtras(); 6 } 7 8 }
1 <receiver android:name="com.example.receiver.Receiver"> 2 <intent-filter android:priority="1000"> 3 <action android:name="android.intent.action.ACTION_SHUTDOWN"/> 4 </intent-filter> 5 </receiver>
1 @Override 2 protected void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 setContentView(R.layout.activity_main); 5 6 receiver = new Receiver(); 7 IntentFilter filter=new IntentFilter("com.broadcast.ORDER"); 8 filter.setPriority(1000); 9 registerReceiver(receiver, filter); 10 } 11 12 @Override 13 protected void onDestroy() { 14 // TODO Auto-generated method stub 15 super.onDestroy(); 16 unregisterReceiver(receiver); 17 }
1 Intent intent=new Intent("com.broadcast.NORMAL"); 2 sendBroadcast(intent,null);
1 Intent intent=new Intent("com.broadcast.ORDER"); 2 intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);//包含从未启动过的程序(3.1以后默认不包含),也可以不写 3 sendOrderedBroadcast(intent,null);//不指定权限,赋值为null
intent.putExtra("data","添加数据");
获取各自对应的数据
intent.getStringExtra("data");
b、ResultAPI传递数据,有序广播可以使用ResultAPI传递数据
1 Bundle bundle=new Bundle(); 2 bundle.putString("name","张三"); 3 bundle.putInt("age",21); 4 sendOrderedBroadcast(intent,null,null,null,1,"MainActivity",bundle);
获取各自的数据
1 int code=getResultCode();//结果数据中的int型参数 2 String data=getResultData();//结果数据中String型参数 3 Bundle bundle=getResultExtras(true); //结果数据中的bundle,若之前的操作结果数据bundle改为null,表示前面没有bundle集合true就会返回一个new Bundle(),创建一个集合,false的话则返回null,因为之前就没有bundle集合
1 bundle.putString("name","王族"); 2 bundle.putInt("age",25); 3 setResult(6,"Paris",bundle);//修改Result数据,后面的接收者将收到这个修改后的数据
Android之BroadcastReceiver组件,布布扣,bubuko.com
原文:http://www.cnblogs.com/myxiaoQ/p/3650076.html