2012-04-24 71 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(); 
     } 
     } 
    } 
});