Thursday, July 18, 2013

Android: Timer thread

  1. import java.util.*;
  2. Timer timer = new Timer();
  3. create subclass of TimerTask, eg.: class MyTask extends TimerTask { ... }
  4. add "public void run()" method in subclass
  5. timer.schedule(new MyTask(), 0, 30); // assume no delay and 30 millisec interval 
  6. timer.cancel(); // for cleanup. to start timer again, need to instantiate:  new Timer(); then schedule(...)
  7. if using "protected void onPause()" or onResume(), ensure that super.onPause(), etc is called. 
  8. if need to refresh View UI, then use postInvalidate() instead of invalidate(). else will have exception
Activity life cycle (to understand when to stop Timer to prevent waste of resources):


No comments: