Search code examples
androidbluetoothandroid-bluetooth

Recognizing a bluetooth connection


I'd like to start an application when a specific device BT is connected.

I do not want to use IFTTT, I'd like to write my own application able to autonomously implements what IFTTT does for any app: start when the event on bluetooth connection on device xxx is done.

how can I do that?


Solution

  • First, you need to detect that smartphone is connected to a BLE device. You can do that in BluetoothGattCallback's onConnectionStateChange() by checking wether newState is equal to BluetoothGatt.STATE_CONNECTED.

    Then, start your target application's activity:

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    
        if (newState == BluetoothGatt.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
            // start your target application's activity here
            Intent intent = new Intent(com.yourapp.ACTION);
            startActivity(intent);
        }
    }