0

How do I make a Switch to toggle automatically (it has to work manually as well) based on the state of bluetooth? What method do I need?

I have a simple switch that I use to turn the bluetooth on and off manually. And it works fine, however if the bluetooth is switched on/off from another app or in phone settings the Switch of course does not change.

BluetoothAdapter mBluetAdapter = BluetoothAdapter.getDefaultAdapter();
Switch mySwitch = findViewById(R.id.blueSwc);
mySwitch.setChecked(mBluetAdapter.isEnabled()); //this only works at the beginning
raff5184
  • 344
  • 1
  • 2
  • 15

1 Answers1

1

Your only problem is that you have to listen to the changes of the Bluetooth state. In order to do that you'll need a BroadcastReceiever that listens to the bluetooth adapter state. The rest of your code regarding this is ok.

 private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch(state) {
                case BluetoothAdapter.STATE_OFF:
                    mySwitch.setChecked(false);
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:

                    break;
                case BluetoothAdapter.STATE_ON:
                    mySwitch.setChecked(true);
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:

                    break;
            }

        }
    }
};

Register it like this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver1, filter1);

    ...
}

And unregister it like

@Override
protected void onDestroy() {
    super.onDestroy();

    unregisterReceiver(mBroadcastReceiver1);
}

Taken from this answer that has very detailed description of how to use BroadcastReceiver of such type.

Hope it helps.

Pavlo Ostasha
  • 14,527
  • 11
  • 35