2012-04-24 303 views
1

可能重复:
How to enable/disable bluetooth programmatically in android如何在android中禁用蓝牙?

我在Android开发一个新手。我无法在我的应用中禁用蓝牙。这里我使用了一个复选框。启用它可以启用蓝牙,但禁用它时仍然可以启用。我该怎么办?

我的代码:

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清单文件权限:

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

[可能重复(http://stackoverflow.com/q/3806536/940096) – Praveenkumar 2012-04-24 07:19:47

回答

3

else if代码是没有用的。 试试这个。

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(); 
    } 
+0

非常感谢开发..你已经解决了我的问题..: – 2012-04-24 07:28:52

+0

@DeepthiG:哦,你不客气。 。 – Bhavin 2012-04-24 08:21:22

1

看起来你别的是错误的。它应该是

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

希望它有帮助。下面的代码

0

使用 -

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