我是视觉工作室的新手,开发通用的Windows应用程序 . 当我单击应该在点击时显示位置信息的UI按钮时,我的程序会抛出异常 . 这是一个UWP . 从包清单打开位置访问权限 . 代码如下所示:
private async void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
var geoLocator = new Geolocator();
geoLocator.DesiredAccuracy = PositionAccuracy.High;
Geoposition positionInfo = await geoLocator.GetGeopositionAsync();
string latitude = "Latitude: " + positionInfo.Coordinate.Point.Position.Latitude.ToString();
string longitude = "Longitude: " + positionInfo.Coordinate.Point.Position.Longitude.ToString();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}
}
异常堆栈跟踪如下:
抛出异常:mscorlib.ni.dll中的'System.Exception'来自HRESULT的异常:0x80072EE7位于系统的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务),系统的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) .Luntime.CompilerServices.TaskAwaiter1.GetResult()在HelloLocation.MainPage . <getBtn_Click> d__1.MoveNext()抛出异常:mscorlib.ni.dll中的'System.Exception'来自HRESULT的异常:0x80072EE7在System.Runtime.CompilerServices.TaskAwaiter位于System.Runtime.CompilerServices.TaskAwaiter1.GetResult()的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的.ThrowForNonSuccess(任务任务),位于HelloLocation.MainPage.d__1.MoveNext()抛出异常:'System.Exception' in mscorlib.ni.dll来自HRESULT的异常:0x80072EE7,System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务),位于System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotifi HelloLocation.MainPage的System.Runtime.CompilerServices.TaskAwaiter1.GetResult()中的阳离子(任务任务) . <getBtn_Click> d__1.MoveNext()抛出异常:mscorlib.ni.dll中的'System.Exception'来自HRESULT的异常:0x80072EE7 at位于HelloLocation.MainPage.d__1.MoveNext()的System.Runtime.CompilerServices.TaskAwaiter1.GetResult()的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)程序'[3032] hellolocation.exe'已退出,代码为-1(0xffffffff) .
2 回答
您需要首先请求访问权限,然后使用此请求的结果来确定您是否可以尝试使用
GetGeopositionAsync
调用 .详情here:
它现在有效 . :)我之前一直在使用虚拟机上运行的visual studio . 我猜它没有访问位置所需的权限,即使在真实(我的PC)和虚拟机中都启用了位置 . 我在没有虚拟机的情况下直接在另一台笔记本电脑上使用了相同的代码,效果非常好!