【问题标题】:Xamarin Geolocation just hangs one some phonesXamarin Geolocation 只是挂了一部手机
【发布时间】:2026-01-24 14:40:02
【问题描述】:

我有一堂课,我有一个计时器,每隔 15 秒我会尝试获取 GeoLocation。

private System.Timers.Timer _getLocationTimer { get; set; }
_getLocationTimer = new System.Timers.Timer { Interval = 15000 };

_getLocationTimer.Elapsed -= GetLocation_Handler;
_getLocationTimer.Elapsed += GetLocation_Handler;
_getLocationTimer.Start();

async void GetLocation_Handler(object sender, ElapsedEventArgs e)
    {
        Position position = null;
        try
        {
             var locator = CrossGeolocator.Current;
            locator.DesiredAccuracy = 100;

            position = await locator.GetLastKnownLocationAsync();

            if (position != null)
            {
                _position = new Position(position.Latitude, position.Longitude);
                //got a cahched position, so let's use it.
                return;
            }

            if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
            {
                //not available or enabled
                return;
            }

            position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
        }
        catch (Exception ex)
        {
            throw ex;
            return;
        }
        _position = new Position(position.Latitude, position.Longitude);
        if (position == null)
            return;
    }

我的问题出在 GetPositionAsync 方法上,因为有时只有一部手机不会返回(只是挂在该方法中)。我正在使用来自 nuget 的 Xam.Plugin.Geolocator 库。有人可以告诉我我该怎么做才能让 GetPositionAsync 每次都能正常工作吗?

【问题讨论】:

  • 您确定您拥有这些手机的权限吗?您正在使用的插件已被 Xamarin Essentials 替换
  • 我拥有所有手机的权限。我可以尝试更新到 Xamarin Essentials

标签: .net xamarin geolocation


【解决方案1】:

目前,Xamarin.Essentials 使权限请求更容易。将 Xamarin.Essentials 更新到最新版本。只需要在android的manifest文件和iOS的Info.plist文件中添加权限即可。

有关地理位置权限的更多详细信息,请查看以下链接。 https://docs.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android

Xamarin.Essentials:权限:https://docs.microsoft.com/en-us/xamarin/essentials/permissions?context=xamarin%2Fxamarin-forms&tabs=android

【讨论】: