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.util.wakelock; 18 19 import android.content.Context; 20 import android.os.Handler; 21 22 import javax.inject.Inject; 23 24 /** 25 * A wake lock that has a built in delay when releasing to give the framebuffer time to update. 26 */ 27 public class DelayedWakeLock implements WakeLock { 28 29 private static final String TO_STRING_PREFIX = "[DelayedWakeLock] "; 30 private static final long RELEASE_DELAY_MS = 100; 31 32 private final Handler mHandler; 33 private final WakeLock mInner; 34 DelayedWakeLock(Handler h, WakeLock inner)35 public DelayedWakeLock(Handler h, WakeLock inner) { 36 mHandler = h; 37 mInner = inner; 38 } 39 40 @Override acquire(String why)41 public void acquire(String why) { 42 mInner.acquire(why); 43 } 44 45 @Override release(String why)46 public void release(String why) { 47 mHandler.postDelayed(() -> mInner.release(why), RELEASE_DELAY_MS); 48 } 49 50 @Override wrap(Runnable r)51 public Runnable wrap(Runnable r) { 52 return WakeLock.wrapImpl(this, r); 53 } 54 55 @Override toString()56 public String toString() { 57 return TO_STRING_PREFIX + mInner; 58 } 59 60 /** 61 * An injectable builder for {@see DelayedWakeLock} that has the context already filled in. 62 */ 63 public static class Builder { 64 private final Context mContext; 65 private final WakeLockLogger mLogger; 66 private String mTag; 67 private Handler mHandler; 68 69 /** 70 * Constructor for DelayedWakeLock.Builder 71 */ 72 @Inject Builder(Context context, WakeLockLogger logger)73 public Builder(Context context, WakeLockLogger logger) { 74 mContext = context; 75 mLogger = logger; 76 } 77 78 /** 79 * Set the tag for the WakeLock. 80 */ setTag(String tag)81 public Builder setTag(String tag) { 82 mTag = tag; 83 84 return this; 85 } 86 87 /** 88 * Set the handler for the DelayedWakeLock. 89 */ setHandler(Handler handler)90 public Builder setHandler(Handler handler) { 91 mHandler = handler; 92 93 return this; 94 } 95 96 /** 97 * Build the DelayedWakeLock. 98 */ build()99 public DelayedWakeLock build() { 100 return new DelayedWakeLock(mHandler, WakeLock.createPartial(mContext, mLogger, mTag)); 101 } 102 } 103 } 104