【问题标题】:Xamarin - ask again for device locationXamarin - 再次询问设备位置
【发布时间】:2019-04-03 09:57:08
【问题描述】:

我正在使用 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
}

【问题讨论】:

    标签: xamarin location xamarin.essentials


    【解决方案1】:

    这个issue是去年开业的,这是James Montemagno的回复:

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

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

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

    所以,您可以在询问之前使用Permissions Plugin for 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
        }
    }
    

    请参阅Docs 了解如何设置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2023-03-14
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多