为Android M权限对话框提供自定义文本

时间:2015-10-05 07:00:23

标签: android android-permissions android-6.0-marshmallow

是否可以为系统对话框提供自定义文本,该对话框在要求用户授予权限时显示?

2 个答案:

答案 0 :(得分:25)

不,您无法自定义对话框的文本,但您可以在请求权限之前提供说明。引自developer.android.com

  

申请权限

     

如果您的应用需要应用中列出的危险权限   显示,它必须要求用户授予权限。 Android的   提供了几种可用于请求权限的方法。调用   这些方法会带来一个标准的Android对话框,你不能这样做   定制

     

解释应用需要权限的原因

     

在某些情况下,您可能希望帮助用户了解原因   您的应用需要权限。例如,如果用户启动了   摄影应用程序,用户可能会对该应用程序感到惊讶   请求允许使用相机,但用户可能不会   了解应用程序为何需要访问用户的位置或   联系人。在您申请许可之前,您应该考虑   向用户提供解释。请记住,你不想要   用解释来压倒用户;如果你提供太多   解释,用户可能会发现应用程序令人沮丧并将其删除。

     

您可能使用的一种方法是仅在提供解释时提供解释   用户已经拒绝了该权限请求。如果用户保持   尝试使用需要权限的功能,但保留   拒绝权限请求,这可能表明用户   不明白为什么应用程序需要获得提供权限的权限   功能。在这样的情况下,它可能是一个好主意   显示解释。

     

为了帮助找到用户可能需要解释的情况,   Android提供了一种实用方法,   shouldShowRequestPermissionRationale()。如果,此方法返回true   该应用先前已请求此权限,并且用户已拒绝   请求。

答案 1 :(得分:11)

我们无法自定义请求权限对话框,但我们可以为用户提供一个自定义说明,说明我们在下面请求的是带有自定义说明的方法

   private void checkForCameraPermission() {
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle("Camera permission necessary");
            alertBuilder.setMessage("FITsociety need camera permission to read barcode.");
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(BarCodeScannerActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CAMERA);
                }
            });

            AlertDialog alert = alertBuilder.create();
            alert.show();
        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CAMERA);
            // MY_PERMISSIONS_REQUEST_CAMERA is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        setBarCodeScannerView();
    }
}

上述方法检查是否已经授予权限,如果没有,则检查此方法是否需要自定义说明

ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)

此方法的文档在此shouldShowRequestPermissionRationale()此方法仅在用户拒绝权限对话框或用户关闭应用程序设置权限时才返回true,如果用户这样做,则显示带有自定义说明的警告对话框并继续进一步希望它有效

相关问题