2

I created two Activities "SplashActivity and AuthenticationActivity" When I start the app it loads the splash screen for 5 seconds and then it moves on to AuthenticationActivity. My problem is that when I run the app, it loads the splash screen, but within 5 seconds when I click the back button, SplashActivity exits, and immediately AuthenticationActivity appears in the foreground. Does anyone know how to make it so when I click the back button, my app exits?

Here's my code so far:

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();

}}
Amir Dora.
  • 2,831
  • 4
  • 40
  • 61
Rahul
  • 404
  • 4
  • 16

1 Answers1

7
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();
}

or you can use Handler also

  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);
 }