2

How can I turn off screen in Android from a Service?

I tried with a wakelock (with permission in manifest) but it doesn't work (screen doesn't turn off).

P.S. I don't want to use a dummy activity which set brightness to 0.

public class Servizio extends Service {


    PowerManager.WakeLock wl;

public class LocalBinder extends Binder {
    Servizio getService() {
        return Servizio.this;
    }
}

private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();


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

    wl.acquire();
    wl.release();

}

@Override
public void onDestroy() {
    super.onDestroy();
}
}
Yury
  • 20,618
  • 7
  • 58
  • 86
Angelo Tricarico
  • 1,333
  • 1
  • 19
  • 36
  • "P.S. I don't want to use a dummy activity which set brightness to 0." Why? – devsnd Mar 02 '12 at 11:08
  • it doesn't turn off screen immediately – Angelo Tricarico Mar 02 '12 at 11:54
  • 2
    You can play with the brightness for a turn off "effect" but as CommonsWare says you cannot really turn the screen off. You can refer to this question: http://stackoverflow.com/questions/6876471/how-to-dim-screen-to-zero-without-conflicting-with-flag-keep-screen-on – C.d. Mar 02 '12 at 13:38

1 Answers1

1

The device admin APIs (e.g., DevicePolicyManager) let you do this (e.g., lockNow()). However, the user has to enable you as a device administrator.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is this how apps such as the Phone app turn off the screen when you put the phone up against your ear? – Michael Jan 18 '19 at 18:43
  • @Michael: Built-in system apps like the phone app probably have other solutions. – CommonsWare Jan 18 '19 at 18:52
  • Huh, ok. It just seems tortuously difficult to so such a simple thing with differing opinions on how to even do it (with annoying suggestions that don't actually turn off the screen on all devices, such as reducing the brightness) with the best I have found being an app written in another language which looks pretty complicated for what seems like such a simple task... – Michael Jan 18 '19 at 18:59
  • @Michael: In general, turning the screen off is not an app's responsibility. Hence, while it may be a simple act from the user's standpoint, that does not mean there is a simple SDK solution for performing that act. – CommonsWare Jan 18 '19 at 19:01
  • seems like using PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK is what phone apps use... problem is, I can't get it to keep the screen to stay in its current state (off) when I release it, regardless of when I release it (proximity sensor near *or* far)! – Michael Jan 19 '19 at 05:39