Xamarin.Forms依赖关系服务难以获取位置

wtlkbnrh  于 2022-12-07  发布在  其他
关注(0)|答案(4)|浏览(125)

因此,在我终于了解了Xamarin.Forms DependencyService之后,我几乎已经让它返回了设备的当前位置。
我的界面

public interface ICurrentLocation
{
    MyLocation SetCurrentLocation();
}

我的位置

public class MyLocation
{
    public double Latitude {get; set;}
    public double Longitude{get; set;}
}

调用它的行

MyLocation location = DependencyService.Get<ICurrentLocation>().SetCurrentLocation();

以及实现Xamarin的Geolocation类的Android项目中的CurrentLocation类。

[assembly: Dependency(typeof(CurrentLocation))]
namespace MyCockburn.Droid
{

    public class CurrentLocation : Activity, ICurrentLocation

        Geolocator locator;
        Position position = new Position();
        MyLocation location;

        public MyLocation SetCurrentLocation()
        {
            GetPosition();
            location = new MyLocation()
            {
                Latitude = position.Latitude,
                Longitude = position.Longitude
            };

            return location;
       }

       async void GetPosition()
       {
           try
           {
                 locator = new Geolocator(this) { DesiredAccuracy = 50 };
                 if (locator.IsListening != true)
                       locator.StartListening(minTime: 1000, minDistance: 0);

                 position = await locator.GetPositionAsync(timeout: 20000);

           }
           catch (Exception e)
           {
               Log.Debug("GeolocatorError", e.ToString());
           }
       }
   }

我的问题似乎是,返回位置之前的位置持有经度和纬度
我希望我的错误显而易见
编辑:如果我把它作为一个普通的Android活动运行,代码就可以工作了

rn0zuynd

rn0zuynd1#

我会做一个小小的修改,因为最好的做法是要么全部异步,要么全部不异步。当你试图从一个非异步方法返回一个异步方法的结果时,你可能会遇到死锁的问题。另外,因为你在调用GetPosition方法时没有使用await关键字,所以你得到的是一个任务,但不检查操作何时完成,我建议您稍微修改代码。

public interface ICurrentLocation {
    Task<MyLocation> GetCurrentLocation();
}

public async Task<MyLocation> GetCurrentLocation()
{
    var position = await GetPosition();
    return new MyLocation()
    {
        Latitude = position.Latitude,
        Longitude = position.Longitude
    };
}

async Task<Location> GetPosition()
{
    try
    {
          locator = new Geolocator(this) { DesiredAccuracy = 50 };
          if (locator.IsListening != true)
                locator.StartListening(minTime: 1000, minDistance: 0);

          return await locator.GetPositionAsync(timeout: 20000);

    }
    catch (Exception e)
    {
        Log.Debug("GeolocatorError", e.ToString());
    }
}
pokxtpni

pokxtpni2#

You aren't waiting for the position function to finish. Many different options and keeping it async is the best one but if you want it synchronous then try this blocking call:

void GetPosition()
   {
       try
       {
             locator = new Geolocator(this) { DesiredAccuracy = 50 };
             if (locator.IsListening != true)
                   locator.StartListening(minTime: 1000, minDistance: 0);

             position = locator.GetPositionAsync(timeout: 20000).Result;

       }
       catch (Exception e)
       {
           Log.Debug("GeolocatorError", e.ToString());
       }
   }

I also recommend taking a look at Xamarin.Forms.Labs as it already has abstracted GPS service and working sample that is functional for all 3 platforms:
https://github.com/XForms/Xamarin-Forms-Labs

cl25kdpy

cl25kdpy3#

请尝试在命名空间上方加入组件,并等候GetPosition方法。
请看这张图片:http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/Images/solution.png

w8f9ii69

w8f9ii694#

我开发了一个应用程序,在获得GPS定位(ALHAMDULILAH)的工作很好。我相信下面的代码将是很大的帮助。
然后,您可以根据自己的喜好编辑SubmitGPSLocation函数。
我希望这对你有帮助...

public async Task Run(CancellationToken token)
    {
        await Task.Run(async () =>
        {
            if (GPSService.Instance.IsListening)
            {
                GPSService.Instance.StopListening();
            }

            GPSService.Instance.StartListening(2500, 50, true); 
            GPSService.Instance.PositionChanged += Instance_PositionChanged;

            System.Diagnostics.Debug.WriteLine(getRunningStateLocationService());

            while (getRunningStateLocationService())
            {
                token.ThrowIfCancellationRequested();                   
                await Task.Delay(500).ConfigureAwait(true);
            }

            GPSService.Instance.StopListening();
          
            //await CrossGeolocator.Current.StopListeningAsync().ConfigureAwait(true);
            GPSService.Instance.PositionChanged -= Instance_PositionChanged;

            return;
        }, token).ConfigureAwait(false);
    }

    private void Instance_PositionChanged(object sender, PositionEventArgs e)
    {
        try
        {
            isEvenCount = !isEvenCount;

            if (e.Position != null)
            { 
                var message = new LocationMessage
                {
                    Latitude = e.Position.Latitude,
                    Longitude = e.Position.Longitude,
                    Accuracy = e.Position.Accuracy,
                    Speed = e.Position.Speed,
                    Heading = e.Position.Heading,
                    TimeStamp = e.Position.Timestamp.DateTime
                };

                SubmitGPSLocation(e).ConfigureAwait(false);
            }
            else
            {
                CrossToastPopUp.Current.ShowToastMessage("Failed to get GPS location");
             }
        }
        catch (Exception ex)
        {
            CrossToastPopUp.Current.ShowToastMessage(ex.Message);
        }
    }

    private static async Task SubmitGPSLocation(PositionEventArgs e)
    {
        if (!NetworkCheck.IsInternet())
        {
            return;
        }

        if (!int.TryParse(App.PhoneID, out var number))
        {
            return;
        }

        try
        {
            var thetrackers = Convert.ToString(Application.Current.Properties["AuthorizedTrackers"]);

            GeneralUserPhoneLocation MyGeneralUserPhoneLocation = new GeneralUserPhoneLocation();
            MyGeneralUserPhoneLocation.PhoneID = int.Parse(App.PhoneID);
            MyGeneralUserPhoneLocation.Latitude = e.Position.Latitude.ToString("n6");
            MyGeneralUserPhoneLocation.Longitude = e.Position.Longitude.ToString("n6");

            MyGeneralUserPhoneLocation.Accuracy = e.Position.Accuracy;
            MyGeneralUserPhoneLocation.Heading = e.Position.Heading;
            MyGeneralUserPhoneLocation.Speed = e.Position.Speed;
            MyGeneralUserPhoneLocation.TimeStamp = e.Position.Timestamp.DateTime;

            MyGeneralUserPhoneLocation.RequestType = "N";
            MyGeneralUserPhoneLocation.Comment = thetrackers;

            string servicestring = JsonConvert.SerializeObject(MyGeneralUserPhoneLocation);
            HttpContent theusercontent = new StringContent(servicestring, Encoding.UTF8, "application/json");

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://mygpswebapi.com");
                var response = await client.PostAsync("Home/SaveGeneralUserPhoneLocationAPP/", theusercontent).ConfigureAwait(true);

                if (response.IsSuccessStatusCode)
                {
                   
                }
                else
                {
                }
            }
        }
        catch (Exception ex)
        {
            CrossToastPopUp.Current.ShowToastMessage(ex.Message);
        }
    }

相关问题