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.