How do I keep my screen unlocked during USB debugging?
Asked Answered
F

20

91

Android OS2.2 used to have an option under Settings/Applications/Development to disable screen lock during USB debugging. After upgrading my Samsung Galaxy S to OS2.3.3 this option disappeared and it's VERY frustrating to keep unlocking my phone while debugging.

Has this option moved or is there another way to do it? (I hate when useful options are removed for no reason!)

Frederiksberg answered 12/1, 2012 at 19:17 Comment(5)
Too bad there is no good answer to this question... Probably because it is not possible (anymore). You should raise an issue for google android team.Fijian
And cyanogen, particularly for adb over TCP option.Dumpish
Try StayAwake, it keeps your screen awake if plugged into AC/USB.Giza
In case this is still useful to anybody... Do you have the "Developer options" menu under Settings? If not, you may have to enable it. Go to Settings > About phone and quickly touch several times (about 10 times) on "Build number". You'll see a toast saying "You're a developer now". Then you'll find the stay awake option under "Developer options".Nellie
I've made an open-source app to set/unset the stay-awake setting for you sa you connect/disconnect ADB, it is available ADB-Stay-AwakeEsplanade
I
64

There are multiple options, many of which have horrible (subjective) side effects. I'll list what I've found and what side effects I could think of.

I'm lazy, possibly like many others, and I don't like to keep on eye out for something unneccessarily. This means that the "Oh, I'll just turn this on while I'm working and then turn it off when finished" option is not a viable one. You will forget it and you will experience any of the sideeffects listed below eventually.

TL;DR

FLAG_KEEP_SCREEN_ON with a Debug.isDebuggerConnected() guard FTW! Stay awake when charging, Screen timeout and wake-lock are non-viable options if you just want to debug.
There's also an advantage of this solution working from API 1 AND wifi debugging!

Settings > Developer Options > Stay awake when charging

Official request: https://issuetracker.google.com/issues/37094654 for ADB debugging option.

Burn in: There should be a huge red flag anyone turning this on. It says "while charging" not "while debugging". Which means that even if your phone is plugged in to the mains it will keep on. This is especially bad if you have an AMOLED screen (e.g. Galaxy S series) which burns stuff in. I had this option on for a few weeks and now I have a permanent portrait status bar...

Notifications: Even if you use low brightness and don't forget to turn your screen off every time you put the phone down some apps wake your screen up if you get just a simple notification which leads to keeping it on most of the time while plugged in.

Night light: If you charge your phone at night, and forget to turn it screen down, you get a free night light that automatically turns on when you get a notification at night or the devices wakes up for a moment for whatever reason.

Security: If you just leave your screen on while charging and you're needed quickly for something at work, the first thing won't be "Ah, let me lock my phone first" and you may expose your dirty secrets if you accidentally left it on. Let me note that if you're working in an environment where you can't trust your collegaues, I would reconsider that employment.

Settings > Display > Screen Timeout

This is very risky if you have lot of apps that give you notifications. Especially if you have some spammers (Facebook, Family Guy or even GMail if you get a lot of mails).

Burn in: The risk is high with this as well. Now you don't even restrict it to "being on the wire" so it will just stay on whenever you forget to turn it off explicity or get a notification.

Battery drain: If you get one the screen will be on for the specified amount of time, draining your battery. And it will be on because sometimes you forget to turn it off, or just get a notification.

Hotpocket: if you get a notification while the phone is in your pocket the illumination from the screen and the confined space will heat your pockets and you may even get burned.

Pocket dial: if your screen turns on while the phone is in your pocket the risk of a pocket dial with increase with every second. Nowadays this is less likely though, because the Phone app is usually well hidden, but my pocket likes to change the date very often or read my emails.

Security: imagine you're in a public place and your phone is on the table, your friends will most likely abuse your unlocked screen if you turn around for long enough to talk to someone or take a quick break. Especially if they're inebriated. Obviously shorter timeouts decrease this risk.

Using a wake-lock

