Skip to content Skip to sidebar Skip to footer

How To Start A Different Activity With Some Delay After Pressing A Button In Android?

I want that a new activity should start with some delay on pressing a button. Is it possible to do that , and whats the procedure.

Solution 1:

Use a postDelayed() call with a runnable that launches your activity. An example code could be

//will care for all postsHandlermHandler=newHandler();

    //the button's onclick method
    onClick(...)
    {
        mHandler.postDelayed(mLaunchTask,MYDELAYTIME);
    }

    //will launch the activityprivateRunnablemLaunchTask=newRunnable() {
        publicvoidrun() {
            Intenti=newIntent(getApplicationContext(),MYACTIVITY.CLASS);
            startActivity(i);
        }
     };

Note that this lets the interface remain reactive. You should then care for removing the onclick listener from your button.

Solution 2:

Use This code

newHandler().postDelayed(newRunnable() {
        @Overridepublicvoidrun() {
            finalIntentmainIntent=newIntent(CurrentActivity.this, SecondActivity.class);
            LaunchActivity.this.startActivity(mainIntent);
            LaunchActivity.this.finish();
        }
    }, 4000);

Solution 3:

You could call a Runnable using the Handler postDelayed() method.

Here's an example (http://developer.android.com/resources/articles/timed-ui-updates.html):

privateHandlermHandler=newHandler();

...

OnClickListenermStartListener=newOnClickListener() {
   publicvoidonClick(View v) {
            mHandler.postDelayed(mUpdateTimeTask, 100);
   }
};

privateRunnablemUpdateTimeTask=newRunnable() {
   publicvoidrun() {
       // do what you need to do here after the delay
   }
};

Props to @mad for getting it right the first time around.

Solution 4:

You can use the method postDelayed(Runnable action, long delayMillis) of a View to add a Runnable to the message queue to be run after an (approximate) delay.

Solution 5:

Sometimes, u need to do it whenever your app process is killed or not. In that case you can not use handling runnable or messages inside your process. In this case your can just use AlarmManager to this. Hope this example helps anybody:

Intentintent=newIntent();
...

PendingIntentpendingIntent= PendingIntent.getActivity(<your context>, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManagermgr= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, <your delay>, pendingIntent);

Post a Comment for "How To Start A Different Activity With Some Delay After Pressing A Button In Android?"