I am writing a program which needs to be run in Android 2.0. I am currently trying to connect my android device to an embedded bluetooth chip. I have been given information as t
You're probably better off using the synchronous version so you don't have to deal with all the moving parts of setting up the BroadcastReceiver
. Since you are always doing this on the heels of discovery, the cached data will always be fresh.
Here the functionality of getting the UUID data encapsulated up into a method. This code was in one of the comments of the blog post you linked:
//In SDK15 (4.0.3) this method is now public as
//Bluetooth.fetchUuisWithSdp() and BluetoothDevice.getUuids()
public ParcelUuid[] servicesFromDevice(BluetoothDevice device) {
try {
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("getUuids", par);
Object[] args = {};
ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
return retval;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
You can then call this method anywhere in your code, passing it a BluetoothDevice
and getting back an array of UUIDs for that device's services (typically for small embedded stacks the array is only 1 item); something like:
// Save the device the user chose.
myBtDevice = btDevicesFound.get( arg2 );
//Query the device's services
ParcelUuid[] uuids = servicesFromDevice(myBtDevice);
// Open a socket to connect to the device chosen.
try {
btSocket = myBtDevice.createRfcommSocketToServiceRecord(uuids[0].getUuid());
} catch ( IOException e ) {
Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
} catch ( NullPointerException e ) {
Log.e( "Bluetooth Socket", "Null Pointer One" );
}
in the block you posted above.
As a side note, calling all this code in the manner you have will make your application sad later. The block of code calling connect()
and obtaining the streams should be done on a background thread because that method will block for a period of time and calling this code on the main thread will freeze your UI temporarily. You should move that code into an AsyncTask
or a Thread
like the BluetoothChat sample in the SDK does.
HTH