Below is the snippet to retrieve list of bonded devices.
Set pairedDevices = btAdapter.getBondedDevices();
getName() returns the public identifier of the devices
getAddress() returns the MAC address of the device
In order to find the nearby devices, which is called scanning we need to use the below code
btAdapter.startDiscovery() is the method to start scanning operation. btAdapter.cancelDiscovery() will cancel the initiated scanning
These two methods are working via Asynchronous feedbacks by Broadcast Receivers.
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcellableExtra(BluetoothDevice.EXTRA_DEVICE);
}
}
}
Connecting to a Device:
Similar to any other connection, there is a Server and Client which communicates via RFCOMM sockets.
On Android, RFCOMM sockets are represented as BluetoothSocket object.
Below is the code to connect to a Bluetooth Device
public class ConnectThreads extends Thread
{
private BluetoothSocket bTSocket;
public boolean connect(BluetoothDevice btDevice, UUID uuid)
{
BluetoothSocket socket = null;
try
{
socket = btDevice.createRFCommSocketToServiceRecord()
}
catch(Exception ex)
{
ex.printStackTrace();
}
try
{
socket.connect();
}
catch(Exception ex)
{
ex.printStackTrace();
try
{
}
catch(Excpetion ex)
{
}
}
}
}
References:
No comments:
Post a Comment