GetPositionAsync在Xamarin Android中不起作用

时间:2017-11-07 08:52:11

标签: xamarin.forms xamarin.android geolocation

这是我正在使用的代码。 此代码适用于IOS,但从未在Android上运行。 我可以在Project中看到一些类似的问题,但无法获得任何帮助。

public async Task<Position> GetCurrentLocation()
{
  Position position = null;
  try
  {
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 100;

    position = await locator.GetLastKnownLocationAsync();

    if (position != null)
    {
      //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(20), null, true);

  }
  catch (Exception ex)
  {
    //Display error as we have timed out or can't get location.
  }

  if(position == null)
    return;

  var output = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}",
      position.Timestamp, position.Latitude, position.Longitude,
      position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);

  Debug.WriteLine(output);
}

我总是得到任务取消例外。

System.Threading.Tasks.TaskCanceledException: A task was canceled.
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at Plugin.Geolocator.GeolocatorImplementation+<GetPositionAsync>d__33.MoveNext () [0x0042a] in C:\projects\geolocatorplugin\src\Geolocator.Plugin.Android\GeolocatorImplementation.cs:206 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0 
  at MtwPublicApp.Services.LocationService+<GetCurrentLocation>d__2.MoveNext () 

请帮我解决 谢谢!

0 个答案:

没有答案