1

我正在使用 Xamarin.Essentials。当我尝试获取最后一个已知位置时,会显示有关设备位置权限的消息。如果我拒绝许可,PermissionException就会被抓住。

如何检查位置并再次触发位置许可消息?

try
{
    var location = await Geolocation.GetLastKnownLocationAsync();
    if (location != null)
    {
        await this.Navigation.PushModalAsync(Nav_to_MAP);
    }
}
catch (PermissionException pEx)
{
    // if deny location
}
4

1 回答 1

2

这个问题是去年开放的,这是 James Montemagno 的回应:

现在它将根据系统处理它的方式为您请求权限。在 iOS 上只能请求一次权限,而在 Android 上可以多次请求。如果用户拒绝,您将获得权限被拒绝异常。

您今天可以使用权限插件来处理检查和请求 https://github.com/jamesmontemagno/PermissionsPlugin

我将打开一个新的权限提案,因为它们有点棘手。

因此,您可以在询问之前使用Xamarin 的权限插件来检查权限。像这样:

var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
    {
        await DisplayAlert("Need location", "Gunna need that location", "OK");
    }

    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
    //Best practice to always check that the key exists
    if (results.ContainsKey(Permission.Location))
        status = results[Permission.Location];
}

if (status == PermissionStatus.Granted)
{
    try
    {
        var location = await Geolocation.GetLastKnownLocationAsync();
        if (location != null)
        {
            await Navigation.PushModalAsync(Nav_to_MAP);
        }
    }
    catch (PermissionException pEx)
    {
        // if deny location
    }
}

请参阅有关如何设置的文档

于 2019-04-03T11:46:08.133 回答