Android GPS Location Update Method does not work in OnCreate of Map activity
I am facing a problem with the LocationManager
class:
I want to update my current location in onCreate()
of a class extended from MapActivity
:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener lcs = new MyLocationListener();
lcs.onLocationChanged(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
whereas getLastKnownLocation()
returns the location but inaccurate, I want to call LocationManager.requestLocationUpdates()
which returns null
in onCreate()
:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener lcs=new MyLocationListener();
l开发者_如何学Gom.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, lcs);
Can anyone tell me how I will be able to get my current location in my onCreate()
?
LocationManager
only communicates with your code using the supplied listener. When a new location fix is available, onLocationChanged()
will be called in the lcs
instance of the MyLocationListener
class your created.
You don't want to risk your app being force closed while waiting for the first location fix in onCreate()
.
Best practice is to register your LocationListener
in onResume()
and also unregister it again in onPause()
using LocationManager.removeUpdates(LocationListener)
. Your users will thank you for not draining their battery when your app isn't in the foreground :)
Thanks, guys for responding and giving very reasonable suggestion but unfortunatly these didnt worked for me.
I acheived my goal by implementing little time delay and every thing started working fine and my primary goal of getting location in Oncreate method is acheived. It came up with the understanding that OnCreate method called first and OnResume later if you want to get your current location with map randering then you will have to wait for map to be render first then call the location update code.
here is the tutorial http://www.androidcompetencycenter.com/?s=GPS
or try this http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/
精彩评论