Android功能记录(七) ------ 蓝牙监听广播

项目中只用到了监听蓝牙状态与连接断开,以下是代码:

注册监听:

IntentFilter statusFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
mContext.registerReceiver(mStatusReceive, statusFilter);

IntentFilter connectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
mContext.registerReceiver(mStatusReceive, connectedFilter);

IntentFilter DisConnectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
mContext.registerReceiver(mStatusReceive, DisConnectedFilter);

监听处理:

private BroadcastReceiver mStatusReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch(intent.getAction()){
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch(blueState){
                        case BluetoothAdapter.STATE_TURNING_ON:
                            break;
                        case BluetoothAdapter.STATE_ON:
                            if(isRestartScan && !isConnect)
                            {
                                Log.e(TAG, "BroadcastReceiver:开始扫描");
                                //开始扫描
                                startScan();
                            }
                            Log.e(TAG, "BroadcastReceiver: " +  isRestartScan + " "+(!isConnect));
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            isRestartScan = true;
                            isConnect = false;
                            break;
                        case BluetoothAdapter.STATE_DISCONNECTED:
                            isConnect = false;
                            break;
                    }
                    break;
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    BluetoothDevice conDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d("aaa", conDevice.getName() + " connected");
                    break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    BluetoothDevice disConDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d("aaa", disConDevice.getName() + " disconnected");
                    break;
            }
        }
};

参考链接:

           1.android 蓝牙设备监听广播 : https://www.cnblogs.com/lesliefang/p/5445684.html

你可能感兴趣的:(Android)