OkyDokyman
OkyDokyman

Reputation: 3876

Disable keep screen on

I used:

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

How do I resume to Default state (no-keep-on)?

Upvotes: 78

Views: 31778

Answers (5)

MBH
MBH

Reputation: 16639

I've created these kotlin extensions:

fun Activity.keepScreenOn(rootView: View? = null) {
    window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    rootView?.keepScreenOn = true
}
fun Activity.clearScreenOn() {
    window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}

Then onCreate you can call keepScreenOn() and onDestroy clearScreenOn()

Upvotes: 1

NazarYavornytskyy
NazarYavornytskyy

Reputation: 359

Directly from documentation:

Note: You don't need to clear the FLAG_KEEP_SCREEN_ON flag unless you no longer want the screen to stay on in your running application (for example, if you want the screen to time out after a certain period of inactivity). The window manager takes care of ensuring that the right things happen when the app goes into the background or returns to the foreground. But if you want to explicitly clear the flag and thereby allow the screen to turn off again, use clearFlags(): getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).

Upvotes: 0

Zar E Ahmer
Zar E Ahmer

Reputation: 34370

Another approach

getWindow().setFlags(this.getWindow().getFlags() & ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Also read this

and you can also set android:keepScreenOn="true" in the root View in xml.

Upvotes: 4

Alexander Abramov
Alexander Abramov

Reputation: 1500

If you instead set a flag android:keepScreenOn="true" (documentation) only on the views that need to keep the screen on, you wouldn't need to reset the flag manually.

Upvotes: 20

Noel
Noel

Reputation: 7410

I think this should do it:

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

See API for details.

Upvotes: 159

Related Questions