AsyncQueryHandler 与 ContentProvider 是必要的吗?

AsyncQueryHandler with ContentProvider is necessary?

我的问题很简单:如果我通过来自 UIThread 的 ContentProvider 在 SQLLite 数据库中插入、更新或删除单行,是否需要 AsyncQueryHandler 的实现?

我知道最佳实践是在异步任务中实现 CRUD 操作,而且关于一行的 CRUD 语句执行起来并不那么繁重。 事实上,Android Studio 也没有提醒他不应该 运行 在 UI 线程上的声明,我在网上找到的关于 ContentProvider 的所有指南都没有提到 ASyncQueryHandler。所有 CRUD 操作都在直接调用 ContentProvider 的 UI 线程上执行。

最好只为所有 ContentProvider 操作走异步路线。我知道这可能很痛苦,但考虑一下:

您的简单单行插入通常需要几毫秒才能等待更大的事务完成。也许您正忙于 SyncAdapter 做很多事情?您的小插件突然需要更长的时间,甚至可能导致 ANR。

我知道机会很小,但机会还是有的。最好只接受样板代码并继续使用它 ;-)

示例样板代码粘贴到 activity class:

private class UpdateHandler extends AsyncQueryHandler {

    private final WeakReference<YourActivityClass> mActivityRef;

    public UpdateHandler(YourActivityClass activity, ContentResolver cr) {
        super(cr);

        mActivityRef = new WeakReference<>(activity); // do a weak reference incase the update takes ages and the activity gets destroyed during
    }

    @Override
    protected void onUpdateComplete(int token, Object cookie, int result) {
        super.onUpdateComplete(token, cookie, result);

        YourActivityClass exampleActivity = mActivityRef.get();
        if (exampleActivity != null) {
            exampleActivity .onUpdateCompleted(token);
        }
    }
}


public void saveStuffToDatabase() {

    // do some stuff like show a progress bar or whatever

    // actually do the update operation
    new UpdateHandler(this, getContentResolver()).startUpdate(
            0,              // this will be passed to "onUpdatedComplete" in the updateHandler
            null,           // so will this!
            uri,
            values
    );


}

private void onUpdateCompleted(int token) {
    // this runs in the main thread after the update you started in saveStuffToDatabase() is complete

}