How do I keep my screen unlocked during USB debugging?

Android

Android Problem Overview


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!)

Thanks in advance...

Android Solutions


Solution 1 - Android

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

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.

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: to 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.

Solution 2 - Android

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

svc power stayon usb

Solution 3 - Android

On console

 while true; do adb shell input keyevent mouse ; sleep 1 ; done

Solution 4 - Android

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.

Solution 5 - Android

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.

Solution 6 - Android

I have created an app for this purpose. You can search it on google play "Keep Awake for Debugging" .It will keep your phone-unlocked/screen-on only when you have ADB debugging enabled. It is not restricted to USB only, it works over wi-fi as well.

Solution 7 - Android

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.

Solution 8 - Android

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 and BatteryManager#BATTERY_PLUGGED_USB.

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 9.0.

Solution 9 - Android

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

Solution 10 - Android

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.");
        }
    }
}

Solution 11 - Android

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

Solution 12 - Android

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 );
	}
}

Solution 13 - Android

# 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

Solution 14 - Android

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

Solution 15 - Android

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 :)

Solution 16 - Android

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.

Solution 17 - Android

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.

Solution 18 - Android

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.

Solution 19 - Android

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?

Solution 20 - Android

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!

Solution 21 - Android

Use this in your Manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />

and your screen won't turn off!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBarry FruitmanView Question on Stackoverflow
Solution 1 - AndroidTWiStErRobView Answer on Stackoverflow
Solution 2 - AndroidKaneView Answer on Stackoverflow
Solution 3 - Androiduser3552437View Answer on Stackoverflow
Solution 4 - AndroidPaul MaserratView Answer on Stackoverflow
Solution 5 - AndroidBurhan ARASView Answer on Stackoverflow
Solution 6 - AndroidArpit GuptaView Answer on Stackoverflow
Solution 7 - AndroidatonView Answer on Stackoverflow
Solution 8 - Androidsatur9nineView Answer on Stackoverflow
Solution 9 - AndroidAdorjan PrinczView Answer on Stackoverflow
Solution 10 - AndroidDmitriy PavlukhinView Answer on Stackoverflow
Solution 11 - AndroidBuild3rView Answer on Stackoverflow
Solution 12 - AndroidrubmzView Answer on Stackoverflow
Solution 13 - Androidover_optimisticView Answer on Stackoverflow
Solution 14 - AndroidARIJITView Answer on Stackoverflow
Solution 15 - AndroidAuri RahimzadehView Answer on Stackoverflow
Solution 16 - AndroidFélix SeveroView Answer on Stackoverflow
Solution 17 - AndroidMarcello Grechi LinsView Answer on Stackoverflow
Solution 18 - AndroidstefanView Answer on Stackoverflow
Solution 19 - AndroidMikyView Answer on Stackoverflow
Solution 20 - AndroidMikeView Answer on Stackoverflow
Solution 21 - AndroidAneemView Answer on Stackoverflow