Android 6.0以后,对于需要动态申请的权限,一般步骤如下:
1.在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://www.toymoban.com/news/detail-612491.html
关于定位权限介绍,参考定位权限文章来源地址https://www.toymoban.com/news/detail-612491.html
到了这里,关于关于ACCESS_BACKGROUND_LOCATION权限申请,导致不弹权限对话框的问题记录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!