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.PowerManager; 21 import android.support.annotation.VisibleForTesting; 22 23 /** WakeLock wrapper for testability */ 24 public interface WakeLock { 25 26 /** @see android.os.PowerManager.WakeLock#acquire() */ acquire()27 void acquire(); 28 29 /** @see android.os.PowerManager.WakeLock#release() */ release()30 void release(); 31 32 /** @see android.os.PowerManager.WakeLock#wrap(Runnable) */ wrap(Runnable r)33 Runnable wrap(Runnable r); 34 createPartial(Context context, String tag)35 static WakeLock createPartial(Context context, String tag) { 36 return wrap(createPartialInner(context, tag)); 37 } 38 39 @VisibleForTesting createPartialInner(Context context, String tag)40 static PowerManager.WakeLock createPartialInner(Context context, String tag) { 41 return context.getSystemService(PowerManager.class) 42 .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag); 43 } 44 wrapImpl(WakeLock w, Runnable r)45 static Runnable wrapImpl(WakeLock w, Runnable r) { 46 w.acquire(); 47 return () -> { 48 try { 49 r.run(); 50 } finally { 51 w.release(); 52 } 53 }; 54 } 55 56 static WakeLock wrap(final PowerManager.WakeLock inner) { 57 return new WakeLock() { 58 /** @see PowerManager.WakeLock#acquire() */ 59 public void acquire() { 60 inner.acquire(); 61 } 62 63 /** @see PowerManager.WakeLock#release() */ 64 public void release() { 65 inner.release(); 66 } 67 68 /** @see PowerManager.WakeLock#wrap(Runnable) */ 69 public Runnable wrap(Runnable runnable) { 70 return wrapImpl(this, runnable); 71 } 72 }; 73 } 74 }