Android:BitmapFactory.decodeStream OutOfMemoryException - SoftReference 是解决方案吗?

标签 android exception out-of-memory soft-references bitmapfactory

我遇到了 OutOfMemoryException:

E/AndroidRuntime( 3013): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
E/AndroidRuntime( 3013):        at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
E/AndroidRuntime( 3013):        at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:375)
E/AndroidRuntime( 3013):        at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:394)

在下面的函数中:

static Bitmap downloadBitmap(String url)
    {
        final HttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        try 
        {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();

            // Check HTTP Status code
            if (statusCode != HttpStatus.SC_OK)
            { 
                debugPrint("ImageDownloader StatusCode Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }
            else;


            final HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                InputStream inputStream = null;
                try
                {
                    inputStream = entity.getContent(); 
                    if( inputStream == null)
                    {
                        debugPrint("ImageDownloader::downloadBitmap() - INPUTSTREAM = NULL!!!!!!");
                    }
                    else;



                    // THIS LINE IS GIVING THE ERROR
                    final Bitmap bitmap = BitmapFactory.decodeStream( new FlushedInputStream(inputStream));

                    if( bitmap == null)
                    {
                        debugPrint("LocrPhoto::downloadBitmap() - about to return BITMAP =NULL!!!!!!");
                    }
                    else;

                    return bitmap;
                }
                catch (Exception e)
                {
                    // Could provide a more explicit error message for IOException or IllegalStateException
                    getRequest.abort();
                    debugPrint("LocrPhoto::downloadBitmap() Error while decoding bitmap from " + url + "\n"+ e.toString());
                }
                finally
                {
                    if (inputStream != null)
                    {
                        inputStream.close();  
                    }
                    entity.consumeContent();
                }
            }
            else
            {
                debugPrint("LocrPhoto::downloadBitmap("+url+") - entity = NULL!!!!!");
            }
        }
        catch (Exception e)
        {
            // Could provide a more explicit error message for IOException or IllegalStateException
            //getRequest.abort();
            debugPrint("LocrPhoto::downloadBitmap() Error while retrieving bitmap from " + url + "\n"+ e.toString());
        }
        finally
        {
            if (client != null)
            {
                // CLOSE CONNECTION
            }
        }
        debugPrint("LocrPhoto::downloadBitmap("+url+") - returning NULL at end of function");
        return null;
    }

FlushedInputStream(虽然我在添加这段代码之前得到了错误):

// A Class to hopefully avoid the BitmapFactory.decodeStream() returning null bug
    //      http://code.google.com/p/android/issues/detail?id=6066
    static class FlushedInputStream extends FilterInputStream {
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                      int byt = read();
                      if (byt < 0) {
                          break;  // we reached EOF
                      } else {
                          bytesSkipped = 1; // we read one byte
                      }
               }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }

基本上,我有一个下载图像的 Activity ,将它们放置在框架布局中,然后淡入淡出帧以进行幻灯片放映。 framelayout 有两个 imageview child 。

我看到有人说 SoftReference 被用来防止 OOMExceptions,但我不明白如何将其应用于我的代码以(希望)防止此错误。

谁能解释一下这是如何实现的?

最佳答案

我正在处理与您相同的问题,我发现问题是 BitmapFactory.decodeStream 的内存消耗(如日志所述)。您需要做的是在调用 BitmapFactory.decodeStream 之前缩放您的位图,您可以找到一篇非常好的文章来解决您的问题!

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

希望对您有所帮助!

关于Android:BitmapFactory.decodeStream OutOfMemoryException - SoftReference 是解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834516/

相关文章:

java - 如何在 PIE 下使用私有(private)创建者(如 EGLContext)创建对象?

java - 如何让我的 Android 应用程序生成随机数?

python - 是否有可能捕获 python 中 try block 中引发的所有警告?

java - 线程 "AWT-EventQueue-0"java.lang.OutOfMemoryError : PermGen space 中的 xception

android - 将 cordova datepicker 与 ng-cordova 一起使用,promise "then"没有按预期执行。在安卓上

android - SyncAdapter 替代品

delphi - 应用程序定义的异常 - 不知道出了什么问题

java - 当代码抛出很多异常并且句柄相同时,哪个选择更好?

Java GC 奇怪的行为还是内存泄漏?

c - 我的 C 程序在 Dev C++ 中运行,但在另一个编译器中出现段错误