美文网首页
Android四大应用组件之BroadcastReceiver篇

Android四大应用组件之BroadcastReceiver篇

作者: flynnny | 来源:发表于2021-03-03 00:53 被阅读0次

    总结自Android四大应用组件之BroadcastReceiver篇
    Android四大应用组件之Activity篇https://www.jianshu.com/p/d22981a8ad0e
    Android四大应用组件之Service篇https://www.jianshu.com/p/f7d57803b86e
    Android四大应用组件之ContentProvider篇https://www.jianshu.com/p/5f783f3db22d
    Android四大应用组件之BroadcastReceiver篇https://www.jianshu.com/p/e6283dec21c7

    理论概述

    系统级跨应用(进程间通信)的事件处理。
    一个应用只要注册了对应的Receiver就会接受此广播

    1.png 2.png

    代码 (位于两个应用)

    广播接收器类继承BroadcastReceiver

    静态注册的

    public class MyBroadcastReceiver extends BroadcastReceiver{
      public void onReceive(Context content,Intent intent){
        //处理广播
        //静态注册
        String ss=  intent.getStringExtra("action");
      }
     }
    
    <receiver android:name="com.xxx1.MyBroadcastReceiver">
      <intent-filter>
        <action android:name="com.xxx1.MyR.action"/>
      </intent-filter>
    </receiver>
    

    发送广播

    //一般广播
    Intent intent = new Intent("com.xxx1.MyR.action");//和上面清单一致
    intent.putExtra("action","go");
    sendBroadcast(intent);
    

    在发送端app发送时创建了MyBroadcastReceiver ,处理完就销毁,再次发送,再次创建MyBroadcastReceiver

    动态注册

    public class MyBroadcastReceiver extends BroadcastReceiver{
      public void onReceive(Context content,Intent intent){
        //处理广播
        //静态注册
        String ss=  intent.getStringExtra("action");
      }
     }
    
    //activity:
    MyBroadcastReceiver  re;
    
    public void registBR(){
      if(re==null){
       re= new MyBroadcastReceiver ();
       //创建过滤器
        IntentFilter filter = new IntentFilter("com.xxx1.MyR.222");
        //注册receiver
        registerReceiver(re,filter);
      }else{
        //已经注册
      }
    }
    
    public void unregistBR(){
      if(re!=null){
        unregisterReceiver(re);
        re= null;
      } else{
        //  还没注册
      }
    }
    
    onDestroy(){
      super.onDestroy();
      unregistBR();
    }
    

    在动态调用方法时才创建MyBroadcastReceiver对象。而且不注销的话不销毁。

    *一般来说动态注册比静态注册先接受到消息,因为静态注册先创建类再创建对象。动态直接创建对象。

    3.png

    有序广播

    4.png
    //一般广播
    Intent intent = new Intent("com.xxx1.MyR.action");//和上面清单一致
    intent.putExtra("action","go");
    sendOrderBroadcast(intent);
    
    <receiver android:name="com.xxx1.MyBroadcastReceiver">
      <intent-filter android:priority="2147483647">//优先级
        <action android:name="com.xxx1.MyR.action"/>
      </intent-filter>
    </receiver>
    
    if(isOrderedBroadcast()){
      abortBroadcast();//中断广播
    }
    

    相关文章

      网友评论

          本文标题:Android四大应用组件之BroadcastReceiver篇

          本文链接:https://www.haomeiwen.com/subject/nhptqltx.html