Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn on screen during unit test?

Tags:

android

junit

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.

like image 715
rochdev Avatar asked Nov 25 '11 08:11

rochdev


2 Answers

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

like image 116
Alexander Kulyakhtin Avatar answered Oct 10 '22 21:10

Alexander Kulyakhtin


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 
        ....
    }
}
like image 3
rochdev Avatar answered Oct 10 '22 19:10

rochdev