Android: How to turn screen on and off programmatically?
Asked Answered
T

16

112

Before marking this post as a "duplicate", I am writing this post because no other post holds the solution to the problem.

I am trying to turn off the device, then after a few minutes or sensor change, turn it back on.

Turn Off Display Tests

I am able to turn off the screen using:

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);

I have been unable to turn off the screen using the wl.release() method.

Turn On Display Test

My first guess, as follows, does not work. Nothing happens, screen remains off.

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = -1f;
getWindow().setAttributes(params);

I also then tried to use wakelocks, with no success.

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "tag");
wl.acquire();

Finally I have tried the following, with no result.

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

All in all, I don't get any kind of error in the console for any of these methods. My test text "Screen should be on", is on the the screen when I turn on the device using the power button. This shows that the code should have ran. Please only answer if you have tested the code, it seems like many of the functions such as params.screenBrightness = -1, do not work as they should according to the sdk.

Tarter answered 5/3, 2012 at 3:36 Comment(3)
Your method to turn off the screen did not work for me. You set the flag to keep the screen on all the time, which will drain power.Finegrain
Did you ever figure this out? There are a few apps on PlayStore suggesting they do it. Tried this one and it works but it asks for Device Administration. play.google.com/store/apps/…Dulcle
did you reached something in this problem ?!!Daryn
M
71

I am going to assume you only want this to be in effect while your application is in the foreground.

This code:

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);

Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.

In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.

Now for turning the screen back to regular brightness, just setting the brightness value should do it:

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);

I can't explain why this wouldn't replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);

This definitely works. For example, Google's Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.

To help debug, you can use "adb shell dumpsys window" to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.

And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)

Marilou answered 14/3, 2012 at 14:28 Comment(4)
Is there a better way for turning off the screeen?Thistledown
As @Marilou has stated above, "params.screenBrightness = 0;" does not turn the screen off completely; instead, it makes the screen as dim as possible. And "params.screenBrightness = -1;" turns the screen back to its previous brightness level. However, there are cases where we need to turn the screen off completely. There may be other methods ...Greed
What would those other methods be which actually turn off the screen rather than just setting minimum brightness which may or may not work?Congelation
I've set the brightness to 0.004 and that makes the screen really dim. setting it to 0.003 does the same as if you would set it to zero.Gulden
L
38

I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-

    private void unlockScreen() {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

And call this method from onResume().

Liquescent answered 16/3, 2012 at 8:8 Comment(2)
Not useful if you plan on turning the screen on when you want to terminate the activity.Gregorio
Well people, I will suggest not to use my method as this did not work for me on Micromax Canvas2+. Use this link instead.Liquescent
W
30

I would suggest this one:

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();

The flag ACQUIRE_CAUSES_WAKEUP is explained like that:

Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately, when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately.

Also, make sure you have the following permission in the AndroidManifewst.xml file:

<uses-permission android:name="android.permission.WAKE_LOCK" />
Wynnie answered 16/3, 2012 at 9:13 Comment(1)
Unfortunately, the flag SCREEN_BRIGHT_WAKE_LOCK has been deprecated.Rotifer
M
22

Hi I hope this will help:

 private PowerManager mPowerManager;
 private PowerManager.WakeLock mWakeLock;

 public void turnOnScreen(){
     // turn on screen
     Log.v("ProximityActivity", "ON!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
     mWakeLock.acquire();
}

 @TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
 public void turnOffScreen(){
     // turn off screen
     Log.v("ProximityActivity", "OFF!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
     mWakeLock.acquire();
}
Morava answered 10/8, 2015 at 6:4 Comment(6)
How to turn off the screen without involving the proximity sensor?Congelation
Hi @Michael, you simply use public void turnOffScreen() function onlyMorava
Yes, but it appears that this function uses PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK which only turns off the screen when the proximity sensor is in the "near" state.Congelation
Ahh okay I understand, you may use this instead PowerManager.SCREEN_DIM_WAKE_LOCKMorava
This is not working in Android M above. Any new solution?Huebner
Problem - as soon as I release the PROXIMITY_SCREEN_OFF_WAKE_LOCK waitlock, the screen comes back on. How do I prevent this?Congelation
S
8
     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    screenLock.acquire();

  //later
  screenLock.release();

//User Manifest file

Softy answered 25/3, 2016 at 13:8 Comment(4)
This should be the correct answer. I'm using Android 5 and this is the only thing that actually works. Only sidenote is that SCREEN_BRIGHT_WAKE_LOCK is deprecated, and I don't see a drop-in replacement. Anyone?Designate
There is no problem, your answer is perfectly usable. As I said: "it's the only answer that actually works"Designate
@Designate what is the difference between this answer and answer provided by ramdroid?Wonky
@BugsHappen Ramdroids one is more elaborate :) But yeah, it's the same. Don't know why Pir Fahim Shah posted this answer, or why I did not see Ramdroids one at the time.Designate
B
6

Are you sure you requested the proper permission in your Manifest file?

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

You can use the AlarmManager1 class to fire off an intent that starts your activity and acquires the wake lock. This will turn on the screen and keep it on. Releasing the wakelock will allow the device to go to sleep on its own.

You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)

Butterwort answered 12/3, 2012 at 22:4 Comment(1)
Thanks for the response. Yes I am sure. Its in my manifest and there are no debug errors. AlarmManager won't help me when I use sensors to turn on the screen. I haven't had much luck with goToSleep, but ya that still doesnt help me in turning on the screen. I am currently able to make the screen go offTarter
S
6

Simply add

android:keepScreenOn="true" 

or call

setKeepScreenOn(true) 

on parent view.

Svetlanasvoboda answered 24/1, 2019 at 6:57 Comment(0)
B
5

The best way to do it ( using rooted devices) :

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

    int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
    getWindow().addFlags(flags); // this is how your app will wake up the screen
    //you will call this activity later

   .
   .
   .
}

Now we have this two functions:

private void turnOffScreen(){

  try{
     Class c = Class.forName("android.os.PowerManager");
     PowerManager  mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
     for(Method m : c.getDeclaredMethods()){
        if(m.getName().equals("goToSleep")){
          m.setAccessible(true);
          if(m.getParameterTypes().length == 1){
            m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
          }
        }
     } 
  } catch (Exception e){
  }
}

And this:

public void turnOnScreen(){
  Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
  startActivity(i);
}

Sorry for my bad english.

Burrows answered 31/1, 2017 at 22:28 Comment(3)
Hello, Rodrigo Gontijo Why we need to root device pl. tell me?Bosanquet
@Bosanquet because you need to invoke the function ( "goToSleep") and this function requires a special permission, only granted to system apps: <uses-permission android:name="android.permission.DEVICE_POWER"/>Burrows
ok thanks and please provide link or step how to root device if possible. Thanks in advance.Bosanquet
T
4

Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).

WindowManager.LayoutParams params = this.getWindow().getAttributes();

/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);

/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);

If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.

Trappist answered 23/2, 2013 at 5:24 Comment(2)
On my device, nexus 7, this does not work well, the screen is still on, just a little darker, but not completely black.Quicksilver
Than surely this implementation shouldn't be used for a public release, although it may serve an integration with specific device. I will keep the post as it might help someone for the later.Jaymejaymee
V
4

To keep screen on:

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

Back to screen default mode: just clear the flag FLAG_KEEP_SCREEN_ON

getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Verrocchio answered 17/4, 2017 at 18:12 Comment(0)
T
4

This is worked on Marshmallow

private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;

public void turnOnScreen() {
    if (_screenOffWakeLock != null) {
        _screenOffWakeLock.release();
    }
}

public void turnOffScreen() {
    try {
        _powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
        if (_powerManager != null) {
            _screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            if (_screenOffWakeLock != null) {
                _screenOffWakeLock.acquire();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Tear answered 22/10, 2018 at 6:14 Comment(2)
It would be great if you explain why your answer works which will help SO member to understand better.Glynnis
turning off the screen doesn't work so well... when the proximity sensor goes from near to far, the screen comes back on... and if i release the wake lock before that, it still comes on immediately!Congelation
H
4

If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission

before you use goToSleep(), you need use reflection just like:

public static void goToSleep(Context context) {
    PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    try {
        powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

Now,you can use goToSleep() to turn screen off.

This is what happens when the power key is pressed to turn off the screen.

Haileyhailfellowwellmet answered 5/12, 2018 at 13:41 Comment(0)
P
4

As per Android API 28 and above you need to do the following to turn on the screen

setShowWhenLocked(true); 
setTurnScreenOn(true); 
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
Prussiate answered 24/8, 2019 at 5:26 Comment(1)
Thanks, this solution worked!Alost
D
2

Regarding to Android documentation it can be achieve by using following code line:

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

I have added this in my onCreate method and it works fine.

On the link you will find different ways to achieve this and general explanation as well.

Link to the documenation: https://developer.android.com/training/scheduling/wakelock.html

Designedly answered 4/12, 2016 at 12:6 Comment(0)
S
1

I wouldn't have hope of "waking the screen" in the activity. If the screen is off the activity is probably in a paused state and shouldn't be running any code.

When waking up, there is the issue of the lockscreen. I don't know how any app can automatically bypass the lockscreen.

You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.

You could also attempt to start the activity direct from the service, but I really don't know if that will turn the screen on or bypass the lockscreen.

Siberson answered 13/3, 2012 at 23:6 Comment(2)
Thank you for the response, I put in some vibrate code, and when i have the screen off,and i activate one of my sensors, it vibrates. So the code is definitely running. The lockscreen is not a big deal, i just use keyguard.Tarter
Even if the code runs, it's outside the lifecycle. You can't trust activities that are off the screen. Think game downloaders, most are written in the activity and you can leave for maybe 30seconds to a few minutes and they'll still download, but they usually break because the OS kills the activity based on your usage patterns.Siberson
C
0

I have tried all above solution but none worked for me. so I googled and found below solutions. I tried and it worked.

https://www.tutorialspoint.com/how-to-turn-android-device-screen-on-and-off-programmatically

if there is any suggestion then please give

Congressman answered 24/5, 2020 at 3:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.