How to lock Android screen via ADB?
Solution 1:
Cool, I just found KEYCODE_POWER
which is 26.
so it works by sending:
adb shell input keyevent 26
which locks the screen if the screen is unlocked. If the screen is already locked, it wakes up the device.
My guess is that the only way to ensure that the screen is locked (off), is to unlock (we use keyevent 82 (menu), then lock it with the power button keyevent. Does anyone have any idea if this is true?
Solution 2:
Michael R. Hines gave the what is arguably the easiest solution. However, the following line is not useful in later versions of Android.
adb shell input keyevent 82 # unlock
I've updated the shell script using coordinates for the individual device I want to wake (Tablet). My tablet does not support orientation changes for lockscreen events, so the values always work as the lockscreen is always in landscape. Should you require orientation change detection, a simple if/then/else would suffice in picking the correct coordinates to use for the orientation.
#!/bin/bash
if [ "$(adb shell dumpsys power | grep mScreenOn= | grep -oE '(true|false)')" == false ] ; then
echo "Screen is off. Turning on."
adb shell input keyevent 26 # wakeup
adb shell input touchscreen swipe 930 380 1080 380 # unlock
echo "OK, should be on now."
else
echo "Screen is already on."
echo "Turning off."
adb shell input keyevent 26 # sleep
fi
Solution 3:
Here's the whole thing in one single bash script which checks if the screen is actually on or not and then wakes up and unlocks the screen in one shot:
if [ "$(adb shell dumpsys power | grep mScreenOn= | grep -oE '(true|false)')" == false ] ; then
echo "Screen is off. Turning on."
adb shell input keyevent 26 # wakeup
adb shell input keyevent 82 # unlock
echo "OK, should be on now."
else
echo "Screen is already on."
fi