How to lock Android screen via ADB?
Asked Answered
J

8

60

Is there a way to lock the Android screen via the ADB?

I find ways to lock the display in an apk, but I want to lock the screen from the PC via ADB, to simulate a display timeout, without having to wait for the timeout.

Is it possible to do this?

Thanks, Diane

Jordans answered 12/12, 2012 at 23:3 Comment(1)
lock/unlock is same as power off/on ? It works for me as power off/on.Parenthood
J
93

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?

Jordans answered 12/12, 2012 at 23:44 Comment(4)
It's great, I put it as a batch file on windows desktop and added a shortcut key to it.Primo
sadly it works as power off on cubietruck and just turns off the deviceSummersault
This is great. I had the same problem in reverse - the device I'm using goes to sleep, and doesn't have any hard keys, so I'd have to reset it all the time. With this, it's just like a wake-up (pressing the "power" button). Thanks.Irresolute
It powers off/on (same as lock/unlock?), but works for me in one device (kitkat), and fails in another (marshmellow).Parenthood
J
19

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
Jake answered 20/7, 2014 at 14:58 Comment(5)
Why are you even suggesting how to unlock - when the OP wants to Lock the device?Disremember
You are absolutely correct. I somehow missed this part. I've since altered the script to reflect the needed change. Thanks @DisrememberJake
touchscreen is not a command on my phone Motorola Razr it should just be "swipe" not "touchscreen swipe"Epanodos
It seems for Lollipop there isn't mScreenOn, though Display power state=OFF/ON does the work, so tmp="$(adb -s $udid shell dumpsys power | grep 'mScreenOn=\|state' | grep -oE '(true|false|ON|OFF)')" + if [ "$tmp" == 'false' ] || [ "$tmp" == 'OFF' ]; then {...}Braille
Why do you say "adb shell input keyevent 82" does not work on current versions? On Nexus 6 with Android 7 it is workingBiased
P
10

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
Peppers answered 7/6, 2014 at 5:0 Comment(0)
B
6

You've already found a solution, but I'll put this code here for reference anyway.

What you could do is to inject event to "press" the power button twice. If you don't know the status of the device (display on/off), check whether the screen is currently on or off and press the power button accordingly.

Here's a simple monkeyrunner script:

import re
from java.util import *
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = MonkeyRunner.waitForConnection()       # connect to a device
device.shell("input keyevent KEYCODE_POWER")    # turn screen off (or on?)
res = device.shell("dumpsys power")             # fetch power state
m = re.search(r'.*mPowerState=([0-9]+).*', res) # parse the string
if m and int(m.group(1)) == 0:                  # screen is off
  device.shell("input keyevent KEYCODE_POWER")  # turn the screen on
Burrus answered 13/3, 2013 at 13:50 Comment(4)
mPowerState might not be an int. On Samsung Galaxy SIII, the line is: mPowerState=SCREEN_BRIGHT_BIT SCREEN_ON_BITPavilion
@Jakub: Thanks for answering! Sorry it took me so long to notice <blush>. I work almost exclusively from Perl scripts using adb commands and some shell scripts. But I'm going to put this in my refs for power when I need to do more of this kind of stuff.Jordans
@Juuso: that is good to know, thanks. I work with test phones so it's good to know that one might show up differently.Jordans
Just to note that since Android 4.4W (API 20), there's been the constant KEYCODE_SLEEP, which takes care of one of the problems. "Sleep key. Puts the device to sleep. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already asleep"Dennie
B
5

In addition to the answers before, here's what I do to lock / unlock my screen using adb:

adb shell input keyevent 26 will lock the screen.
So, if you execute that command again, while the screen is turned off / locked, it will be turned on / unlocked.
adb shell input keyevent 26 will also unlock the screen (if the screen is locked).

Furthermore, I have also tested all commands, such as adb shell input keyevent number, and found out that adb shell input keyevent 3 also unlock the device.

I had also found out (by testing) that key 3 is the home button. So , if you have a physical home button (not the soft home button on the screen), you can also use this to unlock your device.

Baptiste answered 26/11, 2016 at 2:24 Comment(0)
C
1

For those using earlier versions of android (4.2+ at least), dumpsys power has a different output.
Instead of using mPowerState= as the answer given by @Jakub Czaplicki, I used mScreenOn=.

p = Runtime.getRuntime().exec("su", null, null);
OutputStream o = p.getOutputStream();
o.write(("dumpsys power").getBytes("ASCII"));
o.flush();
o.close();
p.waitFor();

boolean screenState;
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((res = in.readLine()) != null) dump += res;
screenState = dump.charAt( dump.indexOf("mScreenOn=") + 10 ) == 't';

screenState is true (screen on), or false (screen off).

Chetchetah answered 2/4, 2014 at 11:41 Comment(0)
H
1

You can use following command to trigger display ON. adb shell input keyevent POWER

I tried and am using in my project, Hope it will work for you.

And here is the ruby code I used:

def ScreenCheck()
system("adb shell dumpsys power > c:/interact.log")

File.open("C:\\interact.log").each do |line|
    if line[/mScreenOn/]
        if line.strip == "mScreenOn=true"
            p "Screen is On, Starting execution.."
        else
            p "Screen is Off, starting screen.."
            system("adb shell input keyevent = POWER")
            p "Starting execution.."
        end
    end
end
end
Hondo answered 1/2, 2016 at 7:15 Comment(0)
I
1

Here is a script to turn on/off the screen for every connected device including any pre-lollipop devices. I use this on my Jenkins server right before running any connected Android tests to make sure the devices are ready to go. Hope someone finds this useful!

#!/bin/sh

# Returns the power state of the screen 1 = on, 0 = off
getDisplayState() {
    state=$(adb -s $1 shell dumpsys power | grep mScreenOn= | grep -oE '(true|false)')

    # If we didn't get anything it might be a pre-lollipop device
    if [ "$state" = "" ]; then
        state=$(adb -s $1 shell dumpsys power | grep 'Display Power' | grep -oE '(ON|OFF)')
    fi

    if [ "$state" = "ON" ] || [ "$state" = "true" ]; then
        return 1;
    else
        return 0;
    fi
}

echo "Turning on screen on all connected devices..."

for device in `adb devices | grep device$ | cut -f1`
do
    echo -n "Found device: $device ... "

    getDisplayState $device
    state=$?

    # If the display is off, turn it on
    if [ $state -eq 0 ]; then
        echo "display was off, turning on"
        adb -s $device shell input keyevent 26
    else
        echo "display was on"
    fi

done
Impuissant answered 24/6, 2017 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.