blob: 433bf5599b0f93368e79d5200565d0281d7bd49f [file] [log] [blame]
Joe Onorato9c1289c2009-08-17 11:03:03 -04001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import android.os.Handler;
20import android.os.Looper;
21import android.os.Message;
22import android.os.MessageQueue;
23import android.util.Log;
24
25import java.util.LinkedList;
26
27/**
28 * Queue of things to run on a looper thread. Items posted with {@link #post} will not
29 * be actually enqued on the handler until after the last one has run, to keep from
30 * starving the thread.
31 *
32 * This class is fifo.
33 */
34public class DeferredHandler {
35 private LinkedList<Runnable> mQueue = new LinkedList();
36 private MessageQueue mMessageQueue = Looper.myQueue();
37 private Impl mHandler = new Impl();
38
39 private class Impl extends Handler implements MessageQueue.IdleHandler {
40 public void handleMessage(Message msg) {
41 Runnable r;
42 synchronized (mQueue) {
43 r = mQueue.removeFirst();
44 }
45 r.run();
46 synchronized (mQueue) {
47 scheduleNextLocked();
48 }
49 }
50
51 public boolean queueIdle() {
52 handleMessage(null);
53 return false;
54 }
55 }
56
57 private class IdleRunnable implements Runnable {
58 Runnable mRunnable;
59
60 IdleRunnable(Runnable r) {
61 mRunnable = r;
62 }
63
64 public void run() {
65 mRunnable.run();
66 }
67 }
68
69 public DeferredHandler() {
70 }
71
72 /** Schedule runnable to run after everything that's on the queue right now. */
73 public void post(Runnable runnable) {
74 synchronized (mQueue) {
75 mQueue.add(runnable);
76 if (mQueue.size() == 1) {
77 scheduleNextLocked();
78 }
79 }
80 }
81
82 /** Schedule runnable to run when the queue goes idle. */
83 public void postIdle(final Runnable runnable) {
84 post(new IdleRunnable(runnable));
85 }
86
87 public void cancel() {
88 synchronized (mQueue) {
89 mQueue.clear();
90 }
91 }
92
93 void scheduleNextLocked() {
94 if (mQueue.size() > 0) {
95 Runnable peek = mQueue.getFirst();
96 if (peek instanceof IdleRunnable) {
97 mMessageQueue.addIdleHandler(mHandler);
98 } else {
99 mHandler.sendEmptyMessage(1);
100 }
101 }
102 }
103}
104