For a long time I thought that I knew how to stop the screen from going into sleep mode, I simply used this code in my Activity:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
However, I realized that this only worked when my phone was in "developer mode", ie when the USB debugging (Settings --> Developer options --> USB debugging) was enabled/checked. Then the above code indeed stops the screen/device to go to sleep.
When that debugging is not checked, then my screen goes to sleep like there's no tomorrow. I am running Android 4.04 on my device, and
android:minSdkVersion="12"
android:targetSdkVersion="16"
Edit
I have tested with Commonsware's suggestion, and added the setKeepScreenOn() to the code, so it looks like this:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
View root = findViewById(android.R.id.content);
if (root != null)
root.setKeepScreenOn(true);
I have also checked so that this code is actually executed, and it is. But it doesn't change a thing.
FLAG_KEEP_SCREEN_ON
, and only have ever usedsetKeepScreenOn()
(as it is simpler), I cannot comment regarding the efficacy of yourFLAG_KEEP_SCREEN_ON
code. – ArchaizesetKeepScreenOn()
for a "delayed timeout", where you want to keep the screen lit for a while, but not indefinitely if the user is not actively using your app. This sample has worked successfully on all hardware that I have tried it on. – ArchaizeOnCreate()
. It works using either method (FLAG_KEEP_SCREEN_ON
flag orView.setKeepScreenOn(true)
). If I try to keep the screen on sometime afterOnCreate()
(based on user input, for example), it doesn't work. – Dace