Android懒加载图片时出现内存不足错误

4
我在这里找到了Fedor的代码(链接),并将其实现到了我的项目中。唯一的区别是我的应用程序没有列表视图,而是从服务器逐个访问1张图片。当活动启动时,我调用“DisplayImage(...)”来显示第一张图片。然后有两个按钮(上一个/下一个),当点击它们时,它们会调用“DisplayImage(...)”。
它可以正常工作一段时间,但之后我会收到“内存不足”错误。在他的代码顶部,他评论说你可能想使用SoftReference。我认为这会解决我的问题,对吗?我试过修改它以使用SoftReference,但图片从未加载。我以前从未使用过SoftReference,所以我想我可能漏掉了什么。如何修改该代码(ImageLoader)以解决我的OOM错误?是否有更好的方法在浏览图片时缓存它们?
更新: 以下是代码,以防您不想查看源文件中的其他文件。
package com.fedorvlasov.lazylist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();

    private File cacheDir;

    public ImageLoader(Context context){
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    final int stub_id=R.drawable.stub;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }    
    }

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }

    private Bitmap getBitmap(String url) 
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();

        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}

在我尝试实现SoftReference后,这是相同的类。我认为我做错了,因为加载后屏幕上没有显示图片。

package com.mycompany.myapp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, SoftReference<Bitmap>> cache=new HashMap<String, SoftReference<Bitmap>>();

    private File cacheDir;

    public ImageLoader(Context context){
        //Make the background thread low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyApp/Temp");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    final int stub_id = R.drawable.loading;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url)){
            imageView.setImageBitmap(null);
            System.gc();
            imageView.setImageBitmap(cache.get(url).get());
        } else {
            queuePhoto(url, activity, imageView);
            imageView.setImageBitmap(null);
            System.gc();
            imageView.setImageResource(stub_id);
        }    
    }

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }

    private SoftReference<Bitmap> getBitmap(String url) 
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);

        //from SD cache
        SoftReference<Bitmap> b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            SoftReference<Bitmap> bitmap=null;
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private SoftReference<Bitmap> decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=1024;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;

            return cache.get(BitmapFactory.decodeStream(new FileInputStream(f), null, o2));
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        SoftReference<Bitmap> bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        SoftReference<Bitmap> bitmap;
        ImageView imageView;
        public BitmapDisplayer(SoftReference<Bitmap> bmp, ImageView i){bitmap=bmp;imageView=i;}
        public void run()
        {
            if(bitmap!=null){
                imageView.setImageBitmap(null);
                System.gc();
                imageView.setImageBitmap(bitmap.get());
            } else {
                imageView.setImageBitmap(null);
                System.gc();
                imageView.setImageResource(stub_id);
            }
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();

        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}

指向压缩文件中的其他代码是没有帮助的。请在此处放置一小段代码片段。 - Aliostad
我更新了我的帖子,加入了ImageLoader类。他创建了一些其他的类,在这里被引用,但我猜你可以弄清楚它们的作用。我只需要修改这段代码来修复我的OOM错误。谢谢。 - Brian
@Brian:你能帮我解决这个问题吗?很紧急。 - skygeek
5个回答

7
通常,您的内存中图像缓存声明应该如下所示:

private static HashMap<String, SoftReference<Bitmap>> cache = 
    new HashMap<String, SoftReference<Bitmap>>();

请注意,您的OOM问题可能并不一定与位图缓存有关。请始终确保在Activity的onDestroy方法中停止/中断由图像加载器生成的线程,或在管理它的任何其他类的finalize中停止/中断该线程。
结合DDMS使用Eclipse Memory Analyzer工具分析应用程序的内存使用情况:http://www.eclipse.org/mat/

