Home | History | Annotate | Download | only in util
      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 
     17 package androidx.wear.widget.util;
     18 
     19 import android.content.Context;
     20 import android.os.PowerManager;
     21 import android.os.PowerManager.WakeLock;
     22 import android.support.test.InstrumentationRegistry;
     23 
     24 import org.junit.rules.TestRule;
     25 import org.junit.runner.Description;
     26 import org.junit.runners.model.Statement;
     27 
     28 /**
     29  * Rule which holds a wake lock for the duration of the test.
     30  */
     31 public class WakeLockRule implements TestRule {
     32     @SuppressWarnings("deprecation")
     33     private static final int WAKELOCK_FLAGS =
     34             PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
     35 
     36     @Override
     37     public Statement apply(final Statement statement, Description description) {
     38         return new Statement() {
     39             @Override
     40             public void evaluate() throws Throwable {
     41                 WakeLock wakeLock = createWakeLock();
     42                 wakeLock.acquire();
     43                 try {
     44                     statement.evaluate();
     45                 } finally {
     46                     wakeLock.release();
     47                 }
     48             }
     49         };
     50     }
     51 
     52     private WakeLock createWakeLock() {
     53         Context context = InstrumentationRegistry.getTargetContext();
     54         PowerManager power = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
     55         return power.newWakeLock(WAKELOCK_FLAGS, context.getPackageName());
     56     }
     57 }
     58