Last active
June 17, 2018 01:05
-
-
Save brandonhenricks/5858655 to your computer and use it in GitHub Desktop.
Bluetooth Socket Creation for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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