Reputation: 20123
I'm suppose to write an application that will act as the bluetooth client. What I'm trying to do is figure out is what would be the best way to figure out if the specific device that I'm supporting is in range without attempting to do a BluetoothDevice.connect() on it all of the time and failing if it's not in range. Here we're assuming that the device as already been paired.
I'm afraid that it would be bad practice to attempt to connect to a specific device all of the time until it's in range. Seems to me that it would be bad for the battery.
Would anyone know of any methods or concepts that should be used to accomplish what I'm trying to do?
Thanks!
Upvotes: 18
Views: 8012
Reputation: 256
Start device discovery and check for the BluetoothDevice BONDED state if a new device is discovered.
val isBonded = discoveredDevice.bondState == BluetoothDevice.BOND_BONDED
Upvotes: 0
Reputation: 327
You can follow below way :
Upvotes: 1
Reputation: 1919
Ok, so as I understand from your question is you want to get name of device you paired with, and if its in range??
So here is the solution:-
class DeviceDetails{ public String name; public String address; public BluetoothDevice remoteDevice; }
You need to connect and pair your devices as explained here, once this is done and connection is made, create an object of DeviceDetails.
DeviceDetails selectedDevice;
and if you have a custom adapter to show list of devices pass on the position of from the view to selectedDevice reference. Example :- selectedDevice = adapter.getItem(pos);
Now you have the SelectedDevice object which you have selected to pair, thus you can save its address and name in
preferences.
Example:-
savePairedDeviceInfo(selectedDevice.name, selectedDevice.address);
public void savePairedDeviceInfo(String name, String addr)
{
if(name != null && !name.equalsIgnoreCase(""))
editor.putString(PNAME_OF_DEVICE, name);
if(addr != null && !addr.equalsIgnoreCase(""))
editor.putString(MAC_ADDRESS_OF_DEVICE, addr);
editor.commit();
}
Now, next time when ever you want to check if setup of pairing is done or not check for name and address of the device by getting values from preferences. Use a check(if cond.) to return true that older device that was paired was same or some other.
If paired device is in range you would get the same value else it would try to pair with some other device.
Let me know, if you understood from my explanation or not.
Upvotes: 0