这可能更像是一个 Java 问题而不是 Android 问题,但是我无法检索在 AsyncTask 中创建的位图以存储在另一个类(一个活动)中,以便在我使用完它时可以回收它。
AsyncTask 在 doInBackground() 中创建 Bitmap,并在 onPostExecute() 中将其设置为 ImageView 的位图,ImageView 通过构造函数传入。但完成后,我希望在 Activity 中可以访问位图。Activity 有一个 ImageViews 的 ArrayList 和另一个 Bitmaps,但是由于 AsyncTask 创建了一个新的 Bitmap,我找不到在 Activity 的 Bitmaps 的 ArrayList 中获取这个新对象的简单方法。目前,我通过将 ArrayList 以及列表中的索引传递给 AsyncTask 构造函数来使其工作,并且 doInBackground 只是将数组中的该条目设置为新创建的位图。
不过我不喜欢这个解决方案,因为我希望能够将这个 AsyncTask 用于不同的事情,也许是 Activity 没有位图的 ArrayList。而且我不能简单地给 AsyncTask 构造函数一个 Bitmap,因为 Java 按值传递引用,并且将其设置为新的 Bitmap 对象将不允许调用者访问。
我怎样才能更优雅地做到这一点?
这是相关的代码。为清楚起见,省略了与此问题无关的行。
public class LoadCachedImageTask extends AsyncTask<String, Void, Void> {
private Context context;
private ImageView image;
private ArrayList<Bitmap> bitmaps;
int index;
public LoadCachedImageTask(Context context, ImageView image, ArrayList<Bitmap> bitmaps, int index) {
this.context = context;
this.image = image;
this.bitmaps = bitmaps;
this.index = index;
}
protected Void doInBackground(String... urls) {
String url = urls[0];
Bitmap bitmap = null;
// Create the bitmap
File imageFile = new File(context.getCacheDir(), "test");
bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// Set the bitmap to the bitmap list
bitmaps.set(index, bitmap);
return null;
}
protected void onPostExecute(Void arg) {
// Display the image
image.setImageBitmap(bitmaps.get(index));
}
protected void onCancelled() {
if (bitmaps.get(index) != null) {
bitmaps.get(index).recycle();
bitmaps.set(index, null);
}
}
}
这是一个使用它的示例 Activity。
public class SampleActivity extends Activity {
private ArrayList<ImageView> images;
private ArrayList<Bitmap> bitmaps;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
images = new ArrayList<ImageView>();
bitmaps = new ArrayList<Bitmap>();
int numImages = 15;
// Create the images and bitmaps
for (int i = 0; i < numImages; i++) {
images.add(new ImageView(this));
bitmaps.add(null);
}
// Load the bitmaps
for (int i = 0; i < numImages; i++) {
new LoadCachedImageTask(this, images.get(i), bitmaps, i).execute("http://random.image.url");
}
}
}
我没有测试上面的代码,所以它可能不起作用,但我认为它明白了这一点。