创建我的第一个应用
使用GoogleApi查找位置,回调正在按预期工作。我使用该位置并将其放入数据库,onDestroy()我正在关闭数据库连接。但现在我偶尔会得到一个堆栈跟踪说
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
我在closeDB调用之前添加了一个removeLocationUpdates(),并且MOSTLY解决了这个问题,但它仍然不时发生。看来我在调用removeLocationUpdates和closeDB后仍然会收到一个流氓回调。
这是典型的延迟吗? removeLocUpdates和closeDB之间有500ms的延迟可以解决这个问题吗?我想有更好的方法,或者我可能只是对removeLocUpdates做错了。但是堆栈跟踪似乎非常清楚,我正在收到回调,因为跟踪显示
onLocationChanged
在堆栈的一部分
编辑添加代码:
的onCreate():
openDB();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//End Google Location API implementation
locationListener = new com.google.android.gms.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
//newestLocation = location;
//bestLocation = bestLocation();
//todo maybe come back and reimplement bestLocation() if needed
bestLocation = location;
getCode(null);
saveCode(null);
}};
的onDestroy()
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener);
}
}
closeDB();
onConnected()
public void onConnected(@Nullable Bundle bundle) {
CharSequence text = "Google API Connected";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
LocationRequest locationRequest = new LocationRequest()
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setMaxWaitTime(3000)
.setInterval(1000);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},10);
return;
}else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, locationListener);
}
return;
}
感谢您对此事的帮助