MessageCapturingHandler.java revision 89e3ffc66c5a05f188ff9748b48abebc247f664b
1/*
2 * Copyright (C) 2016 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.server.accessibility;
18
19import android.os.Handler;
20import android.os.Message;
21import android.util.Pair;
22
23import java.util.ArrayList;
24import java.util.List;
25
26/**
27 * Utility class to capture messages dispatched through a handler and control when they arrive
28 * at their target.
29 */
30public class MessageCapturingHandler extends Handler {
31    List<Pair<Message, Long>> timedMessages = new ArrayList<>();
32
33    Handler.Callback mCallback;
34
35    public MessageCapturingHandler(Handler.Callback callback) {
36        mCallback = callback;
37    }
38
39    @Override
40    public boolean sendMessageAtTime(Message message, long uptimeMillis) {
41        timedMessages.add(new Pair<>(Message.obtain(message), uptimeMillis));
42        return super.sendMessageAtTime(message, uptimeMillis);
43    }
44
45    public void sendOneMessage() {
46        Message message = timedMessages.remove(0).first;
47        removeMessages(message.what, message.obj);
48        mCallback.handleMessage(message);
49        removeStaleMessages();
50    }
51
52    public void sendAllMessages() {
53        while (!timedMessages.isEmpty()) {
54            sendOneMessage();
55        }
56    }
57
58    public void sendLastMessage() {
59        Message message = timedMessages.remove(timedMessages.size() - 1).first;
60        removeMessages(message.what, message.obj);
61        mCallback.handleMessage(message);
62        removeStaleMessages();
63    }
64
65    public boolean hasMessages() {
66        removeStaleMessages();
67        return !timedMessages.isEmpty();
68    }
69
70    private void removeStaleMessages() {
71        for (int i = 0; i < timedMessages.size(); i++) {
72            Message message = timedMessages.get(i).first;
73            if (!hasMessages(message.what, message.obj)) {
74                timedMessages.remove(i--);
75            }
76        }
77    }
78}
79