Android 11运行时权限

nle07wnf  于 2023-01-07  发布在  Android
关注(0)|答案(3)|浏览(168)

几天前,代码工作正常,没有权限问题。
我无法在运行时授予权限,从设置授予权限时也出现问题。(应用程序权限详细信息页)。

var permissions = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
        arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    } else {
        arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
    }

单击相应按钮上的请求权限。

permissionResultLauncher =
        registerForActivityResult(
                ActivityResultContracts.RequestMultiplePermissions()
        ) { permissions ->
            var allPermissionGranted = true
            permissions.entries.forEach {
                if (!it.value) {
                    Log.e(TAG, "Permission ${it.key} granted : ${it.value}")
                    allPermissionGranted = false
                }
            }
            if (!permissionDeniedDialog && !allPermissionGranted) {
                showDialog(
                        "Required",
                        "App needs Bluetooth and Location permissions to scan bluetooth devices.",
                        "Later",
                        "Allow",
                        object : DialogView.ButtonListener {
                            override fun onNegativeButtonClick(dialog: AlertDialog) {
                                dialog.dismiss()
                                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                        Uri.fromParts("package", requireActivity().applicationContext.packageName, null))
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                startActivity(intent)
                            }

                            override fun onPositiveButtonClick(dialog: AlertDialog) {
                                dialog.dismiss()
                                requestRequirdPermissions()
                            }
                        })
            } else {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.fromParts("package", requireActivity().applicationContext.packageName, null))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }
            permissionDeniedDialog = true
        }
permissionResultLauncher.launch(permissions)

检查权限的函数

private fun checkPermission(): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(requireContext(), permission) != PackageManager.PERMISSION_GRANTED) return false
        }
        return true
    }

有没有人能让我知道为什么上面的不工作?。系统直接在结果上,应用程序将应用程序重定向到设置页面,但我也无法从设置页面授予权限。
这是特定的操作系统吗?,任何人有同样的问题与coloros 11?。请指导我,如果有什么是失踪从我身边。
设备:OPPO F17 Pro操作系统:彩色操作系统11,基于Android 11

    • 注:**

以上代码,与三星设备,Android 11为基础(OneUI 3.1),应用程序不要求运行时,但在设置页面重定向后,我授予位置权限和应用程序工作正常,关于OPPO我无法从设置页面授予权限。
尝试:

var permissions = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
    arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
    arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION)
}

private fun requestRequirdPermissions() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            permissionResultLauncher.launch(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION))
        }
        else
        {
            permissionResultLauncher.launch(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION ))
        }
    }
ckocjqey

ckocjqey1#

试试这个方法可能会对你有帮助

fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            var permissions: ArrayList<String> = ArrayList<String>()
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
            val listPermissionsNeeded: ArrayList<String> = ArrayList()
            for (p in permissions) {
                var result = ContextCompat.checkSelfPermission(this, p!!)
                if (result != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(p)
                }
            }

            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(
                        this,
                        listPermissionsNeeded.toTypedArray(),
                        CODE
                )
            } else {
                next()
            }
        } else {
            next()
        }
    }

    override fun onRequestPermissionsResult(
            requestc: Int,
            permissions: Array<String>,
            grantRes: IntArray
    ) {
        super.onRequestPermissionsResult(requestc, permissions, grantRes);
        when (requestc) {
            CODE -> {
                var isGrant = true
                if (grantRes.size > 0) {
                    for (i in 0 until grantResults.size) {
                        if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                            isGrant = false
                        }
                    }
                }
                if (isGrant) {
                    next()
                } else {
                    checkRationalePermission(permissions)
                }
            }
        }
    }

    var alertDialogRatinal: android.app.AlertDialog? = null
    fun checkRationale(permissions: Array<String>) {
        if (alertDialogRatinal != null && alertDialogRatinal!!.isShowing || permissions.size == 0) {
            return
        }
        var someDenied = false
        for (permission in permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this@Activity,
            permission!!
                )
            ) {

            } else {
                if (ActivityCompat.checkSelfPermission(
                        this@Activity,
                permission
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                } else {
                    someDenied = true
                }
            }
        }
        if (someDenied) {
            val alertDialogBuilder =
                    android.app.AlertDialog.Builder(this@Activity)
            alertDialogRatinal = alertDialogBuilder.setTitle("Permissions Required")
                    .setMessage(
                            "Please open settings, go to permissions and allow them."
                    )
                    .setPositiveButton(
                            "Settings"
                    ) { dialog, which ->
                    val intent = Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts(
                            "package",
                            this@Activity.getPackageName(),
                null
                        )
                    )
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityForResult(intent, 100)
            }
                .setNegativeButton(
                    "Cancel"
            ) { dialog, which -> }
                .setCancelable(false)
                    .create()
            alertDialogRatinal!!.show()
        }
    }
