Plugin.Geolocator退出方法(死锁?)

时间:2019-03-26 18:50:08

标签: xamarin geolocation

我正在构建Xamarin应用,对于地理位置,我正在使用GeolocatorPlugin

问题在于,一旦代码想要获得该位置,该代码就会存在而不会发出警告。

我的课程字段:

private Position position;
private IGeolocator locator = CrossGeolocator.Current;

我的页面构造函数:

public MainPage()
{
    InitializeComponent();

    locator.PositionChanged += Locator_PositionChanged;
    locator.PositionError += Locator_PositionError;
}

OnAppearing事件正在调用getLocationPermission:

    private async Task GetLocationPermission()
    {
        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationWhenInUse);
        if (status != PermissionStatus.Granted)
        {
            //Not granted, request permission
            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.LocationWhenInUse))
            {
                // This is not the actual permission request
                await DisplayAlert("Need your permission", "We need to access your location", "Ok");
            }

            // This is the actual permission request
            var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.LocationWhenInUse);
            if (results.ContainsKey(Permission.LocationWhenInUse))
                status = results[Permission.LocationWhenInUse];
        }
        //Already granted, go on
        if (status == PermissionStatus.Granted)
        {
            //Granted, get the location
            GetLocation();
            await GetVenues();
            await locator.StartListeningAsync(TimeSpan.FromMinutes(30), 500);
        }
        else
        {
            await DisplayAlert("Access to location denied", "We don't have access to your location.", "OK");
        }
    }

该权限被授予并获取GetLocation()方法:

    private async void GetLocation()
    {
        //var locator = CrossGeolocator.Current;
        try
        {
            var myPosition = await locator.GetPositionAsync();
            position = new Position(myPosition.Latitude, myPosition.Longitude);
        }
        catch (Exception ex)
        {
            throw;
        }
        if (position == null)
        {
            //Handle exception
        }
    }

使用locator.GetPositionAsync()到达该行后,它将停止。没有引发异常,也不会引发PositionError。

我不知道为什么,但是一开始它只能工作一次,此后再也没有工作。

Android Emulator中的位置设置如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

根据我的研究,您没有像this link那样实现Location Changes

我写了一个关于Location changes的演示。正在运行屏幕截图。

enter image description here

这是我的演示 https://github.com/851265601/GeolocationDemo