谢谢你的回复,Jeff。我已经按照你发布的方式更改了HashMap代码,这导致了代码中许多其他的变化。当我进行其他更改时,图片就无法在imageView中加载。我再次更新了原始帖子,展示了我现在的更改。如果你能看一下并指出我的错误,我将不胜感激。 - Brian
1
通常情况下,如果您花时间理解复制和粘贴到自己项目中的代码,将会使您的生活变得更加轻松。首先,缓存应该被声明为静态的,这样就只有一个实例。其次,decodeFile和getBitmap方法必须返回Bitmap,而不是SoftReference。在PhotoLoader.run()中缓存时,请在声明软引用的同时声明它:`Bitmap bmp=getBitmap(photoToLoad.url); cache.put(photoToLoad.url, new SoftReference(bmp));` - Jeff Gilfelt
2
好的,鉴于您的图像尺寸很大,您需要认真开始查看优化位图样本大小选项以在解码时(在decodeFile方法中)调用recycle()方法并在完成后显式地释放每个位图。在Android中为位图分配内存是一个棘手的问题,我可能没有资格提供建议。请在此网站上搜索类似的问题,这应该会给您一些有用的信息。 - Jeff Gilfelt
1
虽然使用SoftReference解决了OOM错误,但仍存在一些我无法解决的错误。在系统清理SoftReference后,它没有清理缓存。它清除了位图但没有清除URL。因此,我删除了我的SoftReference,然后使其每次仅存储少量图像在缓存中。这似乎很好地工作了,我也没有遇到任何OOM错误。现在我打字时,我意识到我可能也应该在String上使用SoftReference。那可能会解决我遇到的问题。哦,好吧。感谢你的帮助Jeff。 - Brian
Brian,你能解释一下限制缓存大小的想法或提供源代码吗? - user468311
显示剩余4条评论

0
为了解决使用Lazy Loader时的OOM问题,我手动调用垃圾回收(System.gc();)每次创建或销毁页面时(可能只做其中之一也可以),因为Android并不总是像它应该的那样频繁地调用它,并使用Fedor的clearCache方法:
if (ImageLoader.getImageCache() != null)
    ImageLoader.clearCache();

该函数已经存在,但除非您使用它,否则不会被任何东西调用。我在使用Lazy Load的第二个活动的onCreate中执行此操作。您也可以这样做:
@Override
public void onLowMemory() {
    super.onLowMemory();
    ImageLoader.clearCache();
}

这个函数似乎从来没有被调用过,但是考虑到你的图片有多大,你可能需要它。除非你有保持图片如此之大的理由,否则请考虑缩小图片。


我实际上并不想清除缓存。我添加了一个选项,允许用户这样做,但缓存并不是导致OOM的原因。我认为这更多是Android没有适当地进行垃圾回收的问题。在加载器本身中,我确实经常使用System.gc()方法。但如果你阅读文档,它并不会导致系统运行gc,它只是发送一个提示,表示现在可能是个好时机。至于缩小图像,我已经将它们缩小到我想要的尺寸了。我希望保持图片足够大,以适应即将推出的平板电脑。谢谢您的回复。 - Brian
1
@CameronW - 这就是为什么onLowMemory不会被调用的原因:“当整个系统的内存不足时,才会调用onLowMemory(),而不是当您的进程的内存不足时。每个应用程序都限制在固定数量的RAM上(例如,在Nexus One上为24 MB)。如果您使用了这24 MB,但系统仍有更多的RAM可用,则会出现OutOfMemoryError,但不会出现onLowMemory()。”- Romain Guy。因此,没有必要为应用程序专门覆盖此方法。 - Abhijit
此外,你真的不应该依赖于 System.gc();,实际上它可能并没有什么帮助。位图并不存储在 Dalvik(Java)端,而是存储在代码的本地 C 区域中,因此 System.gc() 无法触及它们。 - StackOverflowed

0

请考虑回收您为位图图像分配的内存

bitmap.recyle(); bitmap=null;

当您不再需要位图图像时,请调用此函数,这将释放一些内存。


0
我遇到了同样的问题,我使用了SoftReference来处理位图和URL,但是Dalvik VM似乎非常快地回收了SoftReference,导致我的ListView图片不停地闪烁。然后我尝试设置inPurgeable= true,结果出现了OutOfMemoryException,但是我的listview图片没有闪烁。

-1

在Android 2.1或更低版本中,您应该更改以下行。

cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyApp/Temp");

转换成这个

cacheDir = new File(context.getCacheDir(), "MyApp/Temp");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接