Android

Android四大组件之BroadcastReceiver

2019-03-21  本文已影响19人  12313凯皇

一、概述

BroadcastReceiver是一种消息型组件,常用于在不同的组件乃至不同的应用之间传递消息。它是Android四大组件中唯一一种非必须在AndroidManifest.xml中注册的组件,它可以通过Context.registerReceiver()Context.unRegisterReceiver()来动态注册和解除。

完整的广播分为两个角色:既然有广播接收者(BroadcastReceiver),自然就得先有个广播发送者。由于广播的发送相对而言较为简单,所以我们常把精力集中在了广播接收器上面。

二、广播类型

广播的类型主要分为5类

系统操作 action
监听网络变化 ConnectivityManager.CONNECTIVITY_ACTION
关闭或打开飞行模式 Intent.ACTION_AIRPLANE_MODE_CHANGED
充电时或电量发生变化时 Intent.ACTION_BATTERY_CHANGED
电池电量低 Intent.ACTION_BATTERY_LOW
电池电量充足(即从电量低变化到饱满时会发出广播 Intent.ACTION_BATTERY_OKAY
系统启动完成后(仅广播一次) Intent.ACTION_BOOT_COMPLETED
按下照相时的拍照按键(硬件按键)时 Intent.ACTION_CAMERA_BUTTON
屏幕锁屏 Intent.ACTION_CLOSE_SYSTEM_DIALOGS
设备当前设置被改变时(界面语言、设备方向等) Intent.ACTION_CONFIGURATION_CHANGED
插入耳机时 Intent.ACTION_HEADSET_PLUG
未正确移除SD卡但已取出来时(正确移除方法:设置--SD卡和设备内存--卸载SD卡) Intent.ACTION_MEDIA_BAD_REMOVAL
插入外部储存装置(如SD卡) Intent.ACTION_MEDIA_CHECKING
成功安装APK Intent.ACTION_PACKAGE_ADDED
成功删除APK Intent.ACTION_PACKAGE_REMOVED
重启设备 Intent.ACTION_REBOOT
屏幕被关闭 Intent.ACTION_SCREEN_OFF
屏幕被打开 Intent.ACTION_SCREEN_ON
关闭系统时 Intent.ACTION_SHUTDOWN
重启设备 Intent.ACTION_REBOOT

注:当使用系统广播时,只需要在注册广播接收者是定义相关的action即可,并不需要手动发送广播,当系统有相关操作时会自动进行系统广播。

三、注册广播接收器

上面已经说过了,BroadcastReceiver可以不用在AndroidManifest.xml中注册,因此它有两种注册方式

<receiver 
    android:enabled=["true" | "false"]
 //此broadcastReceiver能否接收其他App的发出的广播
 //默认值是由receiver中有无intent-filter决定的:如果有intent-filter,默认值为true,否则为false
    android:exported=["true" | "false"]
    android:icon="drawable resource"
    android:label="string resource"
 //继承BroadcastReceiver子类的类名
    android:name=".mBroadcastReceiver"
 //具有相应权限的广播发送者发送的广播才能被此BroadcastReceiver所接收;
    android:permission="string"
 //BroadcastReceiver运行所处的进程
 //默认为app的进程,可以指定独立的进程
 //注:Android四大基本组件都可以通过此属性指定自己的独立进程
    android:process="string" >

 //用于指定此广播接收器将接收的广播类型
 //本示例中给出的是用于接收网络状态改变时发出的广播
 <intent-filter>
     <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
 </intent-filter>
</receiver>

// 选择在Activity生命周期方法中的onResume()中注册
@Override
  protected void onResume(){
      super.onResume();

    // 1. 实例化BroadcastReceiver子类 &  IntentFilter
     mBroadcastReceiver mBroadcastReceiver = new mBroadcastReceiver();
     IntentFilter intentFilter = new IntentFilter();

    // 2. 设置接收广播的类型
    intentFilter.addAction(android.net.conn.CONNECTIVITY_CHANGE);

    // 3. 动态注册:调用Context的registerReceiver()方法
     registerReceiver(mBroadcastReceiver, intentFilter);
 }


// 注册广播后,要在相应位置记得销毁广播
// 即在onPause() 中unregisterReceiver(mBroadcastReceiver)
// 当此Activity实例化时,会动态将MyBroadcastReceiver注册到系统中
// 当此Activity销毁时,动态注册的MyBroadcastReceiver将不再接收到相应的广播。
 @Override
 protected void onPause() {
     super.onPause();
      //销毁在onResume()方法中的广播
     unregisterReceiver(mBroadcastReceiver);
     
}

两种注册方式的区别

特别注意
对于不同注册方式的广播接收器回调OnReceive(Context context,Intent intent)中的context值是不一样的

广播类型 onReceive(context,intent)context返回值
静态注册(全局+应用内广播) ReceiverRestrictedContext
动态注册的全局广播 Activity Context
动态注册的应用内广播(LocalBroadcastManager方式 ) Application Context
动态注册的应用内广播(非LocalBroadcastManager方式 ) Activity Context

四、发送/接收广播

Intent intent = new Intent();
//对应BroadcastReceiver中intentFilter的action
intent.setAction(BROADCAST_ACTION);
//发送普通广播
sendBroadcast(intent);
Intent intent = new Intent();
//对应相应系统广播的action
intent.setAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
//发送系统广播
sendBroadcast(intent);
Intent intent = new Intent();
//对应广播的action
intent.setAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
//发送有序广播 第二个参数为permission权限
sendOrderedBroadcast(intent,null);

IntentFilter filter = new IntentFilter();
//添加action
filter.addAction(StaticClass.BROADCAST_LOGIN);
//注册receiver
registerReceiver(loginReceiver, filter);

五、示例

MainActivity中放上两个按钮,分别用于发送静态广播和动态广播。
首先是是实现两个BroadcastReceiver分别对应动态注册的广播接收器和静态注册的广播接收器:

//用于动态注册广播接收器
public class MyDynamicBroadcastReceiver extends BroadcastReceiver {

    private final String TAG = "DynamicReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: ");
        Toast.makeText(context,"动态注册的广播接收器 onReceive",Toast.LENGTH_SHORT).show();
    }
}
//静态注册广播接收器
public class MyStaticBroadcastReceiver extends BroadcastReceiver {

