23

I am trying to turn on and off the display after a certain action happens (Lets just worry about turning the screen off for now). From what I understand from wake lock, this is what I have:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);    
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");

When I read other posts on stackoverflow and else where, they seem to tell me that PARTIAL_WAKE_LOCK will turn the screen off. But if I read the SDK it says that it will only allow the screen to be turned off. I think this isn't right.

Zoe
  • 27,060
  • 21
  • 118
  • 148
thegreyspot
  • 4,079
  • 5
  • 28
  • 34
  • 3
    I'm also struggling with this and I must add: CERTAINLY TEST WITHOUT YOUR CABLE CONNECTED!!! many devices display different behavior with or without cable connected so if you want to test it, install your app; disconnect your cable and only then test your app!!! – SanThee Dec 23 '15 at 15:52

5 Answers5

19

There are two choices for turning the screen off:

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);

// Choice 1
manager.goToSleep(int amountOfTime);

// Choice 2
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();

You will probably need this permission too:

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

UPDATE:

Try this method; android turns off the screen once the light level is low enough.

WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
A. Abiri
  • 10,750
  • 4
  • 30
  • 31
  • 3
    In my experience these methods are highly unreliable. – Jon Willis Jul 20 '11 at 05:05
  • Hi Arash, When i try the first choice I get a force close. I tried debugging it but that doesn't seem to work either. I just manager.goToSleep(1000); I am not sure what the 1000 means. When I try choice 2, i get nothing to happen. Are we sure that this will actually turn off the display? or will it just prevent from anything else turning off the display. I alos have the permissions set in the manifest. Thanks for your help – thegreyspot Jul 20 '11 at 23:14
  • Thanks, this does turn the screen off! However, when my timer runs and the brightness is restored, all i see is a Blank screen with the backlight on. Any Idea what thats happening? Thanks so much again! – thegreyspot Jul 20 '11 at 23:53
  • You might be increasing the brightness too much since it is supposed to be a value between 0 and 1. I recommend you first store the value of the original screen brightness (as a float/double) and then change the value. Then, when the phone is turned on, it can be returned to its original value. – A. Abiri Jul 21 '11 at 00:36
  • 1
    Also, setting a value of less than 0, sets the brightness to the default (preferred screen brightness). – A. Abiri Jul 21 '11 at 00:45
  • 1
    Thanks for your responses again! I tried using -1, 0, and using the variable that saved (getWindow().getAttributes().screenBrightness; earlier) to restore it, every time it returns to just a black screen with the back light on. Do you have any other suggestions maybe? – thegreyspot Jul 21 '11 at 02:46
  • I can't think of anything else that might work. Try looking at [this](http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#BRIGHTNESS_OVERRIDE_FULL) and [this](http://stackoverflow.com/questions/4803248/android-dim-screen-while-user-inactive) to help you out. – A. Abiri Jul 21 '11 at 05:04
  • Well you answered most of my question! htanks – thegreyspot Jul 21 '11 at 21:37
  • 1
    Your first method, choice one, requires DEVICE_POWER permission. – Osmium USA Jun 17 '13 at 22:20
  • Hi A. Abiri, is screenBrightness = 0 setting will work in BroadcastReceiver onReceive method ? it's not working for me. – Bipin Vayalu Sep 23 '13 at 19:52
  • DEVICE_POWER permission is only allowed if you created the Android ROM image. you need to sign your apk with the root rom signature key for DEVICE_POWER permission to be granted to you app.. it ain't gonna happen. – hamish Jun 02 '14 at 03:14
  • * Force the device to go to sleep. Overrides all the wake locks that are held. * * @param time is used to order this correctly with the wake lock calls. * The time should be in the SystemClock.uptimeMillis() time base. */ public void goToSleep(long time) { try { mService.goToSleep(time); } catch (RemoteException e) { } } usage: mService.goToSleep(SystemClock.uptimeMillis()); – hamish Jun 02 '14 at 03:19
  • The choice 2, It's not working. I can't turn off screen.. and The choice 3, It's not turn off screen, that's set brightness = 0. – ChickenVN91 Mar 25 '16 at 07:27
  • Do not forget `import android.view.WindowManager.LayoutParams;` – Jérémy Aug 22 '19 at 20:56
10

The following is copied from SDK document. If you want to keep screen on, I think SCREEN_BRIGHT_WAKE_LOCK is enough.


Flag Value                CPU   Screen  Keyboard

PARTIAL_WAKE_LOCK          On*    Off      Off

SCREEN_DIM_WAKE_LOCK       On     Dim      Off

SCREEN_BRIGHT_WAKE_LOCK    On     Bright   Off

FULL_WAKE_LOCK             On     Bright   Bright

RAPTOR
  • 124
  • 1
  • 11
jiangyan.lily
  • 932
  • 1
  • 8
  • 16
5

For me those methods didn't work. So I used other scenario (not trivial) to make my screen off.

Android has 2 flags that responsible to be awake:

  • Display --> Screen TimeOut
  • Application --> Development --> Stay awake while charging check box.

I used followed flow:

  1. 1st of all save your previous configuration, for example screen timeout was 1 min and Stay awake while charging checked.

  2. After, I uncheck Stay awake while charging and set screen timeout to minimal time.

  3. I register to broadcast receiver service to get event from android that screen turned off.

  4. When I got event on screen off, I set previous configuration to default: screen timeout was 1 min and Stay awake while charging checked.

  5. Unregister receiver

