java - 改进 Java 代码以在 Android 上更快地执行
问题描述
我的 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)来执行此操作。
监视您的应用程序,找出哪一行代码花费了太多时间并尝试对其进行优化。
推荐阅读
- android - REST API 在 Postman 中给出了正确的响应,但给出了 Volley ServerError
- xml - 如何将 QML 之类的声明性语言解析为 QWidgets .ui XML 格式代码?
- git - 本地网络中的源代码控制
- database - Aerospike 集群配置
- javascript - 如何将 CJS 模块要求到本机 Node 中的 ES6 模块中?
- php - 如何在 wordpress 上创建 elementor 的小部件类别
- c - Why does my code print out some garbage from my array?
- python - 如何在 Pygame 中获取精灵的位置?
- symfony - 从 Symofny 中的数组中检索数据
- android - 如何解决“Manifest merge failed : Attribute application@appComponentFactory”的错误