Search code examples
javaandroidandroid-studiobluetooth-lowenergyandroid-bluetooth

How to connect paired bluetooth device on app startup in Android Studio?


Is there any way to automatically connect a specific device via Bluetooth LE on app startup?

I've been scrolling through stack overflow for the past few hours and have seen a number of similar questions, although majority are quite outdated and deal with reflections or other complex methods that I can't quite comprehend (these methods I've tried to implement, but not successfully, as I didn't really understand what was going on).

So far, I've managed to find the device by its friendly name, although I have no clue what to execute in that if statement. This is within my MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    ...
    if (bluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(),"Bluetooth not supported",Toast.LENGTH_SHORT).show();

    } else {
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if(pairedDevices.size()>0){
            for(BluetoothDevice device: pairedDevices){

                if (deviceName.equals(device.getName())) {

                    //Device found!
                    //Now how do I pair it?

                    break;
                }
    ...


Solution

  • Ended up scrolling through the source code for this app, particularly the SerialSocket, SerialService and SerialListener files which completely solved my problem.