当按下返回按钮时,启动画面退出并打开身份验证 Activity

While press back Button splash screen exits and opens Authentication Activity

我创建了两个活动“SplashActivity 和 AuthenticationActivity” 当我启动应用程序时,它会加载启动画面 5 秒钟,然后继续 AuthenticationActivity。我的问题是,当我 运行 应用程序时,它会加载初始屏幕,但在我单击后退按钮后 5 秒内,SplashActivity 退出,并且 AuthenticationActivity 立即出现在前台。 有谁知道如何在我单击后退按钮时退出我的应用程序?

到目前为止,这是我的代码:

public class SplashActivity extends Activity {

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

    Thread splashTimer = new Thread(){


        public void run(){
            try{
                sleep(5000);
                startActivity(new Intent(SplashActivity.this,AuthenticationActivity.class));
                finish();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                finish();
            }
        }

    };
    splashTimer.start();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    
}

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();

}}
Timer timer;
TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    initialize();
}

private void initialize()
{
    timer = new Timer();
    timerTask = new TimerTask()
    {
        @Override
        public void run()
        {
            //Start your activity here
        }
    };

    timer.schedule(timerTask,2500);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    timer.cancel();
}

或者您也可以使用 Handler

  Handler handler;
  Runnable runnable;

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

private void initialize()
{
   handler = new Handler();
  runnable = new Runnable()
            {
                @Override
                public void run()
                {
                    //start your activity here
                }
            };
   handler.postDelayed(runnable, 5000);
   }

 @Override
public void onBackPressed() {
    super.onBackPressed();
     handler.removeCallbacks(runnable);
 }