Permission: You'll need to add a possibly unnecessary android.permission.WAKE_LOCK permission to your app (luckily should be easy to add for only debug variants thanks to Manifest Merger in the Gradle Plugin).

Coding: You'll also need to manage releasing the lock yourself and maybe need to create a Service just for this. I'd like to note here that I've yet to use this feature in Android.

Useless: It also doesn't really help to keep the screen on, since it only keeps the CPU awake. See documentation.

FLAG_KEEP_SCREEN_ON while a Debugger is attached

If you read the documentation for this one, you'll find a very close approximation to your problem.

Coding: the only downside I can think of here is that you need to modify some code, but it's extremely simple (assuming you have a BaseActivity that all your other activities extend):

@Override protected void onResume() {
    super.onResume();
    if (BuildConfig.DEBUG) { // don't even consider it otherwise
        if (Debug.isDebuggerConnected()) {
            Log.d("SCREEN", "Keeping screen on for debugging, detach debugger and force an onResume to turn it off.");
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            Log.d("SCREEN", "Keeping screen on for debugging is now deactivated.");
        }
    }
}

To use it all you need to do is to attach a debugger, then leave the app (Home/Tasks button or turn the screen off) and then come back to it to trigger onResume.

Depending on what you usually debug, it may worth to put the above into onCreate so that it registers earlier and hopefully keeps the screen awake while debugging activity lifecycle before onResume.

In general I advise to use Run instead of Debug when trying out code and only attach the debugger when you found something: this will make your app tenfolds faster and this option the best there is.

Isbell answered 4/5, 2015 at 18:16 Comment(5)
Coding was the easiest option for my test app. I could copy paste above sample and run my app in "debug" mode. It works as expected. ThanksHickey
Thank you for telling me where my "permanent portrait status bar" came from!Dewar
This is an amazing great! I was in the same predicament as you (would forget to turn off "keep screen awake while chargign"). Thank you for going into as much detail as you did!Katherinakatherine
You mention: "Using a wake-lock... Useless: It also doesn't really help to keep the screen on, since it only keeps the CPU awake. See documentation." I checked the documentation page you linked to and it wasn't very clear about the effects. I found this other page here which seems to indicate that wake-locks (well some of them -- there are different types) do indeed keep the screen on (look for the chart listing the types, and their effects): developer.android.com/reference/android/os/PowerManager.html Can you update that part of your answer to include the doc-page above?Sew
For some reason when using Flutter, Debug.isDebuggerConnected() always evaluated to false, so there wasn't a nice way to get that solution to work.Mucronate
S
35

Try this in the adb shell, although it seems not to work on some devices:

svc power stayon usb
Scruff answered 28/12, 2014 at 22:37 Comment(2)
This has been very useful for devices where the OEM skin omits "Stay awake when charging" from developer options. It works perfectly on the HTC One X+. It also allows the screen to dim while not in use - like the missing developer options setting and unlike using other solutions.Repress
svc power stayon false for turning offAdvocation
T
23

On console

 while true; do adb shell input keyevent mouse ; sleep 1 ; done
Topology answered 12/4, 2017 at 8:56 Comment(3)
Nice idea. I use sleep 5 as it's frequent enough, no need to ping the device every second.Rhapsody
this one is a clean solution for meFari
Now, I use auto screen off settings 1 minute and run this command while true; do date "+%H:%M:%S %d-%m-%y - wake up device"; adb shell input keyevent mouse; sleep 50; done. Now I can see, command is working or not.Allanallana
C
17

I have Android version 2.3.6 and under settings -> applications -> development there is an option to stay awake (i.e. your screen will never sleep) while it is plugged in to charge.

