本文介绍了被破坏时释放特定活动的记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动器Activity,该启动器在打开时会加载大位图并调整其背景大小.

I have a launcher Activity that load and resize big bitmap as it's background when it opens.

每当按下后退"按钮时,Activity就是destroyed.但是我认为内存还没有释放.

Whenever hit the back button, the Activity is destroyed. But I think the memory is not released yet.

当我打开应用程序时,点击后退"按钮,然后再次将其打开(重复),我会得到一个OutOfMemoryError.

When I open back the app, hit the back button and open it again (repeatedly), I will get a OutOfMemoryError.

对于这个新手问题,我感到抱歉,但我想知道每当Activitydestroyed时如何释放内存?

I am sorry for this newbie question but I am wondering how do I release the memory whenever an Activity is destroyed?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    //MARK - movingBackgroundImageView
    movingBackgroundImageView = (ImageView) findViewById(R.id.movingBackgroundImageView);
    movingBackgroundImageView.setColorFilter(Color.argb(255, 255, 255, 255));
    movingBackgroundImageView.setScaleType(ImageView.ScaleType.MATRIX);
    movingBackgroundImageView.setAlpha(0.28f);

    prepareBackgroundAnimation();
}

private void prepareBackgroundAnimation() {

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

    screenWidth = displaymetrics.widthPixels;
    screenHeight = displaymetrics.heightPixels;

    movingImageHeight = displaymetrics.heightPixels;
    movingImageWidth = 1920.0 / 1080.0 * movingImageHeight;

    bitmapImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.moving_background_image);
    scaledBitmap = bitmapImage.createScaledBitmap(bitmapImage, (int) movingImageWidth, (int) movingImageHeight, false);
    movingBackgroundImageView.setImageBitmap(scaledBitmap);

    backgroundImageInBeginning = true;

    movingBackgroundImageView.post(new Runnable() {
        @Override
        public void run() {
            movingBackgroundImageView.setImageMatrix(matrix);
            moveBackground();
        }
    });
}

我尝试将所有这些内容放入onDestroyed(),但问题仍然存在

I have tried to put all these in onDestroyed() but the problem persists

@Override
protected void onDestroy() {
    finish();
    bitmapImage = null;
    scaledBitmap = null;
    super.onDestroy();
    Runtime.getRuntime().gc();
    System.gc();
}

推荐答案

为此添加以下代码

@Override
protected void onDestroy() {
    //android.os.Process.killProcess(android.os.Process.myPid());

    super.onDestroy();
    if(scaledBitmap!=null)
            {
                scaledBitmap.recycle();
                scaledBitmap=null;
            }

     }

这篇关于被破坏时释放特定活动的记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 13:23