1

I need to turn screen on from a service, I tried with this:

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

I have seen several posts and has not worked for me any, What do you recommend?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Afermin
  • 41
  • 4
  • Possible duplicate of [Android: How to turn screen on and off programmatically?](https://stackoverflow.com/questions/9561320/android-how-to-turn-screen-on-and-off-programmatically) – tir38 Jul 19 '19 at 18:15

1 Answers1

0

Try doing like this:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
        PowerManager.ACQUIRE_CAUSES_WAKEUP |
        PowerManager.ON_AFTER_RELEASE,
        "My Tag");
wl.acquire();

As wake locks are too dangerous, you must release it when it finish its job. In you case, register an receiver to listen Intent.ACTION_SCREEN_ON. Realize that this intent must be dynamically registered, i.e., you can not use it in a intent-filter in your AndroidManifest.xml.

In your service class:

private WakeLock mWakeLock; // Remember to use this field instead of wl in above code

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                if (mWakeLock != null && mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }
        }
    }
};

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

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver, filter);
}

And does not forget to add in your AndroidManifest.xml

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

Good luck!

Plinio.Santos
  • 1,709
  • 24
  • 31