Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. public class TimerLiveData extends LiveData<Long> {
  2. private static final long SECOND_AS_MILLI = 1000;
  3. private Handler handler;
  4. private Runnable runnable;
  5. private long secondsCount;
  6. private long secondsAtDeactivation;
  7.  
  8. public TimerLiveData() {
  9. handler = new Handler();
  10. runnable = new Runnable() {
  11. @Override
  12. public void run() {
  13. setValue(++secondsCount);
  14. handler.postDelayed(this,SECOND_AS_MILLI);
  15. }
  16. };
  17. }
  18.  
  19. @Override
  20. protected void onActive() {
  21. super.onActive();
  22. if(secondsAtDeactivation>0) //counts the time passed while inactive
  23. secondsCount += (System.currentTimeMillis() / SECOND_AS_MILLI - secondsAtDeactivation);
  24. handler.post(runnable);
  25. }
  26.  
  27. @Override
  28. protected void onInactive() {
  29. super.onInactive();
  30. handler.removeCallbacks(runnable);
  31. secondsAtDeactivation = System.currentTimeMillis() / SECOND_AS_MILLI;
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement