简体   繁体   English

registerReceiver BluetoothAdapter.ACTION_STATE_CHANGED不起作用

[英]registerReceiver BluetoothAdapter.ACTION_STATE_CHANGED not working

I'm working with Android Oreo and bluetooth. 我正在使用Android Oreo和蓝牙。 I want to get from a broadcast info when a new device is found and when Bluetoothadapter has changed its state. 当找到新设备并且Bluetoothadapter更改了状态时,我想从广播信息中获取信息。 I have the following code: 我有以下代码:

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

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

why do I recieve signal with BEReceiver_ADD but not with BEReceiver_Adapter? 为什么我要用BEReceiver_ADD接收信号但不能用BEReceiver_Adapter接收信号? I never enter into BEReceiver_Adapter. 我从不进入BEReceiver_Adapter。 What's wrong? 怎么了?

NOTE: I tried the same code with Android 4.1 and it works. 注意:我在Android 4.1上尝试了相同的代码,并且可以正常工作。 Why is not working with Android 8.0? 为什么不能使用Android 8.0?

BluetoothAdapter.ACTION_STATE_CHANGED produced by bluetooth adapter state changing, like turn on/off. BluetoothAdapter.ACTION_STATE_CHANGED由蓝牙适配器状态更改(例如打开/关闭)产生。 Also in newer android versions method of getting adapter object changed, so the code to have backward compatibility should look like this: 同样在更新的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();

Also I may recommend to use library to work with Rfcomm profile - because it significantly reduce amount of support code and gives comfortable in callbacks. 我也可能建议使用来与Rfcomm配置文件一起使用-因为它大大减少了支持代码的数量,并且使回调很舒适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM