1

创建我的第一个应用程序,

使用 GoogleApi 查找位置并且回调按预期工作。我使用该位置并将其放入数据库中, onDestroy() 我正在关闭数据库连接。但现在我偶尔会得到一个堆栈跟踪说

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

我在 closeDB 调用之前添加了一个 removeLocationUpdates() ,这基本上解决了这个问题,但它仍然不时发生。在调用 removeLocationUpdates 和 closeDB 之后,我可能仍然会收到恶意回调。

这是典型的延迟吗?removeLocUpdates 和 closeDB 之间的 500 毫秒延迟可以解决问题吗?我想会有更好的方法,或者我可能只是在 removeLocUpdates 上做错了什么。但是堆栈跟踪似乎很清楚,正如跟踪所示,我正在收到回调

onLocationChanged

在堆栈中的一部分

编辑添加代码:

创建():

        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;
}

感谢您对此事的帮助

4

0 回答 0