使用浓缩咖啡解锁模拟器屏幕

Unlock emulator screen using espresso

我正在开发我的第一个 android 应用程序并且我正在设置 CI 服务器。我的浓缩咖啡在我的机器上测试 运行 正常,但 travis 出现以下错误

java.lang.RuntimeException: Waited for the root of the view hierarchy to have window focus and not be requesting layout for over 10 seconds.

看来我需要在 运行 测试之前解锁模拟器屏幕。为此,我必须使用所需权限向 src/debug 添加清单,然后使用以下命令解锁屏幕:

KeyguardManager mKeyGuardManager = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mLock = mKeyGuardManager.newKeyguardLock(name);
mLock.disableKeyguard();

问题是我不想用 if 块中包含的上述代码乱丢我的活动。有没有办法从浓缩咖啡测试本身解锁屏幕?

我的浓缩咖啡测试:

@RunWith(AndroidJUnit4.class)
public class EspressoSetupTest {

    @Rule
    public final ActivityTestRule<WelcomeActivity> activity =
            new ActivityTestRule<>(WelcomeActivity.class, true, true);

    @Test
    public void launchTest() {
        onView(withId(R.id.welcome_textView_hello))
                .perform(click())
                .check(matches(withText("RetroLambda is working")));
    }
}

您可以在 Espresso 测试中使用 setUp() 方法,例如:

@UiThreadTest
@Before
public void setUp() throws Exception {
   final Activity activity = mActivityRule.getActivity();
    mActivityRule.runOnUiThread(new Runnable() {
        @Override
        public void run() {
          KeyguardManager mKG = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
          KeyguardManager.KeyguardLock mLock = mKG.newKeyguardLock(KEYGUARD_SERVICE);
          mLock.disableKeyguard();

        //turn the screen on
         activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
          }
      });
}

src/debug/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
</manifest>