1 /* 2 * Copyright 2018 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 androidx.core.os; 18 19 import android.os.Handler; 20 import android.os.Message; 21 22 import androidx.annotation.NonNull; 23 import androidx.annotation.Nullable; 24 25 /** 26 * Helper for accessing features in {@link Handler}. 27 */ 28 public final class HandlerCompat { 29 /** 30 * Causes the Runnable r to be added to the message queue, to be run 31 * after the specified amount of time elapses. 32 * The runnable will be run on the thread to which this handler 33 * is attached. 34 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b> 35 * Time spent in deep sleep will add an additional delay to execution. 36 * 37 * @param r The Runnable that will be executed. 38 * @param token An instance which can be used to cancel {@code r} via 39 * {@link Handler#removeCallbacksAndMessages}. 40 * @param delayMillis The delay (in milliseconds) until the Runnable 41 * will be executed. 42 * 43 * @return Returns true if the Runnable was successfully placed in to the 44 * message queue. Returns false on failure, usually because the 45 * looper processing the message queue is exiting. Note that a 46 * result of true does not mean the Runnable will be processed -- 47 * if the looper is quit before the delivery time of the message 48 * occurs then the message will be dropped. 49 * 50 * @see Handler#postDelayed(Runnable, Object, long) 51 */ 52 public static boolean postDelayed(@NonNull Handler handler, @NonNull Runnable r, 53 @Nullable Object token, long delayMillis) { 54 if (BuildCompat.isAtLeastP()) { 55 return handler.postDelayed(r, token, delayMillis); 56 } 57 58 Message message = Message.obtain(handler, r); 59 message.obj = token; 60 return handler.sendMessageDelayed(message, delayMillis); 61 } 62 63 private HandlerCompat() { 64 } 65 } 66