【发布时间】:2011-03-03 05:29:03
【问题描述】:
我正在处理的 Android 应用程序上遇到位图问题。假设发生的是应用程序从网站下载图像,将它们保存到设备,将它们作为位图加载到内存中并放入数组列表中,然后将它们显示给用户。首次启动应用程序时,这一切正常。但是,我为删除图像的用户添加了一个刷新选项,并且上面概述的过程从头开始。
我的问题:通过使用刷新选项,旧图像仍在内存中,我很快就会得到 OutOfMemoryErrors。因此,如果正在刷新图像,我让它通过 arraylist 运行并回收旧图像。但是,当应用程序将新图像加载到数组列表中时,它会因“尝试使用回收的位图”错误而崩溃。
据我了解,回收位图会破坏位图并释放其内存以供其他对象使用。如果我想再次使用位图,它必须重新初始化。我相信当新文件加载到数组列表中时我正在这样做,但仍然有问题。非常感谢任何帮助,因为这非常令人沮丧。问题代码如下。谢谢!
public void fillUI(final int refresh) {
// Recycle the images to avoid memory leaks
if(refresh==1) {
for(int x=0; x<images.size(); x++)
images.get(x).recycle();
images.clear();
selImage=-1; // Reset the selected image variable
}
final ProgressDialog progressDialog = ProgressDialog.show(this, null, this.getString(R.string.loadingImages));
// Create the array with the image bitmaps in it
new Thread(new Runnable() {
public void run() {
Looper.prepare();
File[] fileList = new File("/data/data/[package name]/files/").listFiles();
if(fileList!=null) {
for(int x=0; x<fileList.length; x++) {
try {
images.add(BitmapFactory.decodeFile("/data/data/[package name]/files/" + fileList[x].getName()));
} catch (OutOfMemoryError ome) {
Log.i(LOG_FILE, "out of memory again :(");
}
}
Collections.reverse(images);
}
fillUiHandler.sendEmptyMessage(0);
}
}).start();
fillUiHandler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
【问题讨论】: