Turn off screen on Android
Asked Answered
G

5

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.

Guidebook answered 20/7, 2011 at 3:43 Comment(1)
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!!!Lowery
G
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);
Gasconade answered 20/7, 2011 at 5:0 Comment(14)
In my experience these methods are highly unreliable.Polston
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 helpGuidebook
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!Guidebook
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.Gasconade
Also, setting a value of less than 0, sets the brightness to the default (preferred screen brightness).Gasconade
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?Guidebook
I can't think of anything else that might work. Try looking at this and this to help you out.Gasconade
Well you answered most of my question! htanksGuidebook
Your first method, choice one, requires DEVICE_POWER permission.Aetolia
Hi A. Abiri, is screenBrightness = 0 setting will work in BroadcastReceiver onReceive method ? it's not working for me.Jaguar
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.Compress
* 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());Compress
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.Thirsty
Do not forget import android.view.WindowManager.LayoutParams;Epicure
C
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

Coulson answered 20/7, 2011 at 3:59 Comment(0)
T
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
Tubercular answered 16/10, 2012 at 20:50 Comment(6)
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.Xanthein
What is the main class? Tried in my MainActivity.java, but BroadCastListenerCallBackItf broadCastListenerCallBack = this; failed.Joyjoya
@Joyjoya be sure that MainActivity implements BroadCastListenerCallBackItfTubercular
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.Compress
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?Deserve
@lettomobile just an example, you can use wait()Tubercular
D
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" />
Desireah answered 17/8, 2015 at 15:25 Comment(4)
Tried this, screen still takes around 10 seconds to go off.Drier
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...)Lowery
This is really dangerous. How to turn the screen back to ON?Tagliatelle
Is it possible to handle screen touches when the screen is in off mode?Tagliatelle
F
-2

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

Frogmouth answered 26/3, 2014 at 6:49 Comment(1)
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.Trossachs

© 2022 - 2024 — McMap. All rights reserved.