EDIT: Updated description and error message and added some images. Still have this problem.
I have a strange error that occur many times when running espresso tests. Af
To avoid this, let your device stay awake. There is an option in the developer options of the device.
You could use com.android.ddmlib and a gradle task to change the device settings via adb for every build run and every device you are testing on.
import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.CollectingOutputReceiver
import com.android.ddmlib.IDevice
import com.android.ddmlib.NullOutputReceiver
task stayAwake {
description = "Activate the Stay Awake settings in the developer options."
group = "Device Setup"
AndroidDebugBridge.initIfNeeded(false)
def bridge = AndroidDebugBridge.createBridge(android.adbExecutable.path, false)
doLast {
bridge.devices.each {
it.executeShellCommand("settings put global stay_on_while_plugged_in 3", NullOutputReceiver.receiver)
println "Device ${it} will stay awake."
}
}
}
In addition you can activate the screen with another gradle task. (precondition is that no PIN or unlock pattern is set)
IDevice.metaClass.inputKeyEventByShell {
delegate.executeShellCommand("input keyevent ${it}", NullOutputReceiver.receiver)
}
IDevice.metaClass.inputSwipeByShell {
delegate.executeShellCommand("input swipe ${it}", NullOutputReceiver.receiver)
}
task unlockScreen {
description = "Activate screen and unlock device."
group = "Device Setup"
AndroidDebugBridge.initIfNeeded(false)
def bridge = AndroidDebugBridge.createBridge(android.adbExecutable.path, false)
doLast {
bridge.devices.each {
def receiver = CollectingOutputReceiver.newInstance()
it.executeShellCommand("dumpsys power | grep \"mHolding\"", receiver)
def displaySuspendFalse = receiver.getOutput().find("mHoldingDisplaySuspendBlocker=false")
def wakelockSuspendFalse = receiver.getOutput().find("mHoldingWakeLockSuspendBlocker")
if (displaySuspendFalse || wakelockSuspendFalse) {
it.inputKeyEventByShell('26') //power keyevent
println "Screen of device $it activated & unlocked."
}
it.inputSwipeByShell('100 500 100 1450 100') //swipe action
}
}
}
Let these tasks run before your gradle task responsible for the UI tests.
This way no additional code in your tests is required to activate the devices and keeping them alive.