Android 平时用到比较多的广播之飞行模式和耳机插拔

飞行模式:

判断当前是否处于飞行模式:

 final boolean isAirplaneModeOn =                     Settings.System.getInt(getActivity().getContentResolver(),
                        Settings.System.AIRPLANE_MODE_ON, 0) != 0;

监听飞行模式状态:

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
BroadcastReceiver airPlaneModeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("tlh", "Service state changed");
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object o = bundle.get("state");
            Log.e("tlh", o.toString());
            switch (o.toString()) {
                case "false":
                    Log.e("tlh", "AirPlaneMode ----- false.");
                 break;
                case "true":
                    Log.e("tlh", "AirPlaneMode ----- true");
                    break;
                default:
                    Log.e("tlh", "Set AirPlaneMode default.");
                    break;
            }

        } else {
            Log.d("tlh", "bundle is null");
        }
    }



检测耳机插入拔出:


	Action: Intent.ACTION_HEADSET_PLUG
	获取状态:int i= intent.getIntExtra("state", 0);
	值:i=1,代表耳机插入;i=2,代表耳机拔出
栗子:
private BroadcastReceiver headsetDetectReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
            if (intent.hasExtra("state")) {
                int state = intent.getIntExtra("state", 0);
                if (state == 1) {
                    Toast.makeText(context, "插入耳机", Toast.LENGTH_SHORT).show();
                } else if (state == 0) {
                    Toast.makeText(context, "拔出耳机", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值