Android run a Task Periodically-ThrowExceptions

Exception or error:

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.

How to solve:

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

###

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

###

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

    }

Leave a Reply

Your email address will not be published. Required fields are marked *