Android GPS Location Update Method does not work in OnCreate of Map activity

牧云@^-^@ 提交于 2019-12-08 11:08:46

问题


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();         
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, lcs);

Can anyone tell me how I will be able to get my current location in my onCreate()?


回答1:


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 :)




回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/7556738/android-gps-location-update-method-does-not-work-in-oncreate-of-map-activity

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