如何使用Xamarin MVVM在android中点击按钮获得当前位置
本文关键字:按钮 位置 Xamarin 何使用 MVVM android | 更新日期: 2023-09-27 18:29:37
如何使用Xamarin MVVM在android中获取按钮点击的当前位置?
我正在尝试使用GPS坐标进行后台处理,当用户点击按钮时,我需要获得当前设备的位置,我不想在我的UI上的任何地方显示这个位置,尝试了一些东西,但都不起作用,有人能帮我解决问题吗?
您可以通过多种方式获取位置。这个问题的按钮单击方面只是遵循您设置的MVVM中相应命令模式的事件处理程序。
MVVMLight(一个支持Xamarin的流行MVVM库)中的命令示例:
https://msdn.microsoft.com/en-us/magazine/dn237302.aspx
让我们来看看你可以获得GPS坐标的方法:
1) 通过LocationManager
:本地
http://developer.android.com/guide/topics/location/strategies.html
http://developer.android.com/reference/android/location/LocationManager.html
2) 在已经提供此功能的Xamarin库中(内部使用LocationManager
:
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Geolocator
您需要启动位置侦听器并等待一段时间。则将触发位置更改。然后只有我们才能捕捉到用户的当前位置。
我更喜欢显示进度对话框并启动线程来侦听位置更改。不要使用任何xamarin第三方插件。使用本地位置管理器
集成以下代码。
[Activity(Label = "Location Activity", MainLauncher = false, Icon = "@drawable/icon")]
public class GetLoationActivity : BaseActivity, Android.Locations.ILocationListener
{
Location userLocation;
Button getLocationButton = FindViewById<Button>(Resource.Id.getLocationButton);
getLocationButton.LongClick += (e, d) =>
{
//TODO:Show Progress Dialog
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
var LocationChangedCalled = false;
var PublishAwayFenceThread = new Thread(new ThreadStart(delegate
{
StartLocationChangeListener(this);
}
}));
PublishAwayFenceThread.Start();
};
}
public void StartLocationChangeListener(Activity activity)
{
try
{
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.Coarse;
locationCriteria.PowerRequirement = Power.Medium;
string locationProvider = Helper.Instance._LocationManager.GetBestProvider(locationCriteria, true);
if (!String.IsNullOrEmpty(locationProvider))
if (activity!= null)
{
activity.RunOnUiThread(() =>
{
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
_LocationManager.RequestLocationUpdates(locationProvider, 1000, 1, this);
Console.WriteLine("****---------*****Location Listener Started****---------*****");
});
}
}
catch (Exception e)
{
}
}
public void OnLocationChanged(Location location)
{
try
{
userLocation = location;
//TODO:Hide Loader
StopLocationChangeListener();
Console.WriteLine("****---------*****Location changed fired****---------*****");
Console.WriteLine("****---------*****" + location.Latitude + "," + location.Longitude + "****---------*****");
}
catch (Exception e)
{
}
}
public void StopLocationChangeListener()
{
try
{
Activity _LocationContextAcitivity = (Activity)Helper.Instance.LocationContext;
_LocationContextAcitivity.RunOnUiThread(() =>
{
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
_LocationManager.RemoveUpdates(this);
Console.WriteLine("****---------*****Location Listener stopped****---------*****");
});
}
catch (Exception e)
{
}
}