-3

I am creating a New Android application

I d like to switch from one activity to another activity after a time interval, How can i do this?

Kindly guide me

  • possible duplicate of [How to put some delay in calling an activity from another activity?](http://stackoverflow.com/questions/7965494/how-to-put-some-delay-in-calling-an-activity-from-another-activity) – Apoorv Aug 25 '14 at 09:45

3 Answers3

1
new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app Next activity
                Intent i = new Intent(CurrentActivity.this, NextActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, TIME_OUT);
Deniz
  • 12,332
  • 10
  • 44
  • 62
0

There are numerous ways to do this.

You could use postDelayed(), however that is not advised since you cannot STOP it, or control it reliably, between various phases of activity lifecycle, to prevent for example wierd behaviour when the user exits the activity, before the delay has passed.

You would need some locks, or other mechanism.

Most proper approach would be to simply start a timer on the 1st activity onPostResume() which will start another activity after some delay.

TimerTask mStartActivityTask;
final Handler mHandler = new Handler();
Timer mTimer = new Timer();

@Override
private protected onPostResume() { // You can also use onResume() if you like

    mStartActivityTask = new TimerTask() {
            public void run() {
                    mHandler.post(new Runnable() {
                            public void run() {
                                startNewActivity(new Intent(MyClass.class));
                        }
               });
        }};

    // This will start the task with 10 seconds delay with no intervals.
    mTimer.schedule(mStartActivityTask, 100000, 0); 
 }

 private void startNewActivity(Intent i) {

     mTimer.cancel();             // To prevent multiple invocations
     startActivity(i);            // Start new activity
     // finish();                 // Optional, depending if you want to return here.

 }
Sven Rojek
  • 5,476
  • 2
  • 35
  • 57
Jitsu
  • 769
  • 3
  • 7
0

Try this code

        private Thread thread;
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        thread = new Thread(this);
        thread.start();
        }

        @Override
        public void run() {
            try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                    Intent userName = new Intent(this, UserNameActivity.class);
                    startActivity(userName);
        }
Dude
  • 173
  • 2
  • 4
  • 14