1

Possible Duplicate:
How to enable/disable bluetooth programmatically in android

I'm a newbie in android development. I'm not able to disable Bluetooth in my app. Here I've used a checkbox.Enabling of which enables the bluetooth but while disabling it remains enable.. What do I do?

My code:

enable_chkbox=(CheckBox)findViewById(R.id.chkboxenable);
enable_chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        if(buttonView.isChecked())
        {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
            else if(!buttonView.isChecked())//updated
            {
                mBluetoothAdapter.disable();
            //finish();
            }
        }
    }
});

Android Manifest file permissions:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Community
  • 1
  • 1
Deepthi G
  • 79
  • 2
  • 10

3 Answers3

3

Your else if code is of no use. Try this.

  BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
  if(buttonView.isChecked())
    {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
    else 
    {
            mBluetoothAdapter.disable();
           //finish();
     }
Bhavin
  • 6,020
  • 4
  • 24
  • 26
1

Looks like your else is misplaced. It should be

if (buttonView.isChecked()) {
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } 
}
else {
    mBluetoothAdapter.disable();
    // finish();
}

Hope it helps.

krishnakumarp
  • 8,967
  • 3
  • 49
  • 55
0

Use below code -

enable_chkbox=(CheckBox)findViewById(R.id.chkboxenable);
enable_chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub
    if(buttonView.isChecked())
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
        if (!mBluetoothAdapter.isEnabled()) 
        {
            // do something
        }else
        { 
            mBluetoothAdapter.disable(); 
        }
        }
    }
});
Praveenkumar
  • 24,084
  • 23
  • 95
  • 173