Tenrampi
Tenrampi

Reputation: 15

Detect Enable/Disable Bluetooth

I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

            switch (state){
                case BluetoothAdapter.STATE_OFF:

                    break;
                case BluetoothAdapter.STATE_ON:
                    break;
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null){
        //Device does not support bluetooth
    }
    else{
        bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
                if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
                    mBluetoothAdapter.disable();
                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
            }
        });
    }
}

}

The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change. I have implemented a broadcast receiver but i can't access the switch from it. I tried:

bluetoothSwich.setChecked(true) 

inside the broadcast receiver but it doesn't work.

Ty

EDIT : I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?

Upvotes: 1

Views: 3010

Answers (1)

SpiritCrusher
SpiritCrusher

Reputation: 21043

To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.

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

Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)

private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
                // Bluetooth is disconnected, do handling here 
            }
        }
    }

};

Runtime register:

LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

Runtime unregister : Don't forget to unregister the broadcast.

LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);

Static Register:

<receiver
    android:name=".FullyQualifiedBroadcastReceiverClassName"
    android:enabled="true">
<intent-filter>
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>

Upvotes: 3

Related Questions