Clausewitz answered 12/1, 2012 at 19:25 Comment(6)
I had that option in OS2.2 but it disappeared when I upgraded to 2.3.3, the latest Samsung release.Frederiksberg
Well it's back on my Nexus 4 running Android 4.3 once you enable developer options. Go to Settings -> Developer Options -> Stay Awake (Screen will never sleep while charging)Ashlieashlin
Well, stay awake while charging could cause securuty problems if you are in the workplace, you leave the phone charging at your desk but you are away. Is there any equivalent to "stay unlocked while connected to the developing tools"?Succursal
That option has no effect. The phone screen still goes dim and then locks.Spall
This option is most annoying for anyone using the phone he/she is debuggin on daily! You really don't want to leave your own phone awake all the time, only when you have to. Why? Mainly because phone is charging slowly with USB and MUCH slower with screen on. AFAIK that is true with Samsung phones. Second thing is, damn option will recognize charger as USB connection, and will leave the phone awake on USB as on CHARGER. ANNOYING!!! My Galaxy S6 keeps loosing battery because of that option. Turning it off makes it impossible to debug. And.. you find yourself switching it on/off all the timeCantlon
This still exists and is called Stay awake. Works for me, but phone still dims partially - just doesn't lock.Waites
S
11

Jorge Cevallos is right.

For Android 4 and higher :

  1. Go to Settings > About phone
  2. Touch several times (about 10 times) on "Build number".
  3. Then go back to Sttings menu and you'll find the "Developer options"
  4. Under "Developer Options", you will see "stay awake option ".

Have fun.

Stoush answered 17/6, 2014 at 22:28 Comment(3)
Doesn't work, the screen still decreases brightness and then locks.Spall
This has worked for me on a samsung S7. The screen will dim, but it stays on.Araucaria
This option is most annoying for anyone using the phone he/she is debuggin on daily! You really don't want to leave your own phone awake all the time, only when you have to. Why? Mainly because phone is charging slowly with USB and MUCH slower with screen on. AFAIK that is true with Samsung phones. Second thing is, damn option will recognize charger as USB connection, and will leave the phone awake on USB as on CHARGER. ANNOYING!!! My Galaxy S6 keeps loosing battery because of that option. Turning it off makes it impossible to debug. And.. you find yourself switching it on/off all the timeCantlon
Q
6

Tell PowerManager to keep the screen on (it will still dim):

adb shell settings put global stay_on_while_plugged_in 3

The value 3 is the following two types OR'd together:

BatteryManager#BATTERY_PLUGGED_AC (equal to 1) and BatteryManager#BATTERY_PLUGGED_USB (equal to 2).

Use adb shell dumpsys power | grep mStayOnWhilePluggedInSetting to see the current value.

To revert to normal behavior set the value to zero like so:

adb shell settings put global stay_on_while_plugged_in 0

Verified working on Android 4.4 through 11.0.

Questionary answered 17/6, 2019 at 21:40 Comment(2)
This is still working in 2023 on Samsung S20FE, I've created .bat files to enable it and disable it, the only issue is that you have to remind to disable it when you are done. Thanks for the solution!Tidemark
Doesn't work for me with a Xiaomi Redmi 9 ProMarketa
M
3

Replace 12345 by your unlock code. Then this shell script unlocks your phone:

adb shell input keyevent KEYCODE_WAKEUP # activate 
adb shell input touchscreen swipe 530 1420 530 1120 # swipe up
adb shell input text 12345 # input password
adb shell input keyevent 66 # press enter

You should never disable security features on your phone (as pointed out above). Make sure nobody can read that script file either.

Metamorphose answered 3/7, 2017 at 17:9 Comment(0)
L
2

I had the sampe problem. I found this app to keep the screen unlocked when the phone is connected.

https://play.google.com/store/apps/details?id=com.gmail.developer.runks.enji

Logbook answered 22/1, 2013 at 16:3 Comment(1)
Your answer led me to search the Play Store, and I found Awake for Debug, which happens to be more targeted to this exact use case. The application you posted works too.Gonad
E
2

Improving best answer:

Debug.isDebuggerConnected() is not enough if you are not debugging right now, but still working with an app while device is connected via ADB to Android studio. Then we have to add ADB Enabled check.

