简体   繁体   English

如何在Android应用程序的整个生命周期中保持全局db4o

[英]How to keep a global db4o throughout the lifecycle of an android application

We are developing an Android application that uses db4o for storing various objects throughout multiple activities and services. 我们正在开发一个使用db4o在多个活动和服务中存储各种对象的Android应用程序。 We are looking for the best approach on working with db4o and specifically when to open and close the db. 我们正在寻找使用db4o的最佳方法,尤其是何时打开和关闭db。 We don't want to close the db after each single store operation and reopen it on every single retrieve operation because that could impact the speed of the application as opening and closing is hard on the processor. 我们不想在每个单个存储操作之后关闭数据库,并在每个单个检索操作上重新打开它,因为这可能会影响应用程序的速度,因为打开和关闭操作很难在处理器上进行。 We prefer to keep a global state of the db4o that can be used throughout the app's lifecycle. 我们希望保留db4o的全局状态,该状态可在应用程序的整个生命周期中使用。

I was reading here global db4o database for multiple activities that is a good idea to keep the database on a Custom Application Object and get an instance when we need it: 我在这里阅读了多个活动的全局db4o数据库,这是将数据库保留在“定制应用程序对象”上并在需要时获取实例的一个好主意:

public class MyApplication extends Application {
    private volatile ObjectContainer container;
    @Override
    public void onCreate() {
        super.onCreate();
        // the application object is a regular Android context,
        // So you can get the required info`
        this.container = Db4oEmbedded.openFile(...)
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        // if something was not finished, better rollback
        container.rollback();
        container.close();
    }

    public ObjectContainer database(){
        return container;
    }
}

However, I realised that the onTerminate() method of the Application exists only for emulation purposes and is never executed on an actual phone. 但是,我意识到该应用程序的onTerminate()方法仅用于仿真目的,而从未在实际的电话上执行。 And my question is, if the onTerminate() is never called where should we close the db object, and was is the best strategy on opening and closing? 我的问题是,如果从不调用onTerminate()来关闭数据库对象,那么打开和关闭的最佳策略是吗?

您可以在应用程序类中创建延迟加载单例实例,然后在Launching Activity的OnCreate方法中对其进行初始化(打开),然后在onDestroy中将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM