美文网首页
Android--BroadCastReceiver

Android--BroadCastReceiver

作者: 始終上路过 | 来源:发表于2019-08-15 21:19 被阅读0次

学校里都会装有大喇叭,这些喇叭都是接人到学校的广播室的,一旦有什么重要的通知,就会播放一条广播来告知全校的师生。类似的工作机制其实在计算机领域也有很广泛的应用,如果你了解网络通信原理应该会知道,在一个IP网络范围中,最大的IP地址是被保留作为广播地址来使用的。比如某个网络的IP范围是192.168.0.XXX, 子网掩码是255.255.255.0,那么这个网络的广播地址就是192.168.0.255。 广播数据包会被发送到同一网络上的所有端口,这样在该网络中的每台主机都将会收到这条广播。

其实BroadcastReceiver就是应用程序间的全局大喇叭,即通信的一个手段, 系统自己在很多时候都会发送广播,比如电量低或者充足,刚启动完,插入耳机,输入法改变等, 发生这些时间,系统都会发送广播,这个叫系统广播,每个APP都会收到,如果你想让你的应用在接收到 这个广播的时候做一些操作,比如:系统开机后,偷偷后台跑服务哈哈,这个时候你只需要为你的应用 注册一个用于监视开机的BroadcastReceiver,当接收到开机广播就做写偷偷摸摸的勾当~ 当然我们也可以自己发广播,比如:接到服务端推送信息,用户在别处登录,然后应该强制用户下线回到 登陆界面,并提示在别处登录

广播机制简介

为什么说Android中的广播机制更加灵活呢?这是因为Android中的每个应用程序都可以对自已感兴趣的广播进行注册,这样该程序就只会接收到自己所关心的广播内容,这些广播可能是来自于系统的,也可能是来自于其他应用程序的。Android 提供了一套完整的API,允许应用程序自由地发送和接收广播。 而接收广播的方法则需要引入一个新的概念——广 播接收器( Broadcast Receiver )。

标准广播( Normal broadcasts)

标准广播是一种完全异步执行的广播,在广播发出之后,所有的广播接收器几乎都会在同一时刻接收到这条广播消息,因此它们之间没有任何先后顺序可言。这种广播的效率会比较高,但同时也意味着它是无法被截断的。


标准广播示意图

有序广播( Ordered broadcasts)

有序广播则是一种同步执行的广播,在广播发出之后,同一时刻只会有一个广播接收器能够收到这条广播消息,当这个广播接收器中的逻辑执行完毕后,广播才会继续传递。所以此时的广播接收器是有先后顺序的,优先级高的广播接收器就可以先收到广播消息,并且前面的广播接收器还可以截断正在传递的广播,这样后面的广播接收器就无法收到广播消息了。


有序广播示意图

实现一个广播

1,先创建一个广播,写一个类继承BroadcastReceiver

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      
    }
}

2,注册一个广播

静态广播注册

在清单文件中注册广播就是静态的

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <!--我是一个广播-->
        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.zhang.broad"></action>
            </intent-filter>
        </receiver>
        <!--广播结束-->
        
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
动态广播注册
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 private Button sendId;
 private  MyReceiver myReceiver;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     sendId = findViewById(R.id.send_id);
     sendId.setOnClickListener(this);
     //1,创建一个广播
     myReceiver = new MyReceiver();
     //添加广播过滤器
     IntentFilter intentFilter = new IntentFilter();
     //添加action
     intentFilter.addAction(BroadcastConst.ACTION);
     //注册
     registerReceiver(myReceiver,intentFilter);
 }

 @Override
 protected void onDestroy() {
     super.onDestroy();
     //注销广播
     unregisterReceiver(myReceiver);
 }
}
发送一个无序广播
Intent intent = new Intent();
     intent.setAction("com.zhang.broad");
     Bundle bundle = new Bundle();
     bundle.putInt("msg",123);
     intent.putExtras(bundle);
     sendBroadcast(intent);
发送一个有序广播
Intent intent1 = new Intent();
 intent1.setAction("com.zhang.broad");
 //第一个参数是intent 二是权限名.
 sendOrderedBroadcast(intent1,null);

完整的

<application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
       <receiver
           android:name=".MyReceiver2"
           android:enabled="true"
           android:exported="true">
           <intent-filter android:priority="1000">
               <action android:name="com.zhang.broad"></action>
           </intent-filter>

       </receiver>
       <receiver
           android:name=".MyReceiver"
           android:enabled="true"
           android:exported="true">
           <intent-filter android:priority="900">
               <action android:name="com.zhang.broad" />
           </intent-filter>
       </receiver>

       <activity android:name=".MainActivity">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>

main:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button sendId;
    private  MyReceiver myReceiver;
    private Button sendOrderId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        sendOrderId = findViewById(R.id.send_order_id);
        sendOrderId.setOnClickListener(this);
        sendId = findViewById(R.id.send_id);
        sendId.setOnClickListener(this);
        //1,创建一个广播
//        myReceiver = new MyReceiver();
//        //添加广播过滤器
//        IntentFilter intentFilter = new IntentFilter();
//        //添加action
//        intentFilter.addAction(BroadcastConst.ACTION);
//        //注册
//        registerReceiver(myReceiver,intentFilter);


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.send_id:
                Intent intent = new Intent();
                intent.setAction("com.zhang.broad");
                Bundle bundle = new Bundle();
                bundle.putInt("msg",123);
                intent.putExtras(bundle);
                sendBroadcast(intent);
                break;

            case R.id.send_order_id:
                Intent intent1 = new Intent();
                intent1.setAction("com.zhang.broad");
                sendOrderedBroadcast(intent1,null);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播
        unregisterReceiver(myReceiver);
    }
}

第一个广播

public class MyReceiver extends BroadcastReceiver {

   private static final String TAG = "MyReceiver";
   @Override
   public void onReceive(Context context, Intent intent) {
       //TODO 1:获取action
       String action = intent.getAction();
       if(BroadcastConst.ACTION.equals(action)){
//            Bundle extras = intent.getExtras();
//            int msg = extras.getInt("msg");
           Log.i(TAG, "onReceive: ");
       }
   }
}

第二个广播

public class MyReceiver2 extends BroadcastReceiver {
   private static final String TAG = "MyReceiver2";
   @Override
   public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();
       if(action.equals("com.zhang.broad")){

           Log.i(TAG, "onReceive: +++");
           //判断是不是有序广播
           if(isOrderedBroadcast()){
           //中断一个广播
               abortBroadcast();
           }
       }
   }
}
皮皮毛毛

相关文章

  • Android--BroadCastReceiver

    学校里都会装有大喇叭,这些喇叭都是接人到学校的广播室的,一旦有什么重要的通知,就会播放一条广播来告知全校的师生。类...

网友评论

      本文标题:Android--BroadCastReceiver

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