gpt4 book ai didi

c# - 如何使用 Xamarin 在 Android 中同步获取 GPS 位置更新?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:29 24 4
gpt4 key购买 nike

具体来说,我正在使用 Xamarin.Forms 进行 C# 开发,但是在 native Android 端编写一个 GPS 包装器类,该类将通过依赖项注入(inject)在 Xamarin.Forms 端使用。在大多数情况下,对于 Android,C# 和 Java 之间的调用应该是相同的。

基本上,我在 Android 端的 Geolocator 对象(它实现了 ILocationListener)中有这个方法:

public async Task<Tuple<bool, string, GPSData>> GetGPSData() {
gpsData = null;
var success = false;
var error = string.Empty;

if (!manager.IsProviderEnabled(LocationManager.GpsProvider)) {
//request permission or location services enabling
//set error
} else {
manager.RequestSingleUpdate(LocationManager.GpsProvider, this, null);
success = true;
}

return new Tuple<bool, string, GPSData>(success, error, gpsData);
}

 public void OnLocationChanged(Location location) {
gpsData = new GPSData(location.Latitude, location.Longitude);
}

我希望能够调用 GetGPSData 并让它返回元组,目前元组唯一重要的事情是填充 gpsData。我知道找到修复可能需要几秒钟,所以我想要这个方法一旦我真正需要该值,就可以在 Xamarin.Forms 端异步并等待。

我的问题是我想不出让 manager.RequestSingleUpdate 同步工作的方法,或任何变通方法。您调用该方法,然后最终触发 OnLocationChanged。我试着扔进一个恶心的、野蛮的

 while (gpsData == null);

在调用强制它不继续直到 OnLocationChanged 被触发之后,但是当我输入该行时,OnLocationChanged 永远不会被调用。我假设这是因为 OnLocationChanged 是在同一个线程上调用的,而不是后台线程。

我有什么办法可以应对这种情况,让 GetGPSData 在 OnLocationChanged 触发之前不返回吗?

谢谢

编辑:补充一下,这个方法不会被定期调用。它是自发的且很少见,所以我不想使用 RequestLocationUpdates,获取定期更新并返回最新的更新,因为这需要始终打开 GPS,同时会不必要地使电池下雨。

最佳答案

您可以使用 TaskCompletionSource 做您想做的事。我遇到了同样的问题,这就是我解决它的方法:

TaskCompletionSource<Tuple<bool, string, GPSData> tcs;
// No need for the method to be async, as nothing is await-ed inside it.
public Task<Tuple<bool, string, GPSData>> GetGPSData() {
tcs = new TaskCompletionSource<Tuple<bool, string, GPSData>>();
gpsData = null;
var success = false;
var error = string.Empty;

if (!manager.IsProviderEnabled(LocationManager.GpsProvider)) {
//request permission or location services enabling
//set error
tcs.TrySetException(new Exception("some error")); // This will throw on the await-ing caller of this method.
} else {
manager.RequestSingleUpdate(LocationManager.GpsProvider, this, null);
success = true;
}

//return new Tuple<bool, string, GPSData>(success, error, gpsData); <-- change this to:
return this.tcs.Task;
}

和:

public void OnLocationChanged(Location location) {
gpsData = new GPSData(location.Latitude, location.Longitude);
// Here you set the result of TaskCompletionSource. Your other method completes the task and returns the result to its caller.
tcs.TrySetResult(new Tuple<bool, string, GPSData>(false, "someString", gpsData));
}

关于c# - 如何使用 Xamarin 在 Android 中同步获取 GPS 位置更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com