How do I keep the screen on in my App? [duplicate]
Asked Answered
K

11

144

For my Android app I never want the phone to lock or the back light to turn off

Kitchenmaid answered 19/4, 2011 at 7:13 Comment(3)
There is a better solution in this post: https://mcmap.net/q/161111/-disable-keep-screen-onWisp
https://mcmap.net/q/158625/-how-do-i-keep-the-screen-on-in-my-app-duplicateMysia
this duplicated question got more views and I guess it's because older question used force but here keepNortheastward
M
104

Use PowerManager.WakeLock class inorder to perform this. See the following code:

import android.os.PowerManager;

public class MyActivity extends Activity {

    protected PowerManager.WakeLock mWakeLock;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle icicle) {
        setContentView(R.layout.main);

        /* This code together with the one in onDestroy() 
         * will make the screen be always on until this Activity gets destroyed. */
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();
    }

    @Override
    public void onDestroy() {
        this.mWakeLock.release();
        super.onDestroy();
    }
}

Use the follwing permission in manifest file :

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

Hope this will solve your problem...:)

Microbiology answered 19/4, 2011 at 7:23 Comment(13)
Shouldn't this be in onResuem and onPause so the app won't keep the screen on when user hits the home button?Adnopoz
Does PowerManager pm have to be declared as final?Fumikofumitory
Not so good proposal for what @SethHikari asked.. Too much work, too much cpu power consumed..Urbannai
In case this helps anyone else, another answer with lower ratings (https://mcmap.net/q/158625/-how-do-i-keep-the-screen-on-in-my-app-duplicate) works just as well and doesn't rely on you releasing the wakelock.Byrdie
This method is deprecated, you can refer to the documentation here: developer.android.com/reference/android/os/…Darksome
Please remove this answer, which is obsolete. Thank you.Raine
PLEASE DO NOT USE A WAKE LOCK.Bobbiebobbin
I don't think the answer should be removed, just edited to state that it's deprecated and that it's best to simply use a FLAG_KEEP_SCREEN_ON flag.Napoli
It is deprecated. You can just add android:keepScreenOn="true" on XML file or add getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); on onCreate Activity. Android DeveloperAgulhas
Do not delete this answer. There are a few cases where getWindow().addFlags(FLAG_KEEP_SCREEN_ON) does not work as intention.Marelda
@Marelda Can you give us some example?Flurried
@FedericoPonzi Case 1: When you need only SCREEN_DIM_WAKE_LOCK, not SCREEN_BRIGHT_WAKE_LOCK. Case 2: When you need screen wake lock while another developer's app is running in the foreground, where you cannot directly get the Window of that app.Marelda
@Raine why remove it? It's still useful for niche applications.Dugong
Z
245

Add one line of code after setContentView() in onCreate()

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flag);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
Zarf answered 17/2, 2013 at 21:4 Comment(5)
This answer is per activity, much better suitable if you don't want app to wake cpu because u didn't manage wake locks properly..Urbannai
So how do you turn this flag off?Wojcik
@kilaka turn it off with the line getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).Modlin
@Modlin I assume it gets reset automatically when the activity is destroyed, right?Aswarm
@androiddeveloper Yes, it will be reset automatically. See the note in the "Keep the Screen On" section: developer.android.com/training/scheduling/wakelock.htmlKenlee
M
130

Lots of answers already exist here! I am answering this question with additional and reliable solutions:

Using PowerManager.WakeLock is not so reliable a solution, as the app requires additional permissions.

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

Also, if it accidentally remains holding the wake lock, it can leave the screen on.

So, I recommend not using the PowerManager.WakeLock solution. Instead of this, use any of the following solutions:

First:

We can use getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); in onCreate()

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

Second:

we can use keepScreenOn

1. implementation using setKeepScreenOn() in java code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        View v = getLayoutInflater().inflate(R.layout.driver_home, null);// or any View (incase generated programmatically ) 
        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

Notes (some useful points):

  1. It doesn't matter that keepScreenOn should be used on a Main/Root/Parent View. It can be used with any child view and will work the same way it works in a parent view.
  2. The only thing that matters is that the view's visibility must be visible. Otherwise, it will not work!
Metonym answered 28/8, 2013 at 11:58 Comment(6)
Yes, it should be the correct answer! I was seeking for an example of an implementation of "keepScreeOn" (which I thought it was the best way to do this) and this is the only answer that shows it well!Micronesian
no need for the permission .Teide
v.setKeepScreenOn(true); Wonderfully works on M sdk phones, didn't check on Ls'Mawkish
Good explanationUnavailing
For the Second solution, we don't steps 1 and 2. Just using step 2 was enough for me.Reflection
android:keepScreenOn="true" was enough for me for exoplayerDoxy
M
104

