java - 如何在简单的非 Activity java 类中创建类似于 onDestroy 的方法?

标签 java android ondestroy

我想在类的实例关闭或销毁时执行一两个操作。我正在寻找类似于 Activity 中的 onDestroy 的东西。

编辑

我已经添加了我的代码,其中指明了我如何从我的 Helper 类返回 SQLiteDatabase。我使用终结代码来确保数据库已关闭。

public class PMDBDatabase {

    private static SQLiteDatabase DataBase = null;
    private static PMDBHelper dbHelper = null;

    public SQLiteDatabase getDatabase(Context ctx) throws SQLException {
        if (DataBase == null) {
            dbHelper = PMDBHelper.getInstance(ctx);
            DBOpen();
        } else
            if(!DataBase.isOpen())
                DBOpen();
        return DataBase;
    }

    private void DBOpen() throws SQLException {
        DataBase = dbHelper.getWritableDatabase();
    }

    public void close(){
        if(DataBase != null)  DataBase.close();
    }

    protected void finalize() throws Throwable {
        try {
            close();
        } finally {
            super.finalize();
        }
    }
}

能否请您帮助这位Java/Android编程新手并指出finalize的实现是否正确?

非常感谢您的宝贵时间,

最佳答案

你不能这样做,因为 GC 会自动处理它。

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector.

完成

It is possible to use something similar to a destructor in Java, the method Object.finalize() , which however does not work exactly like a standard destructor would.

关于java - 如何在简单的非 Activity java 类中创建类似于 onDestroy 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32559282/

相关文章:

java - 多部分 Http 请求

android - 我无法设置 TextView layout_height 来包装内容

android - 显示来自 URL 的图像 - 大小和屏幕方向问题

android - 是否确保在 finish() 之后调用 onDestroy()?

android - 为什么关闭我的android程序不会关闭?

java - 如何在 tx 提交之前获取添加到 JPA 关系的新实体的主键?

Java:如何处理试图修改同一个文件的两个进程

java.lang.IllegalArgumentException : Parse error: Unable to parse Date format 异常

android - TableLayout(TableRow?)在动态添加时未按预期调整 subview 的大小

android - 防止 Activity 在按下后退按钮时被破坏