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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27062249/article/details/54962483

飞行模式:

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

 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();
                }
            }
        }
    }
};

展开阅读全文

没有更多推荐了,返回首页