Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CONNECTION_STATE_CHANGED and STATE_CHANGED

What's the difference between Action CONNECTION_STATE_CHANGED and STATE_CHANGED in Android Bluetooth Receiver ?

            else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED .equals(action)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
                    BluetoothAdapter.STATE_DISCONNECTED);
                if (state == BluetoothAdapter.STATE_CONNECTED) {
                    //nothing
                } else {

                }
        } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (state == BluetoothAdapter.STATE_OFF) {

            }
        }
like image 801
Claudio Ferraro Avatar asked Feb 13 '23 01:02

Claudio Ferraro


1 Answers

According to the docs the difference is the following:

ACTION_CONNECTION_STATE_CHANGED

Intent used to broadcast the change in connection state of the local Bluetooth adapter to a profile of the remote device.

ACTION_STATE_CHANGED

The state of the local Bluetooth adapter has been changed. For example, Bluetooth has been turned on or off.

In other words one Intent is for changes in the connection state and the other one for state changes of the Bluetooth adapter itself.

EDIT:

To detect if a device moves in and out of range you need to use the following intents:

  • ACTION_ACL_CONNECTED: link to documentation
  • ACTION_ACL_DISCONNECTED: link to documentation

For both of those you need the normal BLUETOOTH permission and the BLUETOOTH_ADMIN permission:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

The intent filter for your BroadcastReceiver would look something like this:

<intent-filter> 
    <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>

Here is the general documentation about BluetoothDevice.

like image 76
Xaver Kapeller Avatar answered Apr 30 '23 00:04

Xaver Kapeller