Settings.Global.getInt(contentResolver, Settings.Global.ADB_ENABLED, 0) == 1 where 1 is when ADB is enabled

@Override protected void onResume() {
    super.onResume();
    if (BuildConfig.DEBUG) { // don't even consider it otherwise
        if (Debug.isDebuggerConnected() ||
            Settings.Global.getInt(getContentResolver(), Settings.Global.ADB_ENABLED, 0) == 1) {
            Log.d("SCREEN", "Keeping screen on for debugging, detach debugger and force an onResume to turn it off.");
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            Log.d("SCREEN", "Keeping screen on for debugging is now deactivated.");
        }
    }
}
Echinus answered 28/8, 2019 at 10:56 Comment(2)
Can you provide a link to the answer you used as a basis? (You can use the "share" link under the answer you chose.Typescript
@Dmitry Good memory! Thanks!Typescript
D
2

Completely automated solution with unlock and screen awake

I solved this problem by combining two answers and then automating them. So basically when you run the app on a physical it might locked and it might keep going into sleep mode while you are actively developing.

The solution is to write a script which unlocks the device if locked and then set the power mode to stay awake on usb power

unlock_keep_device_awake.sh

#!/bin/bash
#Check if device locked
if adb shell dumpsys window | grep  "mDreamingLockscreen=true"; then 
    echo "Locked"
    adb shell input keyevent KEYCODE_WAKEUP # activate 
    adb shell input touchscreen swipe 530 1420 530 1120 # swipe up
    adb shell input text 1234 # <Change to the device password> input password 
    #adb shell input keyevent 66 # press enter, if you keyguard requires it
else 
    echo "UnLocked"  
fi

# 2 = Stay awake on USB, 0 = reset
adb shell settings put global stay_on_while_plugged_in 2

To automate this add it to the app run configuration to run before launch

Step 1: Run -> Edit Configuration

Step 2: create a Shell script configuration by clicking on '+' -> Shell Script

enter image description here

Step 3: Add the configuration run before running the app

enter image description here

That's it, no more unlocking device or waking it up while development.

One small thing, i mostly charge the phone via AC power so I might not need to reset the stay_awake setting. But if you don't want the device screen to be awake while you charge via USB power the run the below command after you are done with development for the day.

adb shell settings put global stay_on_while_plugged_in 0

Dixiedixieland answered 6/7, 2020 at 14:58 Comment(0)
C
1

Simple. Just add the following code to your activity, and your screen will turn on ONLY when you debug:

@Override
protected void onResume()
{
    Log.d( tag, "onResume()" );
    try
    {
        super.onResume();
        if( BuildConfig.DEBUG && Debug.isDebuggerConnected() )
        {
            Log.d("SCREEN", "Keeping screen on for debugging, detach debugger and force an onResume to turn it off.");
            getWindow().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 );
        }
        else
        {
            getWindow().clearFlags( 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 );
            Log.d( "SCREEN", "Keeping screen on for debugging is now deactivated.");
        }

    }
    catch( Throwable t )
    {
        Log.e( tag, "onResume() - Exception: " + t.getMessage(), t );
    }
}
Cantlon answered 12/1, 2012 at 19:17 Comment(0)
Q
1

My solution was to use scrcpy to mirror my Android's screen on my PC. I used the option --stay-awake to prevent my screen to lock, but with MOD+O to keep my smartphone's screen off. During development, I usually use just on my PC. But, if needed, I can still use on my smartphone. It was the best approach i could find.

Quarto answered 13/5, 2022 at 16:41 Comment(0)
R
1

in OnePlus phones (maybe other phones) go to settings (developer option must be enabled)

  • Search "do not use lock screen" -> turn on!
  • Search "Keep Screen on While Charging" -> turn on!

enjoy debugging!!

