如何在我的代码中禁用蓝牙?

时间:2012-12-20 08:01:12

标签: android bluetooth

我用两个活动做了一个应用程序。第一个活动导入用户参数,第二个活动通过蓝牙发送数据。我使用.ACTION_REQUEST_ENABLE启用蓝牙,如果它被禁用但是当bt关闭时我的apk退出。它不起作用。有什么帮助吗?

我用这个;关于创建活动的代码以及启动处理程序和runnnable之后的代码......我只测试它并找到工作...

 void findBT()
 {
  mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if(mBluetoothAdapter == null)
  {
      myLabel.setText("No bluetooth adapter available");
  }

  if(!mBluetoothAdapter.isEnabled())
  {
      //My problem is there
      Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enableBluetooth, 0);
  }

  Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  if(pairedDevices.size() > 0)
  {
      for(BluetoothDevice device : pairedDevices)
      {
          if(device.getName().equals(strValue2))
          {
              mmDevice = device;
              break;
          }
      }
  }
  myLabel.setText("Bluetooth Device Found");
  }

2 个答案:

答案 0 :(得分:4)

这是代码:

 public class AndroidBluetooth extends Activity {

    private static final int REQUEST_ENABLE_BT = 1;

    /** Called when the activity is first created. */

    TextView stateBluetooth;
    BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();
    }

    private void CheckBlueToothState(){
        if (bluetoothAdapter == null){
            stateBluetooth.setText("Bluetooth NOT support");
        }else{
            if (bluetoothAdapter.isEnabled()){
                if(bluetoothAdapter.isDiscovering()){
                    stateBluetooth.setText("Bluetooth is currently in device discovery process.");
                }else{
                    stateBluetooth.setText("Bluetooth is Enabled.");
                }
            }else{
                stateBluetooth.setText("Bluetooth is NOT Enabled!");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if(requestCode == REQUEST_ENABLE_BT){
            CheckBlueToothState();
        }

    }


}

答案 1 :(得分:2)

检查设备的代码是否启用蓝牙:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this.getParent(), ConfigClass.BLUETOOTH_NOT_SUPPORTED_ERROR, Toast.LENGTH_LONG);
}

检查并启用蓝牙:

else if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, RESULT_OK);