位置监听器

时间:2011-01-25 09:40:52

标签: android listener latitude-longitude

我正在使用位置监听器来获得更长的时间lat为我的Android应用程序。

我正在使用以下代码:

public Location getLastKnownLocation()
{
 Location location=null;
 try
 {
 // Get the location manager
 mLocMgr = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
 // List all providers:
 // List<String> providers = mLocMgr.getAllProviders();

 Criteria criteria = new Criteria();
 bestProvider = mLocMgr.getBestProvider(criteria, false);
 location = mLocMgr.getLastKnownLocation(bestProvider);
 if(location==null)
 {
  Thread.sleep(5000);
  location=mLocMgr.getLastKnownLocation(bestProvider);
 }
 }
 catch(Exception e)
 {
  Log.i("program", e.getMessage());
 }
 return location;
}

public Location updateCurrentLocation()
{
 Location mLoc=null;
 try
 {
 mLoc=getLastKnownLocation();
 mlocListener = new LocListener(); 
 mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
 mLoc=getLastKnownLocation();
 }
 catch(Exception e)
 {
  Log.e("program", e.getMessage());
 }
 return mLoc;
}

它工作得非常好。但是当我们关闭设备并重新启动它时面临问题。然后我得到的位置为null。 然而,在启动谷歌地图后,它再次开始工作。 所以,请你帮我解决这个问题,因为我不想在开始申请之前启动谷歌地图。感谢您的支持!

2 个答案:

答案 0 :(得分:3)

关闭电源并打开设备电源时,getLastKnownLocation方法可能会失败。

而且,我看到了,在订阅位置更新列表之前,您正在调用它:

 mLoc=getLastKnownLocation();  //<<<<<<<<<<<<<
 mlocListener = new LocListener(); 
 mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);

为什么需要致电getLastKnownLocation()?启动设备时它不会立即生效。

当您使用Google地图时,它会优雅地尝试收听位置更新。而且,一旦它至少获得一个位置更新,那么您的getLastKnownLocation将开始工作。

我看到你的架构需要重新思考(如果你的方法名称合适)

当你的app启动时,应该在某个适当的位置调用它。

mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);

然后,在onLocationChanged(Location location)

中执行您需要的任何更新

答案 1 :(得分:1)

Little Fluffy位置库: http://code.google.com/p/little-fluffy-location-library/

简单,快速,简单!

此库会通知您的位置更新。

相关问题