Reversible answered 17/2, 2023 at 7:30 Comment(0)
V
0
# find out if screen is on works on android 5.0+
screenOn=`adb shell dumpsys power | grep "Display Power" | grep ON`
if [ -z "$screenOn" ]; then
    echo "turning screen on"
    adb shell input keyevent KEYCODE_POWER
    # unlock by emulating slide up
    adb shell input touchscreen swipe 930 880 930 380
fi
Varipapa answered 12/8, 2016 at 2:57 Comment(0)
A
0

I created simple shell script for my macOS

File Name : cell-screen.sh

#!/bin/sh

echo '`cell-screen on` to keep the screen on during usb debugging'
echo '`cell-screen off` to reset'

echo ''
echo 'your parameter - ' $1

if [[ "$1" = "on" ]]; then
    ~/Library/Android/sdk/platform-tools/adb shell settings put global stay_on_while_plugged_in 2
elif [[ "$1" = "off" ]]; then
    ~/Library/Android/sdk/platform-tools/adb shell settings put global stay_on_while_plugged_in 0
else
    echo '\n[****]Bad Input.'
fi

echo '\nEnd'

Steps:

  1. I saved the script to the default use location - /Users/[your username]
  2. Given executable access to the file - chmod +x ~/cell-screen.sh
  3. Whenever I start my development tasks, I just execute the shell script in terminal - ~/cell-screen.sh on
  4. After I complete my development work, I simply execute - ~/cell-screen.sh off

For Windows Users:

Change the shell script for the adb location - %LOCALAPPDATA%\Android\sdk\platform-tools\adb

Amphibian answered 14/8, 2020 at 5:59 Comment(0)
I
0

I've been using Microsoft's YourPhone app, built into Windows 10.

If you tell it to mirror your display, it appears the screen will stay "on" in the mirrored window. Simply having the app installed will not keep your display on.

This has been quite reliable for me on my Samsung Galaxy 21 Ultra. YMMV.

Make sure to close that mirroring window, though, if you don't need it. Keeping your screen on, even if it's mostly black during mirroring, still eats battery. Might not be an issue when debugging, as USB is connected, but disconnecting doesn't stop mirroring :)

Igenia answered 20/5, 2021 at 14:43 Comment(0)
N
-1

You can just set the Screen Timeout to 30 minutes or turn it off. This option is under : Settings/Display/Screen Timeout

Hope it helps.

Nailbiting answered 12/1, 2012 at 19:19 Comment(1)
My phone has max 10 minute timeout and no option to turn it off. :(Frederiksberg
V
-1

Two options come into my mind:

  1. write an app which will force screen timeout to be very high. Use SCREEN_OFF_TIMEOUT or STAY_ON_WHILE_PLUGGED_IN.

  2. If your phone is rooted and you are connected to wifi in the same network as the computer you're developing on, you can enjoy this wonderful app which comes with an option for screen timeout too: wifi adb.

Vala answered 12/1, 2012 at 19:25 Comment(0)
F
-1

I have 2 devices with Android 2.3.3 and they are both having this option in Settings/Applications/Development and its called Stay Awake (Screen will never sleep while charging). And one of them is Samsung Galaxy S.

Also I have a device with Android 2.2 (HTC Desire) an it has also the same functionality in the same location.

It is weird that your doesn't , do you use a custom ROM?

Fungible answered 12/1, 2012 at 19:26 Comment(1)
Yes it is weird that I don't have it on my Samsung Galaxy S with OS2.3.3. Only "USB debugging" and "Allow mock locations" are there. "Stay Awake" disappeared when I upgraded from 2.2 to 2.3.3. :(Frederiksberg
L
-2

You can re-enable Developer options, which configurations are now hidden:

1 - Go to Settings > About > Software information > More...

2 - Then touch Build number 7 times, which will give you a count down, and then say “you’re now a developer”.

And Developer Options are back!

Liva answered 3/3, 2014 at 15:27 Comment(1)
Tried here in my Moto G and it worked! Now I can make the phone never turn off the screen while connected by USB (charging). This is very handy while using to transfer files over MTP.Jedthus

© 2022 - 2024 — McMap. All rights reserved.