Created
August 28, 2019 23:45
-
-
Save rohanmendon/cccc5e493983fc0e8509771b81f5e85a to your computer and use it in GitHub Desktop.
Connecting to the Paired OBD2 Device
This file contains hidden or 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
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. | |
mmSocket.connect(); | |
} 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); | |
Thread.sleep(500); | |
mmSocket.connect(); | |
} 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