1. 在app中调用`Context.requestPermissions()`方法,传入蓝牙相关的权限名称。 2. 在弹出的权限请求对话框中,选择允许app访问蓝牙。 3. 在app的Manifest文件中,添加蓝牙相关的权限声明,如`安卓.permission.BLUETOOTH`。
完成以上步骤后,app就可以使用蓝牙功能进行设备间的通信了。需要留意的是,蓝牙通信需要确保设备之间的距离在蓝牙的有效范围内,并且双方都已打开蓝牙权限。
在安卓应用程序中,使用蓝牙需要应用程序请求蓝牙权限。要使用蓝牙,必须在安卓Manifest.xml文件中声明对BLUETOOTH和BLUETOOTH,ADMIN的权限
```xml
```
使用这些权限在应用程序中启用蓝牙后,可以执行以下操作打开蓝牙
```java
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);
}
```
其中,默认蓝牙适配器是通过getDefaultAdapter()形式调用返回的。如果返回null,则表示该设备不支持蓝牙。
如果蓝牙未启用,则需要通过ACTION,REQUEST,ENABLE意图启用它。这将打开系统默认的蓝牙启用对话框,并提示用户是否启用蓝牙。在用户选择是或否后,将通过onActivityResult()方法回调结果。
需要留意的是在安卓 6.0以后的版本中,还需要动态请求权限才能使用蓝牙。可以借助以下代码片段请求权限
```java
// Check if app has granted Bluetooth permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION,GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.BLUETOOTH }, REQUEST,ENABLE,BT);
}
```
这将检查该应用程序是否已经授予蓝牙权限,并在未获取权限时向用户请求它。在用户解决权限请求后,将通过onRequestPermissionsResult()方法回调结果。