Android 打开蓝牙功能代码
时间: 2023-10-02 09:06:53 浏览: 55
以下是 Android 打开蓝牙功能的代码:
首先,在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
然后,在需要打开蓝牙功能的 Activity 中,添加以下代码:
```java
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
} else {
if (!bluetoothAdapter.isEnabled()) {
// 蓝牙未打开,请求用户打开蓝牙
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
// 蓝牙已打开
}
}
```
其中,`BluetoothAdapter` 是操作蓝牙的核心类,`getDefaultAdapter()` 方法可以获取默认的 `BluetoothAdapter` 实例。如果返回的是 `null`,说明设备不支持蓝牙。
如果蓝牙未打开,可以通过 `BluetoothAdapter.ACTION_REQUEST_ENABLE` Intent 请求用户打开蓝牙。这里通过 `startActivityForResult` 方法启动 Intent,可以在 `onActivityResult` 方法中获取用户的操作结果。
如果蓝牙已经打开,可以直接执行后续操作。