首先是问题:
- 我正在开发
FragmentLists
在自定义FragmentStatePagerAdapter
. 可能存在大量此类片段,例如 20 到 40 个。 - 每个片段都是一个列表,其中每个项目都可以包含文本或图像。
- 图像需要从网络异步上传并缓存到临时内存缓存,如果可用,还可以缓存到 SD
- 当 Fragment 离开屏幕时,应取消任何上传和当前活动(不暂停)
我的第一个实现遵循谷歌著名的图像加载器代码。我对该代码的问题是它基本上为AsyncTask
每个图像创建一个实例。在我的情况下,这会很快杀死应用程序。
由于我使用的是 v4 兼容包,我认为使用扩展的自定义加载器AsyncTaskLoader
会对我有所帮助,因为它在内部实现了一个线程池。但是令我不快的是,如果我多次执行此代码,则每次后续调用都会中断前一次。假设我的ListView#getView
方法中有这个:
getSupportLoaderManager().restartLoader(0, args, listener);
此方法在循环中针对进入视图的每个列表项执行。正如我所说 - 每个后续调用都将终止前一个。或者至少这就是基于 LogCat 发生的事情
11-03 13:33:34.910: V/LoaderManager(14313): restartLoader in LoaderManager: args=Bundle[{URL=http://blah-blah/pm.png}]
11-03 13:33:34.920: V/LoaderManager(14313): Removing pending loader: LoaderInfo{405d44c0 #2147483647 : ImageLoader{405118a8}}
11-03 13:33:34.920: V/LoaderManager(14313): Destroying: LoaderInfo{405d44c0 #2147483647 : ImageLoader{405118a8}}
11-03 13:33:34.920: V/LoaderManager(14313): Enqueuing as new pending loader
然后我想也许给每个加载器提供唯一的 id 会有所帮助,但它似乎没有任何区别。结果,我最终得到了看似随机的图像,并且该应用程序甚至从未加载我需要的 1/4。
问题
- 什么方法可以修复 Loader 做我想做的事情(有没有办法?)
- 如果不是什么是创建
AsyncTask
池的好方法,是否有可能实现它?
为了让您了解这里的代码,这是 Loader 的精简版本,其中实际的下载/保存逻辑位于单独的 ImageManager 类中。
public class ImageLoader extends AsyncTaskLoader<TaggedDrawable> {
private static final String TAG = ImageLoader.class.getName();
/** Wrapper around BitmapDrawable that adds String field to id the drawable */
TaggedDrawable img;
private final String url;
private final File cacheDir;
private final HttpClient client;
/**
* @param context
*/
public ImageLoader(final Context context, final String url, final File cacheDir, final HttpClient client) {
super(context);
this.url = url;
this.cacheDir = cacheDir;
this.client = client;
}
@Override
public TaggedDrawable loadInBackground() {
Bitmap b = null;
// first attempt to load file from SD
final File f = new File(this.cacheDir, ImageManager.getNameFromUrl(url));
if (f.exists()) {
b = BitmapFactory.decodeFile(f.getPath());
} else {
b = ImageManager.downloadBitmap(url, client);
if (b != null) {
ImageManager.saveToSD(url, cacheDir, b);
}
}
return new TaggedDrawable(url, b);
}
@Override
protected void onStartLoading() {
if (this.img != null) {
// If we currently have a result available, deliver it immediately.
deliverResult(this.img);
} else {
forceLoad();
}
}
@Override
public void deliverResult(final TaggedDrawable img) {
this.img = img;
if (isStarted()) {
// If the Loader is currently started, we can immediately deliver its results.
super.deliverResult(img);
}
}
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (this.img != null) {
this.img = null;
}
}
}