Android的GPS位置更新方法不会地图活动的工作的OnCreate [英] Android GPS Location Update Method does not work in OnCreate of Map activity

查看:130
本文介绍了Android的GPS位置更新方法不会地图活动的工作的OnCreate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在面临的的LocationManager 类问题:

我想在的onCreate() MapActivity 扩展一个类来更新我的当前位置:

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

,而 getLastKnownLocation()返回位置,但不准确的,我要打电话 LocationManager.requestLocationUpdates()返回的onCreate()

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

谁能告诉我怎么就能得到我的当前位置我的的onCreate()

推荐答案

的LocationManager 仅适用于使用提供侦听您code通信。当新的位置锁定可用,<一个href=\"http://developer.android.com/reference/android/location/LocationListener.html#onLocationChanged%28android.location.Location%29\"相对=nofollow> onLocationChanged() 将在 LCS被称为的实例 MyLocationListener 类的创建。

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.

您不想冒险您的应用程序被强制关闭,而在的onCreate等待第一个定位()

You don't want to risk your app being force closed while waiting for the first location fix in onCreate().

最佳做法是注册 LocationListener的 onResume()注销它再次在的onPause()使用<一个href=\"http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates%28android.location.LocationListener%29\"相对=nofollow> LocationManager.removeUpdates(LocationListener的) 。你的用户会感谢你不消耗自己的电池当你的应用程序是不是在前台:)

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

这篇关于Android的GPS位置更新方法不会地图活动的工作的OnCreate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