How to turn on screen during unit test?
Asked Answered
W

3

5

I'm having a minor problem with running unit tests against a real device when testing activities.

The problem is that they fail when the screen is not turned on.

Is there an elegant solution to this problem? Except moving my arm slightly to the right and press the power button myself. I'm not interested in WakeLock or any other code that would go into the main application.

Whacky answered 25/11, 2011 at 8:12 Comment(0)
M
4

Can Settings|Applications|Development|Stay Awake help (that's on the phone)? It disables phone screen going to sleep

Matte answered 25/11, 2011 at 8:28 Comment(3)
That option is not available anymore. Even if it were it wouldn't be an option as I'm not looking to keep the screen on at all time. I was hoping for some parameter to pass that would turn on the screen when running a test.Whacky
Strange, I thought this option is available on all devices. On each of mines it's available... Sorry that it didn't help.Matte
At first I thought it was removed with 2.3. After some research it seems like the option is only missing on certain Samsung models, in this case the S2. Thanks for the input.Whacky
W
3

It was actually quite simple. All I had to do was to call getWindow on the Activity with some flags to turn the screen on and unlock the keyguard.

public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {

    private MyActivity mActivity;

    public MyActivityTest() {
        super("com.example.app", MyActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mActivity = getActivity();
    }

    public void testMyActivity() throws InterruptedException {
        mActivity.runOnUiThread(
                new Runnable() {
                    public void run() {
                        mActivity.getWindow().addFlags(
                                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | 
                                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
                    }
                }
                );
        // Start testing 
        ....
    }
}
Whacky answered 25/11, 2011 at 20:56 Comment(2)
Doesn't that require your app to request additional permissions, though? (I'd kinda hope it would! :)Subarctic
The problem with this solution is you have to do it on every test? I want a way I can turn the screen on on the build server one time from a pipeline step and then run all tests then turn it off.Richmal
P
0

For me following solution works:

...
@Before
fun prepare() {
    InstrumentationRegistry
       .getInstrumentation()
       .uiAutomation
       .executeShellCommand("input keyevent KEYCODE_WAKEUP")
}
...

No special activity is necessary.

Pukka answered 8/10, 2024 at 12:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.