0

在 API16 中,Android 的 SQLiteDatabase 类中引入了新的 WAL(预写日志)。我想测试是否为 SQLite 数据库启用了 WAL。该应用程序也可以在较旧的 Android 版本上运行,因此我需要 SQLiteDatabase 中这些新函数的包装类。功能是:

  • 公共布尔 isWriteAheadLoggingEnabled()
  • 公共布尔 enableWriteAheadLogging()
  • 公共无效禁用WriteAheadLogging()

Android 开发者博客中,我确实找到了一篇关于包装新类的包装类的文章。我没有找到一个已经存在的类中新方法的包装器。我该怎么做?

4

1 回答 1

1

for 的构造函数SQLiteDatabase是私有的,因此您将无法扩展它并将“包装器”添加到类本身。但是,您可以像这样编写一个“助手”包装器:

public class WALWrapper {
    private boolean mAvailable;
    private Method mIsWriteAheadLoggingEnabled;
    private Method mEnableWriteAheadLogging;
    private Method mDisableWriteAheadLogging;
    private final SQLiteDatabase mDb;

    public WALWrapper(SQLiteDatabase db) {
        mDb = db;
        mAvailable = false;
        try {
            mIsWriteAheadLoggingEnabled =
                    SQLiteDatabase.class.getMethod("isWriteAheadLoggingEnabled");
            mEnableWriteAheadLogging =
                    SQLiteDatabase.class.getMethod("enableWriteAheadLogging");
            mDisableWriteAheadLogging =
                    SQLiteDatabase.class.getMethod("disableWriteAheadLogging");
            mAvailable = true;
        } catch (NoSuchMethodException e) {
        }
    }

    /**
     * Returns <code>true</code> if the {@link #isWriteAheadLoggingEnabled()},
     * {@link #enableWriteAheadLogging()} and {@link #disableWriteAheadLogging()}
     * are available.
     * @return <code>true</code> if the WALWrapper is functional, <code>false</code>
     *  otherwise.
     */
    public boolean isWALAvailable() {
        return mAvailable;
    }

    public boolean isWriteAheadLoggingEnabled() {
        boolean result = false;
        if (mIsWriteAheadLoggingEnabled != null) {
            try {
                result = (Boolean) mIsWriteAheadLoggingEnabled.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        return result;
    }

    public boolean enableWriteAheadLogging() {
        boolean result = false;
        if (mEnableWriteAheadLogging != null) {
            try {
                result = (Boolean) mEnableWriteAheadLogging.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        return result;
    }

    public void disableWriteAheadLogging() {
        if (mDisableWriteAheadLogging != null) {
            try {
                mDisableWriteAheadLogging.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
    }
}
于 2012-08-10T10:11:24.760 回答