public class PageActivity extends Activity {
private int numPages = 31;
private TouchImageView[] imageViews = new TouchImageView[numPages];
private String URL = "http://www.smbc-comics.com/comics/201108";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager viewPager = new ViewPager(this);
for (int i = 0; i < numPages; i++) {
imageViews[i] = new TouchImageView(this);
imageViews[i].setBackgroundResource(R.drawable.blank);
imageViews[i].setMaxZoom(4f);
}
setContentView(viewPager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
private class ImagePagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return numPages;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = PageActivity.this;
String pageURL = URL;
if (imageViews[position].getDrawable() == null) {
ImageFetcher imagefetcher = new ImageFetcher();
imagefetcher.execute(
pageURL + String.format("%02d", position+1) + ".gif",
String.valueOf(position+1));
}
((ViewPager) container).addView(imageViews[position], 0);
return imageViews[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
imageViews[position].removeCallbacks(null);
}
}
public class ImageFetcher extends AsyncTask<String, Integer, Drawable> {
int fillthisPos;
public Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) new URL(urls[0]).getContent();
fillthisPos = Integer.parseInt(urls[1]);
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
imageViews[fillthisPos].setImageDrawable(result);
result = null;
}
}
}
我正在尝试创建一个可以从给定URL加载图像的图像查看器。上面的代码使用
实现当我下载了一些图片时,应用程序崩溃了。我从DDMS / MAT检查了图像的位图没有被释放。这是因为我正在摧毁的观点并没有被GC收集,因为它们仍在某处被引用。
我想知道在这种情况下他们是否有某种方式明确释放内存?我尝试从代码中删除所有引用,但它仍然没有释放内存。
PS:请原谅我先放入代码,我试图将其移动,但格式化了。答案 0 :(得分:1)
您无需保留ImageFetcher
个任务数组。通过执行此操作,您将维护对已加载的drawable的引用。尝试从代码中删除数组。 AsyncTask
将运行完成,无需维护对它们的引用。