Home » Android » java – How to make a screen wake up when a notification is received?

java – How to make a screen wake up when a notification is received?

Posted by: admin June 15, 2020 Leave a comment

Questions:

For my app I’m trying to get it where the notification wakes up the screen and displays a view from the app. I can’t figure how to get the app to wake up when its in a lock screen. I’ve tried a few things but none seem to work or they crash the app.

How to&Answers:

There is my solution:

createNotification(); //your implementation
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = Build.VERSION.SDK_INT >= 20 ? pm.isInteractive() : pm.isScreenOn(); // check if screen is on
if (!isScreenOn) {
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myApp:notificationLock");
    wl.acquire(3000); //set your time in milliseconds
}

More at PowerManager

Answer:

This BroadCastReceiver Works For, your App Is in back ground State/ mobile In lock mode. That time when notification is recieved i have to redirect particular screen, for that one i added Intent code,
After receiving Notification this code helps to your requirement

public class FirebaseDataReceiver extends WakefulBroadcastReceiver {

      private final String TAG = "FirebaseDataReceiver";

        public void onReceive(Context context, Intent intent) {
            PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
            boolean isScreenOn = pm.isScreenOn();
            if(isScreenOn==false)
            {
                PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MyLock");
                wl.acquire(10000);
                PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyCpuLock");

                wl_cpu.acquire(10000);
            }
           //Redirect particular screen after receiving notification, this is like ola driver app concept accepting driver request
            intent = new Intent(context, MyTicketListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        }
    }