2011-01-25 197 views
1

我正在使用位置侦听器来获取我的android应用程序的long 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地图。感谢您的支持!

回答

3

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

而且,我看到的是,你在呼唤它,你订阅的位置更新利斯特前:

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

为什么你需要调用getLastKnownLocation()?当您启动设备时它不会立即工作。

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

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

这应该只进行一次调用,在一些适当的位置,当你的应用程序发起。

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

然后,你需要的任何更新的onLocationChanged(Location location)

+0

太棒了..它帮助了我。谢谢 – Pankaj 2011-01-27 10:26:14