Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Connecting to the Paired OBD2 Device
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
BluetoothSocket mmSocket;
UUID MY_UUID = UUID.fromString("2cf6e0ab-5417-4595-8564-487134f99ccd");
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
mmSocket = obd2Device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
} catch (IOException connectException) {
// if the connection cannot be made with UUID,
// then connect directly by using a hidden method using reflections
try {
Class<?> clazz = mmSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(1)};
mmSocket = (BluetoothSocket) m.invoke(mmSocket.getRemoteDevice(), params);
} catch (Exception e) {
Log.e(TAG, "Could not connect using reflections", e);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.