如何打开蓝牙按钮点击蓝牙、按钮

2023-09-06 13:44:10 作者:恰好心动

在我的应用程序,我需要打开蓝牙我的设备上的按钮点击。我怎样才能做到这一点?一个例子是很有益的。另外,我需要什么权限的,包括我的 mainfest.xml 的对于相同的?

In my application, I need to turn on bluetooth of my device on a button click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my mainfest.xml for the same?

推荐答案

以下是从的蓝牙 Android的文件

Following are code excerpts from android documentation on Bluetooth

在清单文件权限:

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

来源$ C ​​$ C,使蓝牙

Source code to enable Bluetooth

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

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

如果启用蓝牙成功,你的活动将获得 RESULT_OK 结果code。在 onActivityResult()回调。如果未启用,由于一个错误的蓝牙(或用户回答否),那么结果code将 RESULT_CANCELED

If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code will be RESULT_CANCELED.