Bring the Bluetooth pairing dialog to the front panel

I have a simple service for connecting Bluetooth devices, and it looks like this:

protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); if(!extras.containsKey("bluetoothAddress")) return; String bluetoothAddress = extras.getString("bluetoothAddress"); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if(!adapter.isEnabled()) { adapter.enable(); } BluetoothDevice device = adapter.getRemoteDevice(bluetoothAddress); device.createBond(); } 

It works great, except that sometimes a pair dialog appears, and sometimes it appears in my notification bar, and I have to open it manually. Is there any way to make sure that he always appears at the front?

I tried using Google, and the only thing I can find is that if you stay in the bluetooth settings, it always appears, but that seems like an ugly solution. The reason for all this is that I work with automation and want to make sure that when I start my service, I get that the pair dialogue can just click “Pair”.

+5
source share
2 answers

I had the same problem. I found this message that explains when the dialog is displayed or not: Request for Bluetooth pairing in the notification bar?

Resuming, it depends on the result of the shouldShowDialogInForeground () method.

Quote from the post:

... there are ways to make a dialogue:

  • If the device has recently been in discovery mode
  • If the device has recently detected
  • If a device was recently selected in the device builder
  • If Bluetooth settings are displayed

In my case, in order to make the dialog box appear, I started and canceled the detection before trying to execute a pair ...

Code / Hack

 BluetoothAdapter.getDefaultAdapter().startDiscovery(); //Give it some time before cancelling the discovery Thread.sleep(1000); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); //Then do the LeScan and connect to the device 

PS : I know that this is a terrible hack, but this is the only way to make me work, and pairing should only be done once for the device, so it's not that scary ... Also, if anyone finds the best way, I am open to suggestions

+7
source

I use the following code to solve the problem

 if(!BluetoothAdapter.getDefaultAdapter().isDiscovering()) BluetoothAdapter.getDefaultAdapter().startDiscovery(); //make sure that the device is in discovering while (!BluetoothAdapter.getDefaultAdapter().isDiscovering()); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); 
0
source

Source: https://habr.com/ru/post/1203801/


All Articles