发表了主题帖:
AndroidBLE_osc_申请权限
这个软件的功能是通过蓝牙接收温度数据并绘制温度变化曲线
# 1.获取权限
安卓的BLE需要在AndroidManifest.xml里声明需要的权限。包括蓝牙权限,定位权限,在安卓12以后又增加了一些权限
```xml
```
# 2.动态申请
其中定位权限以及安卓12新增权限需要动态申请。因此下面需要在MainActivity里申请权限
```java
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted, start scanning
Toast.makeText(this, "已授予许可", Toast.LENGTH_SHORT).show();
} else {
// Permission denied, show a message
Log.w("permission","Location permission is required to scan for BLE devices");
Toast.makeText(this, "Location permission is required to scan for BLE devices", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
}
```
其中onResume方法绘制主界面显示之前就区申请权限,onRequestPermissionsResult方法处理相关权限申请失败/成功后内容例如向用户提示申请成功/失败。
这是onResume方法返回的权限请求码,onRequestPermissionsResult通过请求码来处理响应的权限申请结果。
```
private static final int REQUEST_ENABLE_BT = 1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
```
# 3.主函数需要判断设备是否支持BLE,蓝牙是否打开
```java
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
```