    private final String TAG = "StaticReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: ");
        Toast.makeText(context,"静态注册的广播接收器 onReceive",Toast.LENGTH_SHORT).show();
    }
}

然后AndroidManifest.xml中静态注册广播接收器:

<receiver
     android:name=".MyStaticBroadcastReceiver">
     <intent-filter>
          <action android:name="com.hu.yu.broadcastreceiverdemo.broadcastreceiver"/>
     </intent-filter>
 </receiver>

MainActivityonResume中动态注册,onPause中解除:

    @Override
    protected void onResume() {
        super.onResume();
        //动态注册广播接收器
        registerReceiver(dynamicBroadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销 动态注册的广播接收器
        unregisterReceiver(dynamicBroadcastReceiver);
    }

完整的Activity代码

public class MainActivity extends AppCompatActivity {

    public static final String ACTION_STATIC_BROADCAST_RECEIVER = "com.hu.yu.broadcastreceiverdemo.broadcastreceiver";
    public static final String ACTION_DYNAMIC_BROADCAST_RECEIVER = "com.hu.yu.broadcastreceiverdemo.dbroadcastreceiver";

    private IntentFilter filter;
    private MyDynamicBroadcastReceiver dynamicBroadcastReceiver;


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

        //初始化Action过滤器
        filter = new IntentFilter();
        filter.addAction(MainActivity.ACTION_DYNAMIC_BROADCAST_RECEIVER);

        dynamicBroadcastReceiver = new MyDynamicBroadcastReceiver();

        Button button1 = findViewById(R.id.btn_send_dynamic_broadcast);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送动态广播
                Intent intent = new Intent();
                intent.setAction(ACTION_DYNAMIC_BROADCAST_RECEIVER);
                sendBroadcast(intent);
            }
        });

        Button button2 = findViewById(R.id.btn_send_static_broadcast);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送静态广播
                Intent intent = new Intent();
                intent.setAction(ACTION_STATIC_BROADCAST_RECEIVER);
                //适配Android8.0系统 第一个参数为包名 第二个参数为接收器路径
                ComponentName componentName = new ComponentName("com.hu.yu.broadcastreceiverdemo",
                        "com.hu.yu.broadcastreceiverdemo.MyStaticBroadcastReceiver");
                intent.setComponent(componentName);
                sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //动态注册广播接收器
        registerReceiver(dynamicBroadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销 动态注册的广播接收器
        unregisterReceiver(dynamicBroadcastReceiver);
    }

}

log输出:


参考文章:Android四大组件:BroadcastReceiver史上最全面解析

上一篇下一篇

猜你喜欢

热点阅读