1 /* 2 * Copyright (C) 2019 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 package android.platform.test.rule; 17 18 import static android.platform.uiautomatorhelpers.DeviceHelpers.assertInvisible; 19 20 import android.os.RemoteException; 21 22 import androidx.annotation.NonNull; 23 import androidx.test.uiautomator.By; 24 import androidx.test.uiautomator.BySelector; 25 import androidx.test.uiautomator.UiDevice; 26 27 import com.android.systemui.Flags; 28 29 import org.junit.runner.Description; 30 31 import java.time.Duration; 32 33 /** This rule will unlock phone screen before a test case. */ 34 public class UnlockScreenRule extends TestWatcher { 35 36 protected static final BySelector KEYGUARD_ROOT_VIEW = 37 Flags.sceneContainer() 38 ? By.res("element:lockscreen") 39 : By.res("com.android.systemui", "keyguard_root_view"); 40 41 @Override starting(Description description)42 protected void starting(Description description) { 43 unlockScreen(getUiDevice()); 44 } 45 46 /** 47 * Unlocks the screen on the given device and asserts that the lock screen has disappeared. 48 * 49 * @param uiDevice the device to unlock the screen for. 50 */ unlockScreen(@onNull UiDevice uiDevice)51 public static void unlockScreen(@NonNull UiDevice uiDevice) { 52 try { 53 // Turn on the screen if necessary. 54 if (!uiDevice.isScreenOn()) { 55 uiDevice.wakeUp(); 56 } 57 58 BySelector screenLock; 59 screenLock = KEYGUARD_ROOT_VIEW; 60 61 if (uiDevice.hasObject(screenLock)) { 62 uiDevice.pressMenu(); 63 uiDevice.waitForIdle(); 64 assertInvisible(screenLock, /* timeout= */ Duration.ofSeconds(20)); 65 } 66 } catch (RemoteException e) { 67 throw new RuntimeException("Could not unlock device.", e); 68 } 69 } 70 } 71