[ACCEPTED]-How to prevent the screen of an android device to turn off during the execution of an Activity?-android-activity

Accepted answer
Score: 103

Add android:keepScreenOn="true" to some widget in your layout XML resource 9 for this activity. So long as that widget 8 is visible on the screen, the screen will 7 not turn off automatically.

EDIT:

A WakeLock, as suggested 6 by other answers, technically will work. But 5 then you have to manually release the WakeLock (if 4 you mess that up, the screen will stay on 3 a long time). And, since you could mess it up, you 2 need the WAKE_LOCK permission. Using keepScreenOn avoids all 1 of that.

Score: 38

To change it on-the-fly do this:

if (keepScreenOn)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

0

Score: 4

Handling Fragments and Screen Rotation

The Android documentation, Keep the device awake outlines each 16 solution.

Solution #1 - Flags

Documentation - Alternatives to using wake locks

For Fragments use the programmatic 15 approach that is less battery intensive.

Enable

activity!!.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

Disable

activity!!.window.clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON)

For 14 my use case I called this in onStop() so the screen 13 would default to the normal configuration 12 when the Fragment showing the media content 11 is exited.

Avoid

keepScreenOn=true does not work when there is a 10 configuration change such as a screen rotation 9 for Fragments.

Note: Android's Keep the device awake documentation 8 should be updated accordingly to handle 7 this case.

Solution #2 - Wake Lock

Documentation - Keep the CPU on with Wake Locks

A 6 Wake Lock offers more control over keeping 5 the specific elements of the device awake, but 4 is more battery intensive, and important 3 to release manually to save the battery 2 since it is not handled automatically by 1 the system.

Score: 2

For "Xamarin Android":

Window.AddFlags(WindowManagerFlags.KeepScreenOn);

0

Score: 1

You'll want to add WAKE_LOCK to your manifest, and 2 set and remove it as needed within your 1 app. See the google docs here for PowerManager.WAKE_LOCK

http://developer.android.com/reference/android/os/PowerManager.html

Score: 1

You may want to use the wake-lock to prevent 1 the screen off.Pleas refer http://developer.android.com/reference/android/os/PowerManager.WakeLock.html

More Related questions