我有一个Android应用程序,我正在使用Xamarin mobile(MonoDroid)构建。该应用程序需要获取当前用户的gps坐标。不幸的是,我似乎无法触发PositionChanged
事件。
private Geolocator geolocator = null;
private void InitializeStuff()
{
geolocator = new Geolocator(this) { DesiredAccuracy = 1 };
if (geolocator.IsGeolocationEnabled == false)
statusTextView.Text = "Please allow this application to access your location.";
else if (geolocator.IsGeolocationAvailable == false)
statusTextView.Text = "Your location could not be determined.";
else
statusTextView.Text = "Ready.";
geolocator.PositionChanged += geolocator_PositionChanged;
myButton.Click += myButton_Click;
}
private void myButton_Click(object sender, EventArgs e)
{
statusTextView.Text = "Getting position...";
if ((geolocator != null) && (geolocator.IsListening == true))
geolocator.StartListening(minTime: 1000, minDistance: 0);
}
private void geolocator_PositionChanged(object sender, PositionEventArgs e)
{
RunOnUiThread(() =>
{
statusTextView.Text = "Lat: " + e.Position.Latitude.ToString("N6") + ", Long: " + e.Position.Longitude.ToString("N6");
});
}
我可以成功地让我的应用程序达到“获取位置......”的程度。但是,PositionChanged
事件永远不会触发。我正在Android模拟器中测试我的应用,因为我没有Android设备。我通过tenet进入模拟器测试此功能。然后,我输入以下命令:
geo fix -73.985708 40
命令窗口显示“OK”。但是,PositionChanged
事件永远不会触发。我的模拟器是Android 2.2模拟器。感谢您提供的任何见解。
答案 0 :(得分:0)
我怀疑你的if语句中的条件在myButton_Click
处理程序中是错误的:
if ((geolocator != null) && (geolocator.IsListening == true))
以上意味着如果地理定位器不为空并且正在侦听,那么您将开始侦听位置更改。如果您将其更改为:
if ((geolocator != null) && (geolocator.IsListening != true))
它应该按预期工作。
修改强> 此外,你并不需要围绕你的两个条件的那些括号,它可以写成:
if (geolocator != null && geolocator.IsListening == true)