1

我从开发者网站得到的是“如果在加载时动画的总大小超过了虚拟堆内存的值,就​​会出现这个错误”和解决方案使用BitmapFactory。我在下面的代码中试过:

现在,问题是,“是什么导致了这个错误?”

  1. 为动画加载图像时是否计算图像的尺寸。

    喜欢:如果我有 10 个图像尺寸( 1100 * 1100 )并为图像使用 ARGB_8888 模式。

  2. 图像大小(500KB、1MB 等)对于此错误也很重要。

  3. 或者两者都对此错误负责。

  4. 如果我在一个活动上使用的动画比我多change this Activity to another Activity,如何释放我在上一个活动中使用的所有内存AnimationDrawable

欢迎所有建议。谢谢

代码

public class AdActivity extends Activity {

ImageView iView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ad);
    
    iView = (ImageView) findViewById(R.id.iView);
    
    //iView.setBackgroundResource(R.drawable.anim); // ( 1 )

    try{ 
             //  (2)
        iView.setImageBitmap(decodeSampleBitmapFromResource(getResources(), R.drawable.anim, 100, 100));
        
        AnimationDrawable frameAnimation = (AnimationDrawable) iView.getBackground();
        frameAnimation.start();
    }
    catch(Exception e){
    }
}

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

public static Bitmap decodeSampleBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

}

两件事:

  1. 在我提到 (1) 的评论中,这是在 ImageView 中获取动画的简单方法,但在这种情况下,应用程序启动时使用的总大小约为 44MB。“完美运行”

  2. 我在尝试中提到 (2) 的地方,这是 Android 开发者网站在这里给出的解决方案。

我试过没有错误,运行应用程序时大小约为 11Mb,但动画未显示在 ImageView 中。

请告诉我我做错了什么?

4

2 回答 2

1

您可以通过 1) 在清单文件中通过 android:largeheap="true" 增加 dalvik 堆大小来解决您的错误

2)如果你重用你的解码图像,那么你需要实现 Lrucache

3) 每当您使用 decodeSampleBitmapFromResource() 解码任何图像时,它的引用都存储在本机堆中。它可以由 System.gc() 清除以回收内存,但我们不能依赖它,因为它由操作系统决定何时释放它。

4)如果你想清除本机堆,你应该在 NDK 中编写代码

于 2013-11-29T07:04:28.713 回答
0

你检查过 inSampleSize 的值吗?

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

您可以保存位图参考,并在onPause. 你只是设置了一个图像,你怎么能看到动画?请参阅AnimationDrawable。该动画由多帧组成。

于 2013-11-29T07:07:29.497 回答