Loader的loadInBackground()里面的资源?

时间:2017-06-06 11:33:57

标签: android android-resources android-context android-loadermanager android-loader

据我所知,我无法在Loader内提及活动的上下文。

是否有一种安全的方法可以在Loader的{​​{1}}方法中获取资源?

1 个答案:

答案 0 :(得分:0)

请参阅Loader的构造函数的the docs

  

Loader (Context context)

     

存储与上下文关联的应用程序上下文。由于 Loaders 可用于多个活动,因此直接存储上下文会很危险;始终使用 getContext()来检索 Loader 上下文,不要直接使用构造函数参数。 getContext()返回的上下文可以安全地在活动实例中使用。

实施:


    public Loader(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * @return an application context retrieved from the Context passed to the constructor.
     */
    public Context getContext() {
        return mContext;
    }


因此,在loadInBackground()中,您可以自由地从Loader类保留的上下文中获取资源,因为它是应用程序上下文。