Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the screen awake throughout my activity

Tags:

android

screen

I have three activities in my app. I want to keep the screen awake when it is in the second activity. The screen should not go off in my second activity unless the "lock" key is pressed manually. I went through many links but they seem unclear to me.

like image 822
user838522 Avatar asked Dec 09 '11 06:12

user838522


People also ask

How do I keep my Android screen awake?

Open Settings. Tap Display. Tap Sleep or Screen timeout. Select how long you want your Android smartphone or tablet screen to stay on before turning off due to inactivity.

How do I prevent an Android device from going to sleep programmatically?

Using android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON . You can use whichever approach is best for your app. The advantage of setting the flag programmatically in your activity is that it gives you the option of programmatically clearing the flag later and thereby allowing the screen to turn off.


1 Answers

As discussed in the Android tutorial Keep the Screen On, you can do this in a few ways. You can set the FLAG_KEEP_SCREEN_ON on the activity's window:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 

An XML equivalent for that is to add the attribute android:keepScreenOn="true" to the root view of your activity's layout. The advantage of setting the flag programmatically is that you can use

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 

when you no longer need to force the screen to stay on while your activity is running.

Another way to control the screen (and certain other resources) is to use a wake lock:

mWakeLock = ((PowerManager) getContext().getSystemService(Context.POWER_SERVICE))     .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName()); mWakeLock.acquire(); // screen stays on in this section mWakeLock.release(); 

The manifest will have to include this permission:

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

However, as discussed in the tutorial, a wake lock is more appropriate for other use cases (such as a service or background task needing the CPU to keep running while the screen is off).

like image 141
Ted Hopp Avatar answered Sep 22 '22 21:09

Ted Hopp