Broadcast入门1

示例:监听电量变化(动态注册)

    private BatteryLevelReceiver batteryLevelReceiver;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: !");
        initView();
        initBroadcast();
    }

    private void initBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        // 设定监听的广播类型
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
        intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
        // 实例化一个广播接收器
        batteryLevelReceiver = new BatteryLevelReceiver();
        // 注册广播接收器
        this.registerReceiver(batteryLevelReceiver, intentFilter);
    }


    private class BatteryLevelReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取监听广播的类型
            String action = intent.getAction();
            switch (action) {
                case Intent.ACTION_BATTERY_CHANGED:
                    Log.d(TAG, "onReceive: 电量变化"  + intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0));
                    break;
                case Intent.ACTION_BATTERY_LOW:
                    Log.d(TAG, "onReceive: 低电量");
                    break;
                case Intent.ACTION_BATTERY_OKAY:
                    Log.d(TAG, "onReceive: 电量ok");
                    break;
                default:
                    break;
            }
        }
    }

        
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(batteryLevelReceiver);
    }

从示例中可以看出,如果仅实现动态注册——监听广播,需要实现的部分如下:

1.实现一个receiver,继承自BroadcastReceiver。重写onReceive方法,在里面实现监听到具体广播后的逻辑。

2.实例化并注册该receiver,在注册时通过在intentFilter里设置action来指定监听的广播类型。

3.在销毁活动时取消注册。否则会导致内存泄漏。

该示例展示的是动态注册方法。安卓系统的一些系统级别的广播是要求动态注册的。但是也可以发现动态注册存在的一个问题,就是在程序启动之后才会生效。

示例:监听开机完成(静态注册)

public class BootCompleteReceiver extends BroadcastReceiver {
    private static final String TAG = BootCompleteReceiver.class.getSimpleName();
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: " + intent.getAction());
        Toast.makeText(context, "boot complete", Toast.LENGTH_SHORT).show();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.activitydemo">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <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/Theme.MyApplication">
        <activity android:name="com.example.activitydemo.MainActivity"
            android:configChanges="keyboardHidden|screenSize|orientation"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".broadcast.BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <!--  设置监听action          -->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

从示例中可以看出,静态注册—监听广播需要实现的内容为:

1.自定义receiver类,这一项与动态注册相同。

2.在manifest里注册该revicever,指定监听的事件类型。

可以看到静态注册方法可以在程序不启动的情况下监听事件。同时,该监听行为是一直持续的,因此比较消耗资源。

此外,在广播接收器中不允许开启线程,当onReceive运行了比较长的时间而没有返回的时候,程序会报错。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值