Unable to get the location updates in monodroid

天涯浪子 提交于 2019-12-12 05:29:59

问题


I am trying to get the location in my Android app as follows

LocationManager lmanager = (LocationManager)context.GetSystemService(Context.LocationService);
if (lmanager.IsProviderEnabled(LocationManager.NetworkProvider))
 {
  Location currentLoc = lmanager.GetLastKnownLocation(LocationManager.NetworkProvider);
}

I tried with LocationManager.gpsProvider also instead of the Network provider.

In all the cases I am getting a null reference exception for currentLoc.


回答1:


The GetLastKnownLocation() method returns the last location it knew about, which could be null if it has never received any updates before. I think what you want to do here is listen for location updates, and then respond to them once they come in. You can do this by implementing the ILocationListener interface:

class MyLocationListener : Java.Lang.Object, ILocationListener
{
    public void OnLocationChanged(Location location)
    {
    }

    public void OnProviderDisabled(string provider)
    {
    }

    public void OnProviderEnabled(string provider)
    {
    }

    public void OnStatusChanged(string provider, Availability status, Bundle extras)
    {
    }
}

In your activity you can declare that you'd like to use this class to start listening for updates like this:

var locationManager = (LocationManager)GetSystemService(LocationService);
var locationListener = new MyLocationListener();

locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 5000, 2, locationListener);


来源:https://stackoverflow.com/questions/10449969/unable-to-get-the-location-updates-in-monodroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!