Android Bluetooth 搜索不到附近设备的问题

前一阵子研究 Android 蓝牙的时候,在搜索设备时候怎么也搜索不到附近的蓝牙设备,也不报错,经过查阅了一下资料之后发现,在启动蓝牙搜索附近设备时会需要到 LOCATION 权限,Android M 以下则只需要在清单中添加


Android M 以上则需要自行申请权限:

private static final int ACCESS_LOCATION = 1001;

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
   int permissionCheck = 0;
   permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
   permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
         if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //注册权限
                this.requestPermissions(
                         new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION},
                                ACCESS_LOCATION); //Any number
          }else{//已获得过权限
               //进行蓝牙设备搜索操作
          }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case ACCESS_LOCATION:
            if (hasAllPermissionsGranted(grantResults)) {
                // Permission Granted
                ...
            } else {
                // Permission Denied
                ...
            }

            break;
    }
}


// 含有全部的权限
private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
    for (int grantResult : grantResults) {
        if (grantResult == PackageManager.PERMISSION_DENIED) {
            return false;
        }
    }
    return true;
}

你可能感兴趣的:(Android)