1 /* 2 * Copyright (C) 2017 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 17 package com.android.systemui.utils.os; 18 19 import android.os.Handler; 20 import android.os.Looper; 21 import android.os.Message; 22 23 import java.util.ArrayList; 24 25 /** 26 * A handler that allows control over when to dispatch messages and callbacks. 27 * 28 * WARNING: Because most Handler methods are final, the only thing this handler can intercept 29 * are sending messages and posting runnables, but *NOT* removing messages nor runnables. 30 * It also *CANNOT* intercept messages posted to the front of queue. 31 */ 32 public class FakeHandler extends Handler { 33 34 private Mode mMode = Mode.IMMEDIATE; 35 private ArrayList<Message> mQueuedMessages = new ArrayList<>(); 36 FakeHandler(Looper looper)37 public FakeHandler(Looper looper) { 38 super(looper); 39 } 40 41 @Override sendMessageAtTime(Message msg, long uptimeMillis)42 public boolean sendMessageAtTime(Message msg, long uptimeMillis) { 43 mQueuedMessages.add(msg); 44 if (mMode == Mode.IMMEDIATE) { 45 dispatchQueuedMessages(); 46 } 47 return true; 48 } 49 setMode(Mode mode)50 public void setMode(Mode mode) { 51 mMode = mode; 52 } 53 54 /** 55 * Dispatch any messages that have been queued on the calling thread. 56 */ dispatchQueuedMessages()57 public void dispatchQueuedMessages() { 58 ArrayList<Message> messages = new ArrayList<>(mQueuedMessages); 59 mQueuedMessages.clear(); 60 for (Message msg : messages) { 61 dispatchMessage(msg); 62 } 63 } 64 65 public enum Mode { 66 /** Messages are dispatched immediately on the calling thread. */ 67 IMMEDIATE, 68 /** Messages are queued until {@link #dispatchQueuedMessages()} is called. */ 69 QUEUEING, 70 } 71 } 72