After 15 sec. device sleeps

Here is snippets of code:

BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Catch Screen On/Off
 * */
public class BroadcastReceiverScreenListener extends BroadcastReceiver{

private BroadCastListenerCallBackItf mBroadCastListenerCallBack = null;

public BroadcastReceiverScreenListener(
        BroadCastListenerCallBackItf broadCastListenerCallBack) {
    this.mBroadCastListenerCallBack = broadCastListenerCallBack;
}

@Override
public void onReceive(Context arg0, Intent intent) {


    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        mBroadCastListenerCallBack.broadCastListenerCallBack__ScreenOff_onResponse();
    }       
}

}

Interface used as callback

public interface BroadCastListenerCallBackItf {
    public void broadCastListenerCallBack__ScreenOff_onResponse();
}

2 methods from main class:

....

AndroidSynchronize mSync = new AndroidSynchronize();

....

public void turnScreenOff(int wait){
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);

    BroadCastListenerCallBackItf broadCastListenerCallBack = this;

    BroadcastReceiver mReceiver = new BroadcastReceiverScreenListener(broadCastListenerCallBack);       
    m_context.registerReceiver(mReceiver, filter);



    //set Development --> disable STAY_ON_WHILE_PLUGGED_IN
    Settings.System.putInt(
            m_context.getContentResolver(), 
            Settings.System.STAY_ON_WHILE_PLUGGED_IN,
            0                                );



    // take current screen off time 
    int defTimeOut = Settings.System.getInt(m_context.getContentResolver(), 
            Settings.System.SCREEN_OFF_TIMEOUT, 3000);
    // set 15 sec
    Settings.System.putInt(m_context.getContentResolver(), 
            Settings.System.SCREEN_OFF_TIMEOUT, 15000);

    // wait 200 sec till get response from BroadcastReceiver on Screen Off
    mSync.doWait(wait*1000);


    // set previous settings
    Settings.System.putInt(m_context.getContentResolver(), 
            Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);

    // switch back previous state
    Settings.System.putInt(
            m_context.getContentResolver(), 
            Settings.System.STAY_ON_WHILE_PLUGGED_IN,
            BatteryManager.BATTERY_PLUGGED_USB);


    m_context.unregisterReceiver(mReceiver);


}





public void broadCastListenerCallBack__ScreenOff_onResponse() {
    mSync.doNotify();
}

....

AndroidSynchronize class

public class AndroidSynchronize {

    public void doWait(long l){
        synchronized(this){
            try {
                this.wait(l);
            } catch(InterruptedException e) {
            }
        }
    }       

    public void doNotify() {
        synchronized(this) {
            this.notify();
        }
    }   

    public void doWait() {
        synchronized(this){
            try {
                this.wait();
            } catch(InterruptedException e) {
            }
        }
    }
}

[EDIT]

You need to register permission:

android.permission.WRITE_SETTINGS
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • 1
    tried your method, but it's important to mention that it require **android.permission.WRITE_SETTINGS**, which is otherwise not needed for 99% of apps. – Menion Asamm Jun 12 '13 at 07:25
  • What is the `main class`? Tried in my `MainActivity.java`, but `BroadCastListenerCallBackItf broadCastListenerCallBack = this;` failed. – Deqing May 11 '14 at 11:00
  • @Deqing be sure that `MainActivity implements BroadCastListenerCallBackItf` – Maxim Shoustin May 11 '14 at 12:42
  • thanks this is the same idea I came up with. during those 15 seconds I started a countdown timer so the user can set a WAKE lock if they want. and then remove the wake lock only when the POWER_CONNECTED event. – hamish Jun 02 '14 at 03:22
  • Nice solution! I have one question: Why in "mSync.doWait(wait*1000);" we have to wait a certain amount of time? I mean, why don't we wait until the broadcast receives the "screen off" signal and THEN release the wait so we can set the previous settings..etc? – Alberto Ursino Sep 11 '21 at 16:40
  • @lettomobile just an example, you can use `wait()` – Maxim Shoustin Sep 12 '21 at 12:49
2

Per this link, You can also turn the screen off like this:

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000);

1000 is in milliseconds which means 1 second, you can replace it with any value as desired.

Needed permission:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Community
  • 1
  • 1
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
  • Tried this, screen still takes around 10 seconds to go off. – Jyotman Singh Dec 19 '15 at 12:53
  • 2
    Although it does work you probably don't want to do this unless you also read the timeout and set the timeout back to it's original value afterwards; however if your app crashes for any reason at all you (or worse, the user) have a device in their hands that sleeps after one second (and can't change the setting anymore in that way to small amount of time) this setting also survives a reboot and you have a completely useless device (it was already difficult to reboot with this setting set...) – SanThee Dec 23 '15 at 16:43
  • This is really dangerous. How to turn the screen back to ON? – Mohamad Ghaith Alzin Oct 05 '22 at 05:20
  • Is it possible to handle screen touches when the screen is in off mode? – Mohamad Ghaith Alzin Oct 05 '22 at 05:21
-2

try - wakeLock.acquire(1000); // specify the time , it dims out and eventually turns off.

Ankish Jain
  • 11,305
  • 5
  • 36
  • 34
  • I believe you are talking about Screen time out, and it's not related to wakelock.acquire(1000); // wakelock is released after 1 second, then phone's screen time out is doing it's job. – Cԃաԃ Sep 05 '14 at 02:31