Robert Constantinescu
Robert Constantinescu

Reputation: 349

Android: How to turn on screen when new notification received?

I've tried almost everything and I can't understand how to turn on phone screen when new notification received in background mode.

I'm using FCM. When app is in background, notifications received are managed by system tray. How can I ask system tray to turn on the screen when something new received? Thank you!

Upvotes: 3

Views: 6361

Answers (2)

Robert Constantinescu
Robert Constantinescu

Reputation: 349

Finally, the answer is here.

If you are using Firebase API to send notifications from your server to device, remember that onMessageReceived() method from extended FirebaseMessagingService only calls in BACKGROUND if you send notifications like this:

                        $msg = array
                        (
                            'body'  => $newsObj['description'],
                        );
                        $fields = array
                        (
                            'registration_ids'  => $registrationIds,
                            'data'          => $msg,
                            'priority'  => "high"
                        );

You see, if you change that "data" property to "notification", onMessageReceived() method only will be called if the app is in FOREGROUND.

For turning screen on when new notification is received, put the following code into your onMessageReceived() method:

        // Turn on the screen for notification
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean result= Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isInteractive()|| Build.VERSION.SDK_INT< Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isScreenOn();

        if (!result){
            PowerManager.WakeLock wl = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MH24_SCREENLOCK");
            wl.acquire(10000);
            PowerManager.WakeLock wl_cpu = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MH24_SCREENLOCK");
            wl_cpu.acquire(10000);
        }

In AndroidManifest.xml:

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

That's all!

Upvotes: 8

Aniruddh Parihar
Aniruddh Parihar

Reputation: 3103

Try This One

you have to do one thing, when you are showing notification, you have to Broadcast this intent.after generating notification in onMessageReceived(RemoteMessage remoteMessage) method of FirebaseMessagingService extended class

Intent in=new Intent(Intent.ACTION_POWER_CONNECTED);
        getActivity().sendBroadcast(in);

Upvotes: 3

Related Questions