ContentProvider何时调用Application.onCreate

时间:2019-06-24 18:14:33

标签: android

我有一个Android应用,它公开了ContentProvider的openFile方法。该方法访问在Application.onCreate方法中初始化的变量。此数据将作为null返回,但是如果我延迟放置,它将恢复为初始化状态。知道为什么除非我延迟才返回null?我以为这一切都会在同一线程上发生。请参见下面的代码。

public class MyApplication extends Application {
    private MyDatabase database;

    @Override
    public void onCreate() {
        super.onCreate();
        database = new MyDatabase(this);
    }

    public MDRSDatabase getDatabase() {
        return database;
    }
}

public class ExternalContentProvider extends ContentProvider {
    @Nullable
    @Override
    public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
        // d will be null after the following call, but if I stick brief sleep here it won't be.
        MyDatabase d = (MyApplication)getContext().getApplicationContext().getDatabase();
    }
}

更新:在onCreate和openFile方法中记录线程ID确实表明,在与ContentProvider.openFile不同的线程上调用Application.onCreate。怎么办呢? ContentProvider如何知道何时完成onCreate?

更新2:在CommonsWare评论之后,我修改了MyApplication。这似乎确实解决了问题。但是,我无法在在线搜索中找到任何与此相关的体面文档,因此我在某种程度上视而不见。

public class MyApplication extends Application {
    private MyDatabase database;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        database = new MyDatabase(this);
    }

    public MDRSDatabase getDatabase() {
        return database;
    }
}

0 个答案:

没有答案