Android testing, avoiding screen lock during testing

Hello everybody,

If you run a pretty complicated tests which are working till battery dies you know, that it is a big problem when screen locks 🙂 Using setting you can set screen wait timeout to 2 hours. But what you need to do, if you need test to work 24 hours? Touch screen every 2 hours? 🙂 No!

Just use very simple snippet:

package com.your.testpackage;

import android.os.PowerManager;
import android.test.ActivityInstrumentationTestCase2;

public class YourCoolTestClass extends
ActivityInstrumentationTestCase2 {

protected static String TAG = “#########” + YourCoolTestClass.class.getName();
private PowerManager mPowerManager = null;
private PowerManager.WakeLock mWakeLock = null;

public YourCoolTestClass() throws Exception{
super(“com.your.application.package.root”, YourCoolActivity.class);
}

public void setUp() throws Exception {
// Get power manager
mPowerManager = (PowerManager) getActivity().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = this.mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
// Acquire the lock
mWakeLock.acquire();
}

public void testAllBatteryLifeLong() {
// TEST
}

@Override
public void tearDown() throws Exception {
try {
// Wake lock MUST be released to avoid lock leaks
if(mWakeLock != null && !mWakeLock.isHeld) {
mWakeLock.release();
}
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
}

Happy testing 24/7/365 without screen locking (:

Best regards,
Yahor