Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. public class UiLoop {
  2.  
  3. private Handler h;
  4. private AtomicBoolean breakLoop;
  5.  
  6. @UiThread
  7. public UiLoop() {
  8.  
  9. if (Looper.myLooper() != Looper.getMainLooper()) {
  10. throw new RuntimeException("Not called on ui thread!");
  11. }
  12.  
  13. h = new Handler();
  14. breakLoop = new AtomicBoolean(false);
  15. }
  16.  
  17. /**
  18. * Break out of the loop on the next iteration.
  19. */
  20. public void breakLoop() {
  21. this.breakLoop.set(true);
  22. }
  23.  
  24.  
  25. /**
  26. * @param workers A Deque of runnables to execute sequentially.
  27. * @param delay The delay between executing the runnables. This is excluding the time it
  28. * takes for the runnable to complete.
  29. */
  30. @UiThread
  31. public void loop(Deque<Runnable> workers, int delay) {
  32.  
  33. if (Looper.myLooper() != Looper.getMainLooper()) {
  34. throw new RuntimeException("Not called on ui thread!");
  35. }
  36.  
  37. if (workers.isEmpty()) return;
  38.  
  39. if (breakLoop.get()) return;
  40.  
  41. final Runnable first = workers.removeFirst();
  42. h.post(first);
  43. workers.addLast(first);
  44. h.postDelayed(() -> loop(workers, delay), delay);
  45.  
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement