在android中加载大位图时出现OOM异常

时间:2013-01-09 09:22:12

标签: android

我试图在应用程序中显示大型位图,我继续获得OOM异常,

这是我使用的Imageloader类

 public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    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);

        fileCache=new FileCache(context);
    }

//    final int stub_id=R.drawable.stub;
    public void DisplayImage(String url,ImageView imageView)
    {
        imageViews.put(imageView, url);

//        Bitmap bitmap=createScaledBitmap(memoryCache.get(url), 100,100,0);
        Bitmap bitmap=memoryCache.get(url);
      //  Bitmap bitmaps=bitmap.createScaledBitmap(bitmap, 0, 100, 100);

        if(bitmap!=null)
        {
            imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));

            System.gc();
//            bitmap.recycle();
//            bitmap=null;
//            imageView.setImageBitmap(getRoundedCornerBitmap( bitmap, 10,70,70));
//            imageView.setImageBitmap(bitmap);
//            Log.v("first", "first");
        }
        else
        {
            queuePhoto(url, imageView);
//            Log.v("second", "second");

        }    
    }

    private Bitmap createScaledBitmap(Bitmap bitmap, int i, int j, int k) {
        // TODO Auto-generated method stub
        return null;
    }

    private void queuePhoto(String url, 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();
    }

   public Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);

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

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }//Lalit



    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1=new FileInputStream(f);
            BitmapFactory.decodeStream(stream1,null,o);
            stream1.close();

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=Wall.width;
            final int REQUIRED_SIZE1=Wall.height;
            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;
            FileInputStream stream2=new FileInputStream(f);
            Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        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);
                        memoryCache.put(photoToLoad.url, bmp);
                        String tag=imageViews.get(photoToLoad.imageView);
                        if(tag!=null && 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.setBackgroundDrawable(new BitmapDrawable(bitmap));

        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels,int width,int height) {

        Bitmap output = Bitmap.createBitmap(width,height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

我的Memorycache类

public class MemoryCache {

    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes

    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }

    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }

    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }

    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }

    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }

    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }

    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

这是logcat输出------------&gt;

01-09 12:40:38.940: E/dalvikvm-heap(18736): 1123536-byte external allocation too large for this process.
    01-09 12:40:38.979: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:38.979: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4297K/8967K, external 22504K/23758K, paused 29ms
    01-09 12:40:38.979: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.002: I/MemoryCache(18736): cache size=5691144 length=7
    01-09 12:40:39.112: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 89K, 53% free 4272K/8967K, external 21905K/22856K, paused 42ms
    01-09 12:40:39.127: E/dalvikvm-heap(18736): 2457600-byte external allocation too large for this process.
    01-09 12:40:39.167: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:39.167: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4272K/8967K, external 21905K/22856K, paused 28ms
    01-09 12:40:39.167: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.206: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 2K, 53% free 4270K/8967K, external 20808K/22856K, paused 38ms
    01-09 12:40:39.252: I/MemoryCache(18736): cache size=8148744 length=8
    01-09 12:40:39.323: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 148K, 53% free 4253K/8967K, external 23218K/25256K, paused 42ms
    01-09 12:40:39.331: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process.
    01-09 12:40:39.370: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:39.370: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4253K/8967K, external 23218K/25256K, paused 28ms
    01-09 12:40:39.377: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.409: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 1K, 53% free 4251K/8967K, external 23208K/25256K, paused 38ms
    01-09 12:40:39.424: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process.
    01-09 12:40:39.463: E/GraphicsJNI(18736): VM won't let us allocate 960000 bytes
    01-09 12:40:39.463: D/dalvikvm(18736): GC_FOR_MALLOC freed 0K, 53% free 4251K/8967K, external 23208K/25256K, paused 28ms
    01-09 12:40:39.463: D/skia(18736): --- decoder->decode returned false
    01-09 12:40:39.463: W/dalvikvm(18736): threadid=16: thread exiting with uncaught exception (group=0x40018560)
    01-09 12:40:39.471: E/AndroidRuntime(18736): FATAL EXCEPTION: Thread-26
    01-09 12:40:39.471: E/AndroidRuntime(18736): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader.decodeFile(ImageLoader.java:190)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader.getBitmap(ImageLoader.java:100)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader$PhotosLoader.run(ImageLoader.java:257)
    01-09 12:40:39.471: W/ActivityManager(1320):   Force finishing activity com.stellent.beerbro/.Wall

我正在从Facebook图形api加载数据,我正在获取Firstpage数据,我一次显示整个数据。我认为这会使内存增加很多。 那么,如何处理大量数据。 请帮忙

1 个答案:

答案 0 :(得分:0)

您应该使用inJustDecodeBounds解码位图的大小而不将其加载到内存中。 ATM,如果您尝试加载大型位图,则在检查它是否在缓存的大小范围内之前创建它。

您不应强制使用GC,尤其是因为它是异步运行而system.gc强制它是同步的。位图不会直接加载到Java堆上,因此从缓存中传出的任何内容都应该被回收。最后不要保留对位图的引用。

总的来说,我会使用LRUCache而不是你自己的缓存。

最后,作为偏见,我会建议像enter link description here那样将图像缓存到磁盘并使用LRUCache进行表演。