Search code examples
javaandroideclipseoopwakelock

Screen not turning on with wake lock in Android


I have a foreground service that is waiting for a shake. When it receives that motion, it sends out a broadcast with:

Intent i = new Intent("com.company.app.shakeDetectedMessage");
sendBroadcast(i);

My main activity receives this with a broadcast receiver which implements the method:

@Override
    public void onReceive(Context context, Intent intent)
    {
        MainActivity.this.turnOnScreen();
        Toast.makeText(getApplicationContext(), "Screen ON", Toast.LENGTH_SHORT).show();
    }

And my turn on screen method:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

I have a partial wake lock with

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
    PowerManager.WakeLock mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorRead");
    mWakeLock.acquire();

declared in the service

Yet, when I turn my screen off and shake, the screen doesn't turn on! I verified that every method is working with logs. The onReceive is working even when the screen is off. The broadcast is working. Just the screen won't turn on!


Solution

  • call the acquire method of WakeLocker class

    Class :

    public abstract class WakeLocker {
        private static PowerManager.WakeLock wakeLock;
    
        public static void acquire(Context context) {
            if (wakeLock != null) wakeLock.release();
    
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
            PowerManager.ACQUIRE_CAUSES_WAKEUP |
            PowerManager.ON_AFTER_RELEASE, "WakeLock");
            wakeLock.acquire();
        }
    
        public static void release() {
            if (wakeLock != null) wakeLock.release(); wakeLock = null;
        }
    }
    

    Permission Required:

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