Android run a Task Periodically
50,581
Solution 1
You should use Handler
and its postDelayed
function. You can find example here: Repeat a task with a time delay?
Solution 2
You can use below android classes:
1.Handler
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//your code
handler.postDelayed(this,20000);
}
},20000);
2.AlarmManager
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(HomeActivity.this, Yourservice.class);
alarmIntent = PendingIntent.getService(HomeActivity.this, 0, intent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 600*1000, alarmIntent);
Solution 3
You can also do it by CountDownTimer
CountDownTimer countDownTimer;
public void usingCountDownTimer() {
countDownTimer = new CountDownTimer(Long.MAX_VALUE, 10000) {
// This is called after every 10 sec interval.
public void onTick(long millisUntilFinished) {
setUi("Using count down timer");
}
public void onFinish() {
start();
}
}.start();
}
and onPause()
@Override
protected void onPause() {
super.onPause();
try {
countDownTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
Author by
Sultan Saadat
Updated on July 09, 2022Comments
-
Sultan Saadat almost 2 years
I want to run a method periodically in an android activity which updates a certain field after x seconds. I know it can be done in timerTask but what is the best way to do it? Code samples would be helpful.
-
Admin over 7 yearsThis is not 100% correct. What if I close my activity and app? I want the task to run daily, regardless the app is opened or not (i.e. should be service)
-
Abdu almost 5 yearssolution 1 (Handler) doesnt run periodically, but fires only once! (i didnt try solution 2)