简体   繁体   中英

registerReceiver BluetoothAdapter.ACTION_STATE_CHANGED not working

I'm working with Android Oreo and bluetooth. I want to get from a broadcast info when a new device is found and when Bluetoothadapter has changed its state. 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? I never enter into BEReceiver_Adapter. What's wrong?

NOTE: I tried the same code with Android 4.1 and it works. Why is not working with Android 8.0?

BluetoothAdapter.ACTION_STATE_CHANGED produced by bluetooth adapter state changing, like turn on/off. Also in newer android versions method of getting adapter object changed, so the code to have backward compatibility should look like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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