23

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.

Sultan Saadat
  • 2,268
  • 6
  • 28
  • 38

3 Answers3

25

You should use Handler and its postDelayed function. You can find example here: Repeat a task with a time delay?

Community
  • 1
  • 1
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • This 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) –  Dec 19 '16 at 12:39
12

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);
Rajesh.k
  • 2,327
  • 1
  • 16
  • 19
  • 1
    solution 1 (Handler) doesnt run periodically, but fires only once! (i didnt try solution 2) – Abdu Jun 15 '19 at 19:17
7

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();
        }

    }