如何在xamarin.forms中一次显示多个权限?

时间:2019-05-24 20:33:13

标签: c# plugins xamarin.forms cross-platform android-permissions

我想在应用启动或启动屏幕后显示摄像机和位置的运行时权限弹出窗口。

我正在使用NuGet软件包:https://github.com/jamesmontemagno/PermissionsPlugin

我已经在按钮单击事件上尝试了以下代码。

private async void Button_Clicked(object sender, EventArgs e)
    {
        await GetPermissions();
    }


public static async Task<bool> GetPermissions()
    {
        bool permissionsGranted = true;

        var permissionsStartList = new List<Permission>()
        {
            Permission.Location,
            Permission.LocationAlways,
            Permission.LocationWhenInUse,
            Permission.Storage,
            Permission.Camera
        };

        var permissionsNeededList = new List<Permission>();
        try
        {
            foreach (var permission in permissionsStartList)
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                if (status != PermissionStatus.Granted)
                {
                    permissionsNeededList.Add(permission);
                }
            }
        }
        catch (Exception ex)
        {
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());

        try
        {
            foreach (var permission in permissionsNeededList)
            {
                var status = PermissionStatus.Unknown;
                //Best practice to always check that the key exists
                if (results.ContainsKey(permission))
                    status = results[permission];
                if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                {
                    permissionsGranted = true;
                }
                else
                {
                    permissionsGranted = false;
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return permissionsGranted;
    }

请提出您的建议或更好的方法。

1 个答案:

答案 0 :(得分:0)

  

我想显示摄像机和位置的运行时权限弹出窗口   该应用程序启动或启动屏幕之后。

如果您想在app starts or after splash screen时弹出摄像机和位置的权限。

您可以在主页的GetPermissions中调用OnAppearing()方法:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        bool a = await GetPermissions();
    }

    public static async Task<bool> GetPermissions()
    {
        ....
    }
}

注意:

  1. here所述,当您安装PermissionsPlugin时,还将在您的Android应用中安装一个名为“ MainApplication.cs”的文件。

  2. ,并通过右键单击READ_EXTERNAL_STORAGE项目-> {确保选择了WRITE_EXTERNAL_STORAGEACCESS_COARSE_LOCATIONACCESS_FINE_LOCATIONxxxx.Android权限{1}}-> Properties-> Android Mainfest

我已经上传了sample,您可以检查一下。让我知道它是否有效。