Skip to content

Instantly share code, notes, and snippets.

@arkty
Created September 9, 2014 09:42
Show Gist options
  • Save arkty/4ead2f8cda913ea03ff6 to your computer and use it in GitHub Desktop.
Save arkty/4ead2f8cda913ea03ff6 to your computer and use it in GitHub Desktop.
Bluetooth helper
public static final UUID RFCOMM_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static BluetoothSocket createSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
return createSocketPostGingerbread(device);
}
else {
return createSocketPreGingerbread(device);
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private static BluetoothSocket createSocketPostGingerbread(BluetoothDevice device) throws IOException {
return device.createInsecureRfcommSocketToServiceRecord(RFCOMM_UUID);
}
private static BluetoothSocket createSocketPreGingerbread(BluetoothDevice device) throws IOException {
try {
BluetoothSocket socket = null;
Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor(
int.class, int.class, boolean.class, boolean.class, BluetoothDevice.class, int.class, ParcelUuid.class);
if(constructor == null)
throw new IOException("can't find the constructor for socket");
constructor.setAccessible(true);
Field f_rfcomm_type = BluetoothSocket.class.getDeclaredField("TYPE_RFCOMM");
f_rfcomm_type.setAccessible(true);
int rfcomm_type = (Integer)f_rfcomm_type.get(null);
socket = constructor.newInstance(new Object[] { rfcomm_type, -1, false, true, device, -1,new ParcelUuid(RFCOMM_UUID)} );
return socket;
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(InvocationTargetException e) {
if(e.getCause() instanceof IOException) {
throw (IOException)e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment