registerReceiver BluetoothAdapter.ACTION_STATE_CHANGED不起作用

时间:2019-02-10 01:46:40

标签: android android-intent bluetooth android-broadcastreceiver bluetoothadapter

我正在使用Android Oreo和蓝牙。当找到新设备并且Bluetoothadapter更改了状态时,我想从广播信息中获取信息。我有以下代码:

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);

    registerReceiver(BEReceiver_ADD, filter);
    registerReceiver(BEReceiver_Adapter, filter2);

为什么我要用BEReceiver_ADD接收信号但不能用BEReceiver_Adapter接收信号?我从不进入BEReceiver_Adapter。怎么了?

注意::我在Android 4.1上尝试了相同的代码,并且可以正常工作。为什么不能使用Android 8.0?

1 个答案:

答案 0 :(得分:1)

BluetoothAdapter.ACTION_STATE_CHANGED由蓝牙适配器状态更改(例如打开/关闭)产生。同样在更新的android版本中,更改适配器对象的方法也是如此,因此具有向后兼容性的代码应如下所示:

BluetoothAdapter bluetoothAdapter = null;
if(android.os.Build.VERSION.SDK_INT >= 18) { 
     BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); 
     bluetoothAdapter = bluetoothManager.getAdapter(); 
} else bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

我也建议使用library处理Rfcomm配置文件-因为它大大减少了支持代码的数量,并且使回调很舒适。