【问题标题】:How to disable the Bluetooth in android? [duplicate]如何在android中禁用蓝牙? [复制]
【发布时间】:2012-04-24 07:15:06
【问题描述】:

可能重复:
How to enable/disable bluetooth programmatically in 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 Manifest 文件权限:

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

【问题讨论】:

标签: android checkbox bluetooth


【解决方案1】:

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

【讨论】:

  • 非常感谢 Dev.. 你解决了我的问题.. :
  • @DeepthiG : 哦不客气..
【解决方案2】:

看起来你的 else 放错地方了。应该是

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

希望对你有帮助。

【讨论】:

    【解决方案3】:

    使用下面的代码 -

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

    【讨论】:

      猜你喜欢
      • 2013-05-21
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 2016-07-05
      • 1970-01-01
      相关资源
      最近更新 更多