简体   繁体   中英

Unlock emulator screen using espresso

I'm developing my first android application and I was setting up the CI server. My espresso tests run fine on my machine but travis errors out with the following

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

It seems that I need to unlock the emulator screen before I run the tests. To do so I have to add a manifest to src/debug with the required permissions and then unlock the screen with:

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

The thing is I don't want to litter my activities with the above code wrapped in if blocks. Is there a way to unlock the screen from the espresso test itself?

My espresso test:

@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")));
    }
}

You can use the setUp() method in your Espresso Test like:

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM