Finish an activity after a time period

Since you also want to show the countdown, I would recommend a CountDownTimer. This has methods to take action at each “tick” which can be an interval you set in the constructor. And it’s methods run on the UI Thread so you can easily update a TextView, etc…

In it’s onFinish() method you can call finish() for your Activity or do any other appropriate action.

See this answer for an example

Edit with more clear example

Here I have an inner-class which extends CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_xml);      
    // initialize Views, Animation, etc...

    // Initialize the CountDownClass
    timer = new MyCountDown(11000, 1000);
}

// inner class
private class MyCountDown extends CountDownTimer
{
    public MyCountDown(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        frameAnimation.start();
        start();            
    }

    @Override
    public void onFinish() {
        secs = 10;
       // I have an Intent you might not need one
        startActivity(intent);
        YourActivity.this.finish(); 
    }

    @Override
    public void onTick(long duration) {
        cd.setText(String.valueOf(secs));
        secs = secs - 1;            
    }   
}

Leave a Comment