如何改善我的Java代码以减少Android Studio上的内存垃圾?

时间:2019-03-24 18:51:02

标签: java android memory

我正在创建一个简单的应用,该应用看起来像带有移动backgroung图像的扫描仪,但开始变得不方便,当我检查android profiler时,我注意到它正在使用约400mb的内存,并且大部分来自图形和本机,我不知道为什么。也许我的代码中需要一些recyclerview或destroy方法来删除使用的内存。我该如何在当前代码中应用类似的内容?

A picture of my current android profiler

打包com.example.android.miulimaapp;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {
    View white;
    Animation downtoup;

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

        //Remove notification bar
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

        //MovingScanSquare
        white = findViewById(R.id.white);
        downtoup = AnimationUtils.loadAnimation(this, R.anim.downtoup);

        white.setVisibility(View.VISIBLE);
        downtoup = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, 1.1f,
                TranslateAnimation.RELATIVE_TO_PARENT, 0.f);
        downtoup.setDuration(2200);
        downtoup.setRepeatCount(-1);
        downtoup.setRepeatMode(Animation.REVERSE);
        downtoup.setInterpolator(new LinearInterpolator());
        white.setAnimation(downtoup);

        //movingscreen

        final ImageView backgroundOne =  findViewById(R.id.background_one);
        final ImageView backgroundTwo =  findViewById(R.id.background_two);

        final ValueAnimator animator = ValueAnimator.ofFloat(0.0f, -1.0f);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(2100L);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final float progress = (float) animation.getAnimatedValue();
                final float width = backgroundOne.getWidth();
                final float translationX = width * progress;
                backgroundOne.setTranslationX(translationX);
                backgroundTwo.setTranslationX(translationX + width);
            }
        });
        animator.start();
    }
}

1 个答案:

答案 0 :(得分:0)

检查背景图像的分辨率。如果分辨率过高,则降低分辨率。