11

该文档指出,如果成功加载提供程序,我们应该返回 true,否则返回 false。在我的实现中,如果 DatabaseHelper == null,我将返回 false。

假设现在在 onCreateDatabaseHelper == null中返回false,稍后在代码中的某处查询提供程序,提供程序仍在被查询,因为它会崩溃。

我的问题是在 ContentProvider 的 OnCreate 中返回 false 有什么用?在 onCreate 失败后我应该如何处理查询?只是再次运行查询中的onCreate?

4

1 回答 1

12

在 ContentProvider 的 OnCreate 中返回 false 有什么用?

通过快速浏览 Android 源代码,我发现,就目前而言,返回什么实际上并不重要,它只是被忽略了,同样是现在

在测试和ActivityThread,attachInfo之后立即调用,newInstance因此如果您查看第 1058 行ContentProvider的源代码,则调用它的位置如下所示:onCreate

/**
 * After being instantiated, this is called to tell the content provider
 * about itself.
 *
 * @param context The context this provider is running in
 * @param info Registered information about this content provider
 */
public void attachInfo(Context context, ProviderInfo info) {
    /*
     * We may be using AsyncTask from binder threads.  Make it init here
     * so its static handler is on the main thread.
     */
    AsyncTask.init();

    /*
     * Only allow it to be set once, so after the content service gives
     * this to us clients can't change it.
     */
    if (mContext == null) {
        mContext = context;
        mMyUid = Process.myUid();
        if (info != null) {
            setReadPermission(info.readPermission);
            setWritePermission(info.writePermission);
            setPathPermissions(info.pathPermissions);
            mExported = info.exported;
        }
        ContentProvider.this.onCreate();
    }
}

请记住,如果文档这么说谁知道,也许这将在未来的版本中使用/修复。


onCreate失败后我应该如何处理查询?只是再次运行查询中的onCreate?

我会说是的,不一定是onCreate您自己的方法,该方法初始化一次并确保您的DatabaseHelper左右,这将是您的最大努力,我的意思是根据文档onCreate

您应该推迟重要的初始化(例如打开、升级和扫描数据库),直到使用内容提供程序

所以从技术上讲,你会按预期做,但那里很疯狂,所以要安全。

于 2013-06-12T00:50:18.093 回答