bfnvny8b

bfnvny8b2#

我的问题是由系统重置修复,但根据评论和文件,请遵循以下指南的位置权限。
感谢您的评分
参考:https://stackoverflow.com/a/66321942/9909365
后台位置权限不像其他权限那样工作。它是一个将位置权限从仅前台提升到前台和后台的请求。
用户必须有意识地选择"允许所有时间",以便这样做,并授予后台位置权限。否则,该权限被视为拒绝。
您甚至不能请求后台位置,除非前台位置已被授予-当系统权限活动显示时,它应该已经选择了选项2或3。
See https://developer.android.com/training/location/permissions#request-background-location

    • 注:**

当您的应用使用此后台位置时,请准备一段简短的视频,演示您的应用中需要在后台访问位置的基于位置的功能(当应用未使用时)。
参见https://support.google.com/googleplay/android-developer/answer/9799150

92vpleto

92vpleto3#

private val requestIdMultiplePermissions = 1
private val permissionsRequest: ArrayList<String> =
    arrayListOf(READ_CALENDAR
            , CAMERA)
findViewById<Button>(R.id.multiplePermissionBtn).setOnClickListener {
            if (checkMultipleRequestPermissions()) {
                doOperation()
            }
}
private fun doOperation() {
        Toast.makeText(this, "Successfully granted", Toast.LENGTH_LONG).show()
    }
private fun checkMultipleRequestPermissions(): Boolean {
        val listPermissionsNeeded: MutableList<String> = ArrayList()

        for (p in permissionsRequest) {
            val result = ContextCompat.checkSelfPermission(this, p)
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p)
            }
        }

        if (listPermissionsNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                listPermissionsNeeded.toTypedArray(),
                requestIdMultiplePermissions
            )
            return false
        }
        return true
    }
override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == requestIdMultiplePermissions) {
            if (grantResults.isNotEmpty()) {
                var isGrant = true
                for (element in grantResults) {
                    if (element == PackageManager.PERMISSION_DENIED) {
                        isGrant = false
                    }
                }
                if (isGrant) {
                    doOperation()
                } else {
                    var someDenied = false
                    for (permission in permissions) {
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                permission
                            )
                        )  {
                            if (ActivityCompat.checkSelfPermission(
                                    this,
                                    permission
                                ) == PackageManager.PERMISSION_DENIED
                            ) {
                                someDenied = true
                            }
                        }
                    }
                    if (someDenied) {
                        settingActivityOpen()
                    }else{
                        showDialogOK { _: DialogInterface?, which: Int ->
                            when (which) {
                                DialogInterface.BUTTON_POSITIVE -> checkMultipleRequestPermissions()
                                DialogInterface.BUTTON_NEGATIVE -> { }
                            }
                        }
                    }
                }
            }
        }
}
private fun settingActivityOpen() {
        Toast.makeText(
            this,
            "Go to settings and enable permissions",
            Toast.LENGTH_LONG
        )
            .show()
        val i = Intent()
        i.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        i.addCategory(Intent.CATEGORY_DEFAULT)
        i.data = Uri.parse("package:$packageName")
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
        i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
        startActivity(i)
}
private fun showDialogOK(okListener: DialogInterface.OnClickListener) {
        MaterialAlertDialogBuilder(this)
            .setMessage("All Permission required for this app")
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", okListener)
            .create()
            .show()
}

相关问题