Correct method for setKeepScreenOn / FLAG_KEEP_SCREEN_ON
Solution 1
Try this answer:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow
is a method defined for activities, and won't require you to find a View
first.
Solution 2
As Hawk said but poorly explained.
You can also use FLAG_KEEP_SCREEN_ON
in your XML layout file.
Note the android:keepScreenOn="true"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true"
android:orientation="vertical" >
<!-- whatever is in your layout -->
</LinearLayout>
I've now written all the choices for keeping the screen on up into a blog post:
http://blog.blundellapps.com/tut-keep-screen-onawake-3-possible-ways/
Solution 3
Set android:keepScreenOn
in XML
Solution 4
If you are doing it on a class extends View. You can simple:
this.setKeepScreenOn(true);
Related videos on Youtube
Emma Assin
Updated on July 09, 2022Comments
-
Emma Assin almost 2 years
I am using the method setKeepScreenOn(true) and haven't been able to figure out how to call this in relation to the current Activity (which has a content view set). I've been able to get it to work by calling it on one of my buttons which is always present in the view, but this feels wrong - and I'm sure there must be a way to get around this. I tried referencing the current focus like this:
getCurrentFocus().setKeepScreenOn(true);
but that threw a NullPointerException. Maybe there was no current focus. So, can anyone tell me how I can reference the view class which I am working inside? Thanks :)
-
Matthew Willis about 13 yearspossible duplicate of How to keep android device from sleeping while plugged in
-
-
Emma Assin about 13 yearshmm. my class extends Activity, but as I setContentView I assumed it was also a View - maybe not the case?
-
Matthew Willis about 13 yearsIt's not a view, actually. But, setContentView does take a View parameter. I think he misread your question.
-
Tony D almost 12 yearsnice, I was using wake locks before.
-
Ted about 11 yearsThis only works for me if the phone is in "developer mode", so if you go into settings --> "USB-something". Then it works to use the FLAG_KEEP_SCREEN_ON, but if I do not have the developer mode checked, then it has no effect at all.
-
caw over 10 years@Ted: What you've written here and in (at least) two other questions is just wrong. We should put it right for others:
FLAG_KEEP_SCREEN_ON
works perfectly for what it describes: It just makes the screen keep on. Neither is there any permission required for this to work nor does it only work if your device is in debug mode. It should work on every device, and if it doesn't, it's the device's fault ;) -
Muhammad Shauket over 7 yearsits not work for some devices. not working on nexus 6p