I have a checkbox in my activity. I want this checkbox checked when the bluetooth is turned on and unchecked when it is turned off. I know that periodically checking the Bluetooth state is an inefficient way. So I need to use a BroadcastReciever. I tried doing this using the following code in my activity. But it doesn't work. I'm not sure if I used the BroadcastReciever properly.[new to this] here is my code.
package com.example.sample;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Toast;
public class BluetoothActivity extends AppCompatActivity {
public CheckBox btcheck;
private final BroadcastReceiver mReceiver = 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){
btcheck.setChecked(false);
}
else{
btcheck.setChecked(true);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
btcheck=(CheckBox)findViewById(R.id.btcheck);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
registerReceiver(mReceiver,filter);
}
}