Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct method for setKeepScreenOn / FLAG_KEEP_SCREEN_ON

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

like image 949
Emma Assin Avatar asked Mar 16 '11 20:03

Emma Assin


2 Answers

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.

like image 99
Matthew Willis Avatar answered Oct 16 '22 16:10

Matthew Willis


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/

like image 40
Blundell Avatar answered Oct 16 '22 14:10

Blundell