2

I need to auto refresh data displayed in my Activity every second, I've used runnable, timer etc. These works perfectly but after a few seconds the UI is slow and sometimes not responsive. I've read about IntentService but I don't think it's a good idea to use infinite loops in an IntentService. Is there something I'm missing, please help.

AADProgramming
  • 6,077
  • 11
  • 38
  • 58
  • If the process of reloading data on the screen taking more than one second? Is it CPU intensive? If not you should easily be able to use a handler to post a delayed runnable and not effect the UI performance. – Adam W Aug 23 '16 at 19:56
  • I've checked and found that reloading data takes exactly one second and the process is not taking more than 5% cpu but the ui is not responsive at times. – Abhishek Purohit Aug 24 '16 at 07:09

2 Answers2

2

I'd do something like this.

private Handler mRepeatHandler;
private Runnable mRepeatRunnable;
private final static int UPDATE_INTERVAL = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     mRepeatHandler = new Handler();
     mRepeatRunnable = new Runnable() {
          @Override
          public void run() {
               //Do something awesome

               mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
          };

     mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
}

@Override
protected void onDestroy() {
    super.onDestroy();

    mRepeatHandler.removeCallbacks(mRepeatRunnable);
}
Adam W
  • 972
  • 9
  • 18
0

Maybe this could help:

private class WaitTimer extends TimerTask {
        @Override
        public void run() {
            //every 5 seconds
            if(millis % 5 == 0) {
                //Do your magic here
            }
            millis+=1
        }
}

And then in onCreate()

millis = 0;
timer = new Timer();
timer.schedule(new WaitTimer(), 0, 1000);
Gustavo Conde
  • 927
  • 12
  • 20