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.
Use This code
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
final Intent mainIntent = new Intent(CurrentActivity.this, SecondActivity.class);
LaunchActivity.this.startActivity(mainIntent);
LaunchActivity.this.finish();
}
}, 4000);
Use a postDelayed() call with a runnable that launches your activity. An example code could be
//will care for all posts
Handler mHandler = new Handler();
//the button's onclick method
onClick(...)
{
mHandler.postDelayed(mLaunchTask,MYDELAYTIME);
}
//will launch the activity
private Runnable mLaunchTask = new Runnable() {
public void run() {
Intent i = new Intent(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.
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:
Intent intent = new Intent();
...
PendingIntent pendingIntent = PendingIntent.getActivity(<your context>, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, <your delay>, pendingIntent);
try this piece of code
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// run AsyncTask here.
}
}, 3000);
You could call a Runnable using the Handler postDelayed() method.
Here's an example (http://developer.android.com/resources/articles/timed-ui-updates.html):
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// do what you need to do here after the delay
}
};
Props to @mad for getting it right the first time around.
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.