Skip to content

Instantly share code, notes, and snippets.

@brandonhenricks
Last active June 17, 2018 01:05
Show Gist options
  • Save brandonhenricks/5858655 to your computer and use it in GitHub Desktop.
Save brandonhenricks/5858655 to your computer and use it in GitHub Desktop.
Bluetooth Socket Creation for Android
public BluetoothSocket createSocketFromAddress(String remoteAddress) {
if (TextUtils.isEmpty(remoteAddress)) return null;
// SPECIAL UUID FOR DEVICE CONNECTION
UUID mSPUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothSocket mSocket = null;
BluetoothDevice mDevice = getAdapter().getRemoteDevice(remoteAddress.toUpperCase());
// CANCEL DISCOVERY
getAdapter().cancelDiscovery();
// CREATE SOCKET
try {
mSocket = mDevice.createRfcommSocketToServiceRecord(mSPUUID);
} catch (Exception e) {
mSocket = null;
}
if (null == mSocket) {
try {
Method m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mSocket = (BluetoothSocket) m.invoke(mDevice, Integer.valueOf(1));
} catch (Exception e) {
mSocket = null;
}
}
if (null == mSocket) {
try {
mSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mSPUUID);
} catch (Exception e) {
mSocket = null;
}
}
return mSocket;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment