即使没有叫过Kotlin android,AlertDialogBox也会显示

时间:2019-07-17 20:50:49

标签: android kotlin android-permissions android-alertdialog

我正在制作一个android应用程序,并请求读取存储的权限。

以下是请求权限的代码:

private fun checkPermission():Boolean {
        return checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED
}

private fun toast(text: String){
    Toast.makeText(applicationContext, text, Toast.LENGTH_LONG).show()

}
private fun setupPermissions() {
    if (!checkPermission()) {
        var requestCode = 7
        requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE), requestCode)
        if (!checkPermission()) {
            toast("Permissions not granted")

            val builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("Permissions were denied.")
            builder.setMessage("You must allow MyApp access to your files to continue.\n\nNote: If you clicked \"Don't ask again,\" you'll have to enable the permission in settings")
            builder.setPositiveButton("OK") { dialog, which ->
                setupPermissions()
            }
            builder.setNeutralButton("EXIT") { _, _ ->
                Toast.makeText(applicationContext, "You cancelled the dialog.", Toast.LENGTH_SHORT).show()
            }
            val dialog: AlertDialog = builder.create()
            dialog.show()
        }
        else{
            toast("Permissions granted")
        }
    }


}

问题在于它请求了权限,但是即使它尚未被调用,您仍可以在其下看到AlertDialog框:

Screenshot of app when it launches (它说“别再问了”,因为我已经尝试了多次)

它似乎正在运行requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE), requestCode),并且没有等待用户选择允许或拒绝,它显示了对话框。

为什么会这样?感谢您的帮助,因为我是Kotlin的新手

1 个答案:

答案 0 :(得分:0)

Dialog立即出现的原因是,您在请求许可后正在检查是否创建它。

第二个if (!checkPermission())不会有所不同,因为权限更改不会立即发生。您可以尝试执行以下步骤:

  1. 删除代码,将Dialog放入setUpPermissions()
  2. 复制并粘贴以下代码:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (!checkPermission()) {
            toast("Permissions not granted")
    
            val builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("Permissions were denied.")
            builder.setMessage("You must allow MyApp access to your files to continue.\n\nNote: If you clicked \"Don't ask again,\" you'll have to enable the permission in settings")
            builder.setPositiveButton("OK") { dialog, which ->
                setupPermissions()
            }
            builder.setNeutralButton("EXIT") { _, _ ->
                Toast.makeText(applicationContext, "You cancelled the dialog.", Toast.LENGTH_SHORT).show()
            }
            val dialog: AlertDialog = builder.create()
            dialog.show()
        }
        else{
            toast("Permissions granted")
        }
    }
    

这应该是在requestPermission()结果发生之后,它应该检查权限。然后,如果未授予该权限,它将创建Dialog

让我知道这是否可行,或者由于我自己没有进行测试而遇到任何错误。