如何在安卓应用程序的权限中启用相机权限?

4

我正在Xamarin平台上开发Android应用程序。我已经在应用程序清单中启用了相机功能。在运行该应用程序后,用户从应用程序权限屏幕禁用相机。那么,我该如何获取用户已经从应用程序权限中禁用了该功能?

我尝试使用以下代码获取它,但每次只得到“Granted”结果。如果用户禁用了权限,则应在结果中获得“Denied”。

 var val = PackageManager.CheckPermission (Android.Manifest.Permission.Camera, PackageName);

enter image description here

2个回答

5

请求所需权限

如果您的应用程序没有所需的权限,该应用程序必须调用其中一个requestPermissions()方法来请求适当的权限。您的应用程序传递它想要的权限,以及您指定的整数请求代码,以标识此权限请求。此方法是异步的:它立即返回,并在用户响应对话框后,系统调用应用程序的回调方法,将相同的请求代码传递给requestPermissions()

int MY_PERMISSIONS_REQUEST_Camera=101;
// Here, thisActivity is the current activity
if (ContextCompat.CheckSelfPermission(thisActivity,
                Manifest.Permission.Camera)
        != Permission.Granted) {

    // Should we show an explanation?
    if (ActivityCompat.ShouldShowRequestPermissionRationale(thisActivity,
            Manifest.Permission.Camera)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.RequestPermissions(thisActivity,
                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.
    }
}

处理权限请求响应

当您的应用程序请求权限时,系统会向用户显示一个对话框。用户做出响应后,系统会调用您的应用程序的OnRequestPermissionsResult()方法,并将用户响应传递给它。您的应用程序必须覆盖该方法以查找是否已授予权限。回调传递与您传递给requestPermissions()相同的请求代码。例如,如果应用程序请求相机访问权限,则可能具有以下回调方法:

public override void OnRequestPermissionsResult(int requestCode, 
          string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_Camera: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.Length > 0 && grantResults[0] == Permission.Granted) {

                // permission was granted, yay! Do the
                // camera-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

以上示例基于Google原始权限文档


0

谢谢回复。我已经安装了它。你有什么想法,我应该使用什么代码来获取权限结果吗? - anand
谢谢回复,Giorgi。但是Permission.Camera不可用。在Permission下只有两个值Granted和Denied可用。我尝试使用Manifest.Permission.Camera,但它会抛出错误,说这不是应该传递给此方法的正确值。 - anand
我已经完成了编码部分,但是在每种情况下我仍然得到“Granted”值。如果我从应用程序权限屏幕禁用相机权限,那么结果仍然是Granted。你有任何想法我可能做错了什么吗? - anand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接