Use PowerManager.WakeLock class inorder to perform this. See the following code:

import android.os.PowerManager;

public class MyActivity extends Activity {

    protected PowerManager.WakeLock mWakeLock;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle icicle) {
        setContentView(R.layout.main);

        /* This code together with the one in onDestroy() 
         * will make the screen be always on until this Activity gets destroyed. */
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();
    }

    @Override
    public void onDestroy() {
        this.mWakeLock.release();
        super.onDestroy();
    }
}

Use the follwing permission in manifest file :

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

Hope this will solve your problem...:)

Microbiology answered 19/4, 2011 at 7:23 Comment(13)
Shouldn't this be in onResuem and onPause so the app won't keep the screen on when user hits the home button?Adnopoz
Does PowerManager pm have to be declared as final?Fumikofumitory
Not so good proposal for what @SethHikari asked.. Too much work, too much cpu power consumed..Urbannai
In case this helps anyone else, another answer with lower ratings (https://mcmap.net/q/158625/-how-do-i-keep-the-screen-on-in-my-app-duplicate) works just as well and doesn't rely on you releasing the wakelock.Byrdie
This method is deprecated, you can refer to the documentation here: developer.android.com/reference/android/os/…Darksome
Please remove this answer, which is obsolete. Thank you.Raine
PLEASE DO NOT USE A WAKE LOCK.Bobbiebobbin
I don't think the answer should be removed, just edited to state that it's deprecated and that it's best to simply use a FLAG_KEEP_SCREEN_ON flag.Napoli
It is deprecated. You can just add android:keepScreenOn="true" on XML file or add getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); on onCreate Activity. Android DeveloperAgulhas
Do not delete this answer. There are a few cases where getWindow().addFlags(FLAG_KEEP_SCREEN_ON) does not work as intention.Marelda
@Marelda Can you give us some example?Flurried
@FedericoPonzi Case 1: When you need only SCREEN_DIM_WAKE_LOCK, not SCREEN_BRIGHT_WAKE_LOCK. Case 2: When you need screen wake lock while another developer's app is running in the foreground, where you cannot directly get the Window of that app.Marelda
@Raine why remove it? It's still useful for niche applications.Dugong
R
57

Don't Use Wake Lock.

It requires permission and other stuff and may cause error if you forget to set it in right time.

The easiest way is to use the below code when you want to keep your screen on..

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

One addition to the answer if you want to remove or terminate keep_Screen_on

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

you can also see here..

And the best and easiest way .. Using android:keepScreenOn="true" in layout root of your activity does the same thing without extra code. But it will remain it in Keep_Scree_on State..

It can be vary on your demand See here

Revivify answered 17/6, 2014 at 10:49 Comment(1)
Works great. I also clear the flag in onStop so screen on state behaves as usual when outside my app. For some odd reason it seemed to work without doing that but seems to be the correct way to do it anyway so to be sure I'll leave it (perhaps it works differently on other phones than my Nexus 5).Durian
M
15
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.

Mysia answered 15/4, 2013 at 12:38 Comment(1)
Same as @hackbod's solution: https://mcmap.net/q/161112/-force-screen-onWojcik
E
12

Adding android:keepScreenOn="true" in the XML of the activity(s) you want to keep the screen on is the best option. Add that line to the main layout of the activity(s).

Something like this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:keepScreenOn="true">

...

</LinearLayout>
Eparchy answered 2/1, 2015 at 15:31 Comment(0)
A
10

You can simply use setKeepScreenOn() from the View class.

Anaglyph answered 21/11, 2012 at 22:37 Comment(0)
B
10

There are multiple ways you can do it:

Solution 1:

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

Solution 2:

In activity_main.xml file, simply add:

<android:KeepScreenOn="true"/>

My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.

Also, make sure to turn off the screen while closing the activity. You can do it in this way:

public void onDestry() {
    getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
Beatific answered 23/7, 2017 at 6:19 Comment(1)
There are such suggestions/answers exist alreadyStokehold
S
4

You need to use Power Manager to acquire a wake lock in your application.

Most probably you are interested in a FULL_WAKE_LOCK:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
....
wl.release();
Selvage answered 19/4, 2011 at 7:21 Comment(1)
he's talking about screen (can be solved with one flag), why did you suggest FULL_WAKE_LOCK?Northeastward
A
4

No need to add permission and do tricks. Just use below text in your main layout.

  android:keepScreenOn="true"
Acumen answered 21/3, 2017 at 8:12 Comment(0)
F
1

At this point method

final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();

is deprecated.

You should use getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); and getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Flashlight answered 27/5, 2015 at 8:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.