getLastLocation 第二次不起作用
getLastLocation does not work on second time
我正在使用 google 播放服务来获取用户最后的已知连接。
@Override
public void onConnected(Bundle connectionHint) {
final Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(
_googleApiClient);
}
@Override
protected void onResume() {
super.onResume();
connectToGooglePlay();
}
@Override
protected void onPause() {
super.onPause();
if (_googleApiClient != null) {
_googleApiClient.disconnect();
}
}
按预期工作。
每当我单击后退按钮然后再次启动应用程序时,就会出现问题。我的应用程序崩溃,因为 getLastLocation
return 为空。正式文档说明 -
If a location is not available, which should happen very rarely, null
will be returned.
很好,但是我确定某个位置存在,我刚刚在一秒钟前检索到它。
我做了一个快速实验并删除了 _googleApiClient.disconnect();
并且它起作用了,断开连接以某种方式删除了最后一个位置
为什么?我错过了什么吗?
需要考虑的几点:
1) 您应该在 onStart()
中连接到 GoogleApiClient
并在中断开连接
onStop()
:
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
2) 您的代码应始终假定 getLastLocation()
可能 return null
。进行空检查。
3) 使用 getLastLocation()
时使用 isLocationAvailable()
。如果 return 为真,则可以假定由 getLastLocation()
编辑的位置 return 是最新的。
找到问题了。
我正在使用 roboguice 进行注射。
我没有每次都创建一个新的 GoogleApiClient.Builder,而是使用单例只创建了一次,看起来调用 disconnect 时它破坏了构建器的状态。
解决方案 - 每次我需要创建一个 GoogleApiClient 时,我都会创建一个新的构建器
我正在使用 google 播放服务来获取用户最后的已知连接。
@Override
public void onConnected(Bundle connectionHint) {
final Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(
_googleApiClient);
}
@Override
protected void onResume() {
super.onResume();
connectToGooglePlay();
}
@Override
protected void onPause() {
super.onPause();
if (_googleApiClient != null) {
_googleApiClient.disconnect();
}
}
按预期工作。
每当我单击后退按钮然后再次启动应用程序时,就会出现问题。我的应用程序崩溃,因为 getLastLocation
return 为空。正式文档说明 -
If a location is not available, which should happen very rarely, null will be returned.
很好,但是我确定某个位置存在,我刚刚在一秒钟前检索到它。
我做了一个快速实验并删除了 _googleApiClient.disconnect();
并且它起作用了,断开连接以某种方式删除了最后一个位置
为什么?我错过了什么吗?
需要考虑的几点:
1) 您应该在 onStart()
中连接到 GoogleApiClient
并在中断开连接
onStop()
:
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
2) 您的代码应始终假定 getLastLocation()
可能 return null
。进行空检查。
3) 使用 getLastLocation()
时使用 isLocationAvailable()
。如果 return 为真,则可以假定由 getLastLocation()
编辑的位置 return 是最新的。
找到问题了。
我正在使用 roboguice 进行注射。
我没有每次都创建一个新的 GoogleApiClient.Builder,而是使用单例只创建了一次,看起来调用 disconnect 时它破坏了构建器的状态。
解决方案 - 每次我需要创建一个 GoogleApiClient 时,我都会创建一个新的构建器