我使用location listener为我的android应用程序获取long & lat。
我正在使用以下代码:
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;
}它工作得非常好。但是当我们关闭设备并重新启动它时,就会面临这个问题。那么我得到的位置是空的。然而,在启动google地图之后,它又开始工作了。所以你们能帮我解决这个问题吗?因为我不想在启动我的应用程序之前启动google地图。感谢您的支持!
发布于 2011-01-25 18:34:18
当您关闭并打开设备电源时,您的getLastKnownLocation方法可能会失败。
而且,我看到了,您在订阅位置更新列表器之前调用它:
mLoc=getLastKnownLocation(); //<<<<<<<<<<<<<
mlocListener = new LocListener();
mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);为什么需要调用getLastKnownLocation()?当您启动设备时,它不会立即起作用。
当你使用谷歌地图时,它会优雅地尝试监听位置更新。而且,一旦它获得至少一个位置更新,那么您的getLastKnownLocation将开始工作。
我认为您的体系结构需要重新思考(如果您的方法名称合适)
当你的应用程序启动时,这应该只在适当的位置调用一次。
mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);然后,在onLocationChanged(Location location)中执行所需的任何更新
发布于 2012-12-13 19:20:08
https://stackoverflow.com/questions/4791888
复制相似问题