我的 Java 代码在 Android 设备中执行速度非常慢。我想这是因为我在一个类上完成了这一切。我需要一些关于如何改进我的代码的建议,也许可以通过将其划分为不同的类来实现。你会怎么做?
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(3000L);
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();
}
}
最佳答案
将代码拆分为不同的类不会让您走得太远。如果不对其进行分析,就很难说出那里发生了什么。使用分析工具之一,VisualVM例如,这样做。
监视您的应用程序,找出哪一行代码花费了太多时间并尝试对其进行优化。
关于java - 改进 Java 代码,使其在 Android 上执行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55293538/