据我所知,我无法在Loader
内提及活动的上下文。
是否有一种安全的方法可以在Loader
的{{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
类保留的上下文中获取资源,因为它是应用程序上下文。