为什么在闪屏在 Android 中完成动画之前重定向到下一个 activity?

Why redirect to next activity before flash screen finish its animation in Android?

我创建了一个 Android 应用程序。最近我为它添加了一个 SplashScreen。但是如果我 运行 没有重定向到主应用程序的应用程序,动画播放正常。但是当它被重定向到主 activity 时,启动画面根本看不到。它直接启动 main activity。有人可以解释一下原因吗?

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StartAnimations();


/* If comment these lines animations works fine, */
        Intent mainIntent = new Intent(SpalshScreenActivity.this,MainActivity.class);
        startActivity(mainIntent);
        finish();

    }


private void StartAnimations() {
    Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
    anim.reset();
    LinearLayout l=(LinearLayout) findViewById(R.id.lin_lay);
    l.clearAnimation();
    l.startAnimation(anim);

    anim = AnimationUtils.loadAnimation(this, R.anim.translate);
    anim.reset();
    ImageView iv = (ImageView) findViewById(R.id.logo);
    iv.clearAnimation();
    iv.startAnimation(anim);


}

我可以通过添加如下线程来避免这种行为。

Thread timer = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    Intent mainIntent = new Intent(SpalshScreenActivity.this, MainActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
            }
        };
        timer.start();

但我想知道这种行为的原因。

您可以使用 AnimationListener,在您的动画中实现下面的监听器,一旦动画完成,您就可以开始新的 activity

anim.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        Intent mainIntent = new Intent(SpalshScreenActivity.this, MainActivity.class);
        startActivity(mainIntent);
        finish();
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
});