简体   繁体   English

Android GPS位置更新方法在OnCreate of Map活动中不起作用

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

I am facing a problem with the LocationManager class: 我遇到了LocationManager类的问题:

I want to update my current location in onCreate() of a class extended from MapActivity : 我想更新我在MapActivity扩展的类的onCreate()中的当前位置:

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() : getLastKnownLocation()返回的位置却不准确,我想调用在onCreate()返回null LocationManager.requestLocationUpdates() 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() ? 任何人都可以告诉我如何在我的onCreate()获取我当前的位置?

LocationManager only communicates with your code using the supplied listener. LocationManager仅使用提供的侦听器与您的代码进行通信。 When a new location fix is available, onLocationChanged() will be called in the lcs instance of the MyLocationListener class your created. 当新的位置修复可用时,将在您创建的MyLocationListener类的lcs实例中调用onLocationChanged()

You don't want to risk your app being force closed while waiting for the first location fix in onCreate() . 您不希望在等待onCreate()的第一个位置修复时强制关闭应用程序。

Best practice is to register your LocationListener in onResume() and also unregister it again in onPause() using LocationManager.removeUpdates(LocationListener) . 最佳做法是在onResume()注册LocationListener ,并使用LocationManager.removeUpdates(LocationListener)onPause()再次注销它。 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. 我通过实现很少的时间延迟来实现我的目标,并且每件事情都开始正常工作,我的主要目标是在Oncreate方法中获得位置。 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. 它得出的结论是OnCreate方法首先调用,OnResume稍后如果你想通过map randering获取当前位置,那么你必须先等待map渲染然后调用位置更新代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM