1

重複の可能性:
AndroidでBluetoothをプログラムで有効/無効にする方法

私はAndroid開発の初心者です。アプリでBluetoothを無効にできません。ここではチェックボックスを使用しました。これを有効にするとBluetoothが有効になりますが、無効にすると有効のままになります。どうすればよいですか。

私のコード:

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"/>
4

3 に答える 3

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();
     }
于 2012-04-24T07:22:40.170 に答える
1

あなたの他の人が置き忘れられているようです。そのはず

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

それが役に立てば幸い。

于 2012-04-24T07:21:54.270 に答える
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(); 
        }
        }
    }
});
于 2012-04-24T07:22:37.247 に答える