How to turn on and turn off screen with adb command?

46k views Asked by At

I am using KEYCODE_POWER to turn on and turn off my rooted phone. The bellow command is used in both case turn on and turn off the screen.

adb shell input keyevent KEYCODE_POWER

However, I want to use it in separated cases: turn on and turn off. I have two functions: turn on and turn off functions. If the screen is off and I call the turn on function, it will turn on the screen. if the screen is already turn on, the turn on function will not do anything. Otherwise, If the screen is on, I will call turn off function and it will turn off.

I tried to check the screen state but it does not work well. Actually, the screen state update is so slow comparison with processing of phone. I also use other way but these ways make the screen wakeup without sleep.

final Window win = getWindow();
    win.addFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON ); 

Second way:

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();
2

There are 2 answers

5
Vova On
adb shell input keyevent 26

26 - is the keyevent code power button on the device.

You can find more command by link : http://adbshell.com/commands

4
0xAliHn On

You can write a script to control turn ON/OFF of the screen. Here is the sample script code:

result="$(adb shell dumpsys input_method | grep -c "mScreenOn=true")"

if [ "$result" == 1 ]; then
    echo "Screen is already on."

else
    echo "Turning screen on."
    adb shell input keyevent 26
fi