Xamarin.Forms DependencyService难度越来越位置 [英] Xamarin.Forms DependencyService difficulty getting location
问题描述
于是后,终于让我的头周围Xamarin.Forms DependencyService我还差点就返回设备的当前位置。
So after finally getting my head around Xamarin.Forms DependencyService I have nearly got it returning the device's current location.
我的界面
public interface ICurrentLocation
{
MyLocation SetCurrentLocation();
}
MyLocation
MyLocation
public class MyLocation
{
public double Latitude {get; set;}
public double Longitude{get; set;}
}
调用它的行
MyLocation location = DependencyService.Get<ICurrentLocation>().SetCurrentLocation();
和在实现Geolocation类Xamarin.Mobile的Android项目的CurrentLocation类
and in the CurrentLocation class in the Android project that implements the Geolocation class of Xamarin.Mobile
[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());
}
}
}
我的问题似乎是在返回位置位置持有的经度和纬度之前
my problem seems to be that is returning location before position holds the longitude and latitude
我希望我的错误已经昭然若揭了。
I am hoping my mistake is glaringly obvious
编辑:code的作品,如果我运行它作为一个正常的Android活动
the code works if I run it as a normal Android Activity
推荐答案
我会做一个轻微的修改,因为最好的做法是要么做异步或无。当您尝试从异步方法从非异步方法返回的结果,你可以遇到了问题,死锁。此外,由于在调用为getPosition方法时不使用计谋
关键字,你取回一个任务,但不检查时,操作完成。我建议稍微修改您的code这样。
I would do a slight modification since best practice is to either do all async or none. When you try to return the result from an async method from a non async method you can run into problems with deadlocks. Also, since you aren't using the await
keyword when calling the GetPosition method, you are getting back a Task, but aren't checking when the operation is complete. I suggest slightly modifying your code as such.
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());
}
}
这篇关于Xamarin.Forms DependencyService难度越来越位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!