Android 6.0以后,对于需要动态申请的权限,一般步骤如下:
在Manifest中添加相应权限;
2.使用ActivityCompat或者ContextCompat的checkSelfPermission的方法,检查有没有权限;
3.如果没有权限,则使用ActivityCompat的requestPermissions方法申请相应权限。
4.重写onRequestPermissionsResult方法,监听权限授权结果
对于定位权限,一般需要申请ACCESS_COARSE_LOCATION权限或者ACCESS_FINE_LOCATION权限,当targetSdkVersion >= 29时,还需要申请ACCESS_BACKGROUND_LOCATION权限。
例如:
private fun checkPermissions() { val mutableListOf = mutableListOf<String>() for (permission: String in permissions) { if (ActivityCompat.checkSelfPermission( this, permission ) != PackageManager.PERMISSION_GRANTED ) { mutableListOf.add(permission) Log.d("PermissionTag", "has no $permission permission") } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (ACCESS_BACKGROUND_LOCATION.isNotEmpty() && ActivityCompat.checkSelfPermission( this, ACCESS_BACKGROUND_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { mutableListOf.add(ACCESS_BACKGROUND_LOCATION) Log.d("PermissionTag", "has no background location permission") } } if (mutableListOf.isNotEmpty()) { val permissions = mutableListOf.toTypedArray() ActivityCompat.requestPermissions(this, permissions, 0x01) } }
其中,permissions和ACCESS_BACKGOUND_LOCATION为定义的权限常量
val permissions = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)val ACCESS_BACKGROUND_LOCATION = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) Manifest.permission.ACCESS_BACKGROUND_LOCATION else ""
但是,当app的targetSdkVersion>=30,如果要申请ACCESS_BACKGOUND_LOCATION权限,则需要先申请ACCESS_COARSE_LOCATION权限或者ACCESS_FINE_LOCATION权限以后,才能申请ACCESS_BACKGROUND_LOCATION权限。如果ACCESS_BACKGROUND_LOCATION权限跟ACCESS_COARSE_LOCATION权限或者ACCESS_FINE_LOCATION权限一起申请,则不会弹出权限申请对话框,如果还有其他权限一起申请,则会导致所有权限申请都不会弹窗。
解决方法:
方法1.targetSdkVersion<=2;
方法2.先申请通过ACCESS_COARSE_LOCATION权限或者ACCESS_FINE_LOCATION权限,申请通过以后,再申请ACCESS_BACKGROUND_LOCATION权限
关于定位权限介绍,参考定位权限
来源地址:https://blog.csdn.net/fengyulinde/article/details/129556403