丿你猜我是谁

导航

广播的简单使用BroadcastReceiver

1、定义BroadcastReceiver  继承BroadcastReceiver 重写onReceive方法

2、注册广播

  A、AndroidManifest注册 android:priority="100"表示广播顺序,取值在-1000到1000之间,越大优先级越高   

    <receiver android:name="com.example.broadcast.MyBroadcastReceiver1">  

              <intent-filter android:priority="100">  

                  <action android:name="android.intent.action.MY_BROADCAST1"/>  

                  <category android:name="android.intent.category.DEFAULT" />  

              </intent-filter>  

         </receiver>

 

  B、代码注册  在Activity的onCreate方法中加入一下代码,需要在onDestroy方法中调用unregisterReceiver()方法解除广播,不然会报出异常

    MyBroadcastReceiver receiver;

    IntentFilter filter = new IntentFilter();  

    filter.addAction("android.intent.action.MY_BROADCAST1");  

    registerReceiver(receiver, filter); 

3、发送广播

  通过  BroadcastReceiver 中的 isOrderedBroadcast()方法判断是普通广播(false)还是有序广播(true)

  A、普通广播

    发送的是普通广播,所有订阅者都有机会获得并进行处理。

    Intent intent = new Intent("android.intent.action.MY_BROADCAST1");  

         intent.putExtra("msg", "aaaaaaaaa");  //发送的广播消息

           sendBroadcast(intent);  

  B、有序广播

    发送的是有序广播,系统会根据接收者声明的优先级按顺序逐个执行接收者,

    前面的接收者有权通过调用BroadcastReceiver.abortBroadcast()终止广播,

    如果广播被前面的接收者终止,后面的接收者就再也无法获取到广播。

    对于有序广播,前面的接收者可以将处理结果存进广播Intent,然后传给下一个接收者。

    Intent intent = new Intent("android.intent.action.MY_BROADCAST1");  

           intent.putExtra("msg", "aaaaaaaaa");  //发送的广播消息

           sendOrderedBroadcast(intent,null); 

 

 

public class MyBroadcastReceiver1 extends BroadcastReceiver {  

  private static final String TAG = "MyBroadcastReceiver1";  

  @Override  

  public void onReceive(Context context, Intent intent) {  

  String msg = intent.getStringExtra("msg");   //原广播发送的内容 

  if ( isOrderedBroadcast()) {

        Toast.makeText(context,"有序广播"+msg,Toast.LENGTH_LONG).show();

    //有序广播可以将收到的广播进行处理保存进广播的Intent发送给下一个广播

    Bundle bundle = new Bundle();  

        bundle.putString("msg", msg+ "这是追加的消息,保存后传递给下一个广播接收者");  

        setResultExtras(bundle); 

//    abortBroadcast();  //终止广播

      }else {

        Toast.makeText(context,"普通广播"+msg,Toast.LENGTH_LONG).show();

  } 

   }  

 

public class MyBroadcastReceiver2 extends BroadcastReceiver {  

  private static final String TAG = "MyBroadcastReceiver2";  

  @Override  

  public void onReceive(Context context, Intent intent) {  

      String msg = intent.getStringExtra("msg");  //原广播发送的消息

  if ( isOrderedBroadcast()) { //发送的有序广播

    Bundle bundle = getResultExtras(true);

        String msgs = bundle.getString("msg");//上一个广播处理之后的广播消息,上一个广播没做处理则msgs为空

    Toast.makeText(context,"有序广播"+msgs,Toast.LENGTH_LONG).show();

    Log.e(TAG, msg);  

  }else{

    Toast.makeText(context,"普通广播"+msg,Toast.LENGTH_LONG).show();

  } 

   }  

 

posted on 2016-08-04 15:46  丿你猜我是谁  阅读(62)  评论(0)    收藏  举报