我试图在Android中获取当前GPS位置,而没有使用Xamarin MVVM在后台进程的UI上显示,并且无论何时进行方法调用都无法获取它,我知道事件处理程序会导致此问题,是否有任何解决方法我单击它就立即将其选中吗?
代码-可移植项目中的App.cs
:
public string GetLocation(){
loc = DependencyService.Get<IMyLocation>();
loc.locationObtained += (object sender,
ILocationEventArgs e) => {
var lat = e.lat;
var lng = e.lng;
latitude = lat.ToString();
longitude = lng.ToString();
};
loc.ObtainMyLocation();
return latitude+":"+longitude;
}
这是我的界面代码:
public interface IMyLocation
{
void ObtainMyLocation();
event EventHandler<ILocationEventArgs> locationObtained;
}
public interface ILocationEventArgs
{
double lat { get; set; }
double lng { get; set; }
}
最后是Droid Project上的依赖服务插件:
[assembly: Xamarin.Forms.Dependency(typeof(GetMyLocation))]
namespace Tutorial.Droid
{
public class LocationEventArgs : EventArgs, ILocationEventArgs
{
public double lat { get; set; }
public double lng { get; set; }
}
public class GetMyLocation : Java.Lang.Object,
IMyLocation,
ILocationListener
{
LocationManager lm;
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider,
Availability status, Android.OS.Bundle extras)
{ }
//---fired whenever there is a change in location---
public void OnLocationChanged(Location location)
{
if (location != null)
{
LocationEventArgs args = new LocationEventArgs();
args.lat = location.Latitude;
args.lng = location.Longitude;
locationObtained(this, args);
};
}
//---an EventHandler delegate that is called when a location
// is obtained---
public event EventHandler<ILocationEventArgs>
locationObtained;
//---custom event accessor that is invoked when client
// subscribes to the event---
event EventHandler<ILocationEventArgs>
IMyLocation.locationObtained
{
add
{
locationObtained += value;
}
remove
{
locationObtained -= value;
}
}
//---method to call to start getting location---
public void ObtainMyLocation()
{
lm = (LocationManager)
Forms.Context.GetSystemService(
Context.LocationService);
lm.RequestLocationUpdates(
LocationManager.NetworkProvider,
0, //---time in ms---
0, //---distance in metres---
this);
}
//---stop the location update when the object is set to
// null---
~GetMyLocation()
{
lm.RemoveUpdates(this);
}
}
}
最佳答案
希望这个项目可以解释您的需求https://github.com/raechten/TestGPS ...我不是它的作者,只是在冲浪时发现的
关于c# - 使用MVVM在Xamarin中的Android GPS定位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34669162/