简体   繁体   中英

Bluetooth ToggleButton not checking state

I am developing an app that is going to use a ToggleButton to enable and disable BlueTooth. I manage to make the ToggelButton turn on and off BlueTooth, but I can not make it check if BlueTooth is turned on and off. The problem is that if you turn BlueTooth on or off from another location, you may turn off BlueTooth when you actually want to turn it on. Here is my code so far:

public void onClick(View v) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 
    if(adapter != null) {
        if(adapter.getState() == BluetoothAdapter.STATE_ON) {
            adapter.disable();
        } else if (adapter.getState() == BluetoothAdapter.STATE_OFF){
            adapter.enable();
        } else {
            //State.INTERMEDIATE_STATE;
        } 
    }

}

How can I make it be checked when BlueTooth is on and unchecked when BlueTooth is off?

You will have to register a broadcast receiver with the following intent filter: " android.bluetooth.intent.action.BLUETOOTH_STATE_CHANGED ".

Whenever you receive this broadcast you should recheck for actual bluetooth state.

Check out Google's PowerWidget implementation .

The receiver with appropriate intent-filters is registered in the manifest .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM