Search code examples
androidwindowbroadcastreceiverwakelockandroid-wake-lock

getWindow() for Broadcast Receiver


I am trying to create a function to wake up my phone and unlock. For this I was using the getWindow() function, which do not work in BroadcastReceivers. How do I fix this? Any help would be appreciated!

public class ShakeToWake extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock mWakeLock = pm.newWakeLock((PowerManager.ACQUIRE_CAUSES_WAKEUP), "TapApp");
            mWakeLock.acquire();

            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            mWakeLock.release();
        }

}

Solution

  • Broadcast receivers don't need wakelocks- there's an implicit one in the Android framework, otherwise the OS couldn't call the BroadcastReceiver in the first place in order to run it and take a wakelock. Activities and Services are what need wakelocks. And Activities have windows, so it all works out.