0

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);



    }
}
  • in broadcast receiver log action values. shee what you get. – Calvin Jun 20 '16 at 06:39
  • Possible duplicate of [Android Broadcast Receiver bluetooth events catching](http://stackoverflow.com/questions/30222409/android-broadcast-receiver-bluetooth-events-catching) – Rajen Raiyarela Jun 20 '16 at 06:45
  • @Rajen yes I have checked that questioned and followed the same. However, I'm not able to access the checkbox from within Broadcastreceiver. – Rakesh Sharma Jun 20 '16 at 06:55
  • did you try printing the log are you receiving the broadcast of state changes in first place? Did you add bluetooth permission in android manifest? – Rajen Raiyarela Jun 20 '16 at 06:57
  • Just now I put the Log print in my code and looks like the code never reaches in Broadcastreceiver. and I have put the permission in Manifest – Rakesh Sharma Jun 20 '16 at 07:08
  • Pl add action `BluetoothAdapter.ACTION_STATE_CHANGED` also to your intent filter and see it works or not. – Rajen Raiyarela Jun 20 '16 at 07:25

0 Answers0