Force Screen On

How do I force the screen to stay active and not shut off while my app is running?


Solution 1:

PLEASE DO NOT USE A WAKE LOCK

This requires that you give your app an additional permission, and it is very easy to introduce bugs where you accidentally remain holding the wake lock and thus leave the screen on.

It is far, far better to use the window flag FLAG_KEEP_SCREEN_ON, which you can enable on your activity's window in your onCreate() like this:

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

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

This will make sure that the screen stays on while your window is in the foreground, and only while it is in the foreground. It greatly simplifies this common use case, eliminating any juggling you need to do as your app transitions between states.

Solution 2:

This Question has Already Great Answer by @hackbod !

I am Answering this Question with Two Additional Solutions !

Existing Solution :

@Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);    
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

Additional Solutions:

we can use keepScreenOn

1. implementation using setKeepScreenOn() in java code

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // or any View (in case generated programmatically ) 
        View v = getLayoutInflater().inflate(R.layout.driver_home, null);

        v.setKeepScreenOn(true);
        setContentView(v);
       }

Docs http://developer.android.com/reference/android/view/View.html#setKeepScreenOn(boolean)

2. Adding keepScreenOn to xml layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true" >

Docs http://developer.android.com/reference/android/view/View.html#attr_android%3akeepScreenOn

Note ( Some Useful Points) :

1. it Doesn't matter that keepScreenOn should be used on Main/Root/Parent View it can be used with any child view will work As same as it works in Parent view

2. The Thing Only matter is that View's Visibility must be visible other wise it will not work !