android - "Bitmap size exceeds VM budget"虽然功能在Android中进行了优化

标签 android memory bitmap

我知道,您可以找到数百个关于这个特殊主题的问题,但我已经阅读了其中的大部分,但它们没有帮助。这是堆栈跟踪:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:573)
at PACKAGE.MyApp.getPhoto(MyApp.java:191)
at PACKAGE.MyApp.getEntries(MyApp.java:149)
at PACKAGE.AlarmSetup.createNotifications(AlarmSetup.java:48)
at PACKAGE.AlarmSetup.onHandleIntent(AlarmSetup.java:30)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.os.HandlerThread.run(HandlerThread.java:60)

虽然我在 Stack Overflow 上阅读了很多问题后优化了我的 Java 函数(至少我认为是这样),但还是抛出了这个异常。这是我的代码:

public Bitmap getContactPhoto(String lookup_key) {
    Uri lookUpUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup_key);
    Uri contentUri = ContactsContract.Contacts.lookupContact(ctx.getContentResolver(), lookUpUri);
    try {
        final int REQUIRED_SIZE = 144;
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true; // first get only the size of the image
        BitmapFactory.decodeStream(ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(), contentUri), null, o);
        int scale = 1;
        while ((o.outWidth/scale/2) >= REQUIRED_SIZE && (o.outHeight/scale/2) >= REQUIRED_SIZE) {
            scale *= 2;
        }
        BitmapFactory.Options oScaled = new BitmapFactory.Options();
        oScaled.inSampleSize = scale; // decode with calculated sample size now
        oScaled.inPurgeable = true; // prevent OutOfMemory
        oScaled.inInputShareable = true; // prevent OutOfMemory
        return BitmapFactory.decodeStream(ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(), contentUri), null, oScaled);
    }
    catch (Exception e) {
        return null;
    }
}

你能帮帮我吗?我变得绝望,尝试了很多改进。提前致谢!

最佳答案

问题可能不在这段代码中。也许您创建了很多无法进行垃圾回收的位图实例。尝试使用 MAT(Memory Analysis for Android Applications)检查是否存在此类实例。

关于android - "Bitmap size exceeds VM budget"虽然功能在Android中进行了优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12240686/

相关文章:

java - 将多个 Android 传感器与辅助类相结合

android - 来自 RSS 提要的自动推送通知

c# - UWP Windows 10 应用程序内存在导航时增加

c - glClear 函数 : Question about the parameters

android - 如何在按钮上显示多行文本

php - AsyncTask异常RuntimeException

objective-c - 从同一个方法中调用一个方法会造成内存泄漏吗?

android - 如何在不使用 mask 的情况下创建拼图 block ?

c# - 替换位图/图像中特定颜色的有效方法

java - 将位图设置为 TextView 的背景 - Android