【问题标题】:How to fetch current location of device when App is launched first time in windows 8.1 using c#?使用 c# 在 Windows 8.1 中首次启动 App 时如何获取设备的当前位置?
【发布时间】:2015-07-08 05:38:19
【问题描述】:

我想在应用首次启动时获取当前位置。所以我在 App.xaml.cs 文件中添加了以下代码,但我面临的问题是获取位置需要花费大量时间。我认为发生这种情况是因为我没有允许或阻止位置跟踪的对话框。

var location=new Windows.Devices.Geolocation.Geolocator();
Geoposition pos=await location.GetGeopositionAsync();
GetLocation.Lat = pos.Coordinate.Point.Position.Latitude.ToString(); 
GetLocation.Long = pos.Coordinate.Point.Position.Longitude.ToString();

我在 App.xaml.cs 页面的 OnLaunched 事件中添加了上述代码,GetLocation 是我存储当前位置的类。

谁能提出可能是什么问题?

【问题讨论】:

  • 有人可以提供帮助或建议其他方法吗?

标签: c# location windows-8.1


【解决方案1】:

如果第一次是指每次打开应用程序(对于单个位置会话),我尝试了一个解决方案并为我工作。使用 Windows.Devices.Geolocation,我的代码如下:

public async void MyLocationFinder()
    {
        Geolocator MyGeolocator = new Geolocator();
        MyGeolocator.DesiredAccuracyInMeters = 50;
        try
        {
            Geoposition MyGeoposition = await MyGeolocator.GetGeopositionAsync(
               maximumAge: TimeSpan.FromMinutes(5),
               timeout: TimeSpan.FromSeconds(10) );
            LatitudeTextBlock.Text = MyGeoposition.Coordinate.Latitude.ToString("0.00");
            LongitudeTextBlock.Text = MyGeoposition.Coordinate.Longitude.ToString("0.00");
        }
        catch (UnauthorizedAccessException)
        {
            //The app doesn't has the right capability or the location master switch is off
            StatusTextBlock.Text = "Location is Disabled in phone storage.";
        }
    }

您可以在 app.xaml.cs 的 OnLaunched 函数中调用 MyLocationFinder() 方法,如果这样做,您必须从代码中删除 Textblock 部分,并且可以将其替换为全局声明的任何变量以存储它以另一种方法进入类。

【讨论】:

  • 您是否尝试过启动事件,因为我的代码也适用于应用程序,但不适用于启动方法的应用程序。
  • @KinjanBhavsar 是的,我确实在 OnLaunched 方法上进行了尝试,它工作得很好。是的,启动应用程序确实需要几秒钟,但效果很好(我刚刚删除了带有消息框的 statusTextBlock.Text)。我还尝试了另一种方法,方法是在 MainPage.xaml.cs 的 OnNavigated to 方法中使用相同的方法,这也有效。请在这两种方法中尝试上述解决方案,并让我知道它是否显示任何错误或它是否不起作用或是否有效,请勾选我的答案为正确以供将来参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多