Android 获取最后已知位置的问题

Android 获取最后已知位置的问题,android,google-maps-android-api-2,locationmanager,Android,Google Maps Android Api 2,Locationmanager,我在两部手机上测试我的应用程序(1)一部运行2.3.7的LG Optima和(2)一部运行4.1.2的galaxy S3。以下代码始终在LG上运行,并且始终在Galaxy上出现nullPointerException时失败 try { //sometimes getting the last known location gets a nullpointerexception String locationProvider = LocationManager.GPS_PROVIDER;

我在两部手机上测试我的应用程序(1)一部运行2.3.7的LG Optima和(2)一部运行4.1.2的galaxy S3。以下代码始终在LG上运行,并且始终在Galaxy上出现nullPointerException时失败

try { //sometimes getting the last known location gets a nullpointerexception
    String locationProvider = LocationManager.GPS_PROVIDER;
    locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location myLoc = locMgr.getLastKnownLocation(locationProvider);
    CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()));
    map.animateCamera(center);
    DebugLog.debugLog("Instantiated new Location listener.  Moved camera to: " + myLoc.getLatitude() + myLoc.getLongitude() , false);

} catch (Exception e) {
    DebugLog.debugLog("Exception getting lastknownlocation - doing without" + e, false);
}
这个代码有什么问题吗? 谢谢 加里

这个代码有什么问题吗


您没有检查
myLoc
是否为
null
。不必返回非
null
值。

以防出现注释:是的,他确实捕捉到异常,但异常是异常行为,而不是预期的行为,并且
null
返回值在这里是预期的。也就是说,虽然这个答案确实有道理,但我认为它没有抓住要点。我想OP是在问为什么
getLastKnownLocation
在他的银河系中不返回任何东西。@IngoBürk:
getLastKnownLocation()
将在需要时返回
null
。:-)在这种情况下,有很多可能性:GPS被禁用,自上次重新启动以来GPS没有被使用(通过
requestLocationUpdate()
,等等),GPS最近被使用过,AOSP/Samsung没有缓存那么长的值,等等。“我想它没有抓住要点”——欢迎你提出任何你想要的观点。我的观点是,
getLastKnownLocation()
可以并将返回
null
。Ingo Burk准确地描述了我问题的要点(我意识到我应该检查null,而不是使用Try/Catch)。原来独立Loc服务是关闭的,但谷歌Loc服务和Verizon Loc服务是打开的。我应该问我是否提供了。