Capacitor: bug: PushNotifications not triggering code within `pushNotificationReceived` (data notification)

Created on 4 Feb 2020  路  37Comments  路  Source: ionic-team/capacitor

Bug Report

A push notification send through firebase isn't triggering the code located within the addEventListener for pushNotificationReceived.

Capacitor Version

Installed Dependencies:
  @capacitor/cli 1.4.0
  @capacitor/core 1.4.0
  @capacitor/android 1.4.0
  @capacitor/ios 1.4.0

Affected Platform(s)

  • [X] Android
  • [?] iOS
  • [?] Electron
  • [?] Web

Current Behavior

Currently when a data notification is pushed through Firebase, to a device which is no longer in the foreground ( has been (non forcefully) killed by swiping it away in the recent application viewer):
The notification is handled by CapacitorFirebaseMessagingService#onMessageReceived yet it is never handled by the pushNotificationReceived within the application code (like it should according to the documentation).

The reason for this is the fact that PushNotifications#sendRemoteMessage expects the bridge to be set within: PushNotifications#getPushNotificationsInstance. This is however never the case as the plugin load method is not called as such the static staticBridge is never assigned. And the call is never relayed down to the application Typescript code.

Expected Behavior

I would expect the getPushNotificationsInstance method to initialize the application / load it so the staticBridge property is set. Otherwise the documentation will have to be updated to reflect the fact that listening for pushNotificationReceived only works when the application is active and the user hasn't (none forcefully) killed the app by swiping it away within the recent application viewer.

Sample Code

Notification we push to firebase:

{
    "to": "<<address>>",
    "data" : {
        "body" : "Body of Your Notification in data"
    },
    "priority": "high"
}

Code within the AppComponent

...
async initializePushNotificationListener() {
    console.debug("AppComponent#initializePushNotificationListener initializing notification listeners");
    await PushNotifications.register();
    console.debug("AppComponent#initializePushNotificationListener notification listeners registered");
    // On success, we should be able to receive notifications
    PushNotifications.addListener("registration", (token: PushNotificationToken) => {
        // tslint:disable-next-line:max-line-length
        console.debug(`AppComponent#initializePushNotificationListener Push registration success, token: ${token.value}`);
    });
    PushNotifications.addListener("registrationError",
        (error: any) => {
            alert("Error on registration: " + JSON.stringify(error));
        }
    );
    // Show us the notification payload if the app is open on our device
    PushNotifications.addListener("pushNotificationReceived",
        (notification: PushNotification) => {
            console.info("AppComponent#initializePushNotificationListener notification received", notification);
            LocalNotifications.schedule({
                notifications: [
                    {
                        title: "Title",
                        body: "Body",
                        id: 1,
                        schedule: {at: new Date(Date.now() + 1000 * 20)},
                        sound: null,
                        attachments: null,
                        actionTypeId: "",
                        extra: null
                    }
                ]
            }).catch(error => {
                console.debug("AppComponent#initializePushNotificationListener notifications denied", error);
            });
        }
    );
    // Method called when tapping on a notification
    PushNotifications.addListener("pushNotificationActionPerformed",
        (notification: PushNotificationActionPerformed) => {
            alert("Push action performed: " + JSON.stringify(notification));
        }
    );
}
...

Other Technical Details

npm --version output: 6.11.3
node --version output: 10.17.0

Tested on two different devices:

  • Sony Experia XZ3 (Android API version 29)
  • Samsung Galaxy Tab S2 (Android API version 24)

Other Information

Might relate to: https://github.com/ionic-team/capacitor/issues/1928#issuecomment-572607628

bug android

Most helpful comment

Still waiting...

All 37 comments

I've seen it work in the past, but I confirm is not working anymore. Once I open the app I get the notification data, but not while it's killed.

Is there any update regarding to this bug (or any workaround), otherwise planning to write plugin of my own, this is becoming real pain, as the app is not running (not forcefully killed), it is not performing any action inside _'pushNotificationReceived'_ event listener. One more request, if _setLargeIcon_ can be added to _LocalNotification_ plugin as well.

@2bona this is indeed not the place to ask. Nevertheless, you can use the api as needed without needing typescript... The api is exactly the same.

@2bona this is indeed not the place to ask. Nevertheless, you can use the api as needed without needing typescript... The api is exactly the same.

thank you very much, its just as u said the same thing

Any update please ?

Still waiting...

Guys not to sound like a tool but push notifications were one of the main things that led me to choose Capacitor for my project. The fact that they're not working as intended is a big let down.

The behaviour on my end sounds the same as other people noted above. When the app is closed or running in the background the pushNotificationReceived event is still being triggered, whereas I would expect it to only be triggered when the app is in the foreground. No notifications are being shown.

My dependencies are:

  • @capacitor/android 2.02
  • @capacitor/cli 2.02
  • @capacitor/core 2.02

I'm sending notifications from my server via FCM.

Oh I should note that sending notifications via the Firebase cloud messaging test page works as intended. It's only when my actual functions code is sending notifications that pushNotificationReceived fires even if in the background.

Sorry if I sounded like a jerk in my original post. I'm really impressed with Capacitor I was just frustrated.

Same problem, data push notification is not received when app is in background, only foreground and closed if i use notification type.
I have this configuration (ionic 4, angular 8):

"@capacitor/android": "^2.0.2",
"@capacitor/core": "2.0.2",
"@ionic-native/core": "^5.0.7"

We have a booking app, this problem is lethal because we have to confirm payments.

Hope you will fix the problem.

Tests made on a Samsung S7 Edge.

Best regards.

So I don't know if I was having the exact same issue as everyone else here is, but here's how I solved it. My issue was with iOS and I'm using FCM.
So I just wasn't getting any data notifications whether the app was open or not. So, at least for me, data notifications are being sent as Remote Notifications. First the Background Modes > Remote Notifications permission needs to be enabled. Then the remote notifications need to be handled. I added the following code to my AppDelegate.swift

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        NotificationCenter.default.post(name:Notification.Name("OnRemoteMessage"), object: userInfo);
        completionHandler(UIBackgroundFetchResult.newData)
    }

I also created a new local plugin I just added a file called remote.swift to my project:

import Capacitor

@objc(RemotePlugin)
public class RemotePlugin: CAPPlugin {

    public override func load() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.handleDataMessage(notification:)), name: Notification.Name("OnRemoteMessage"), object: nil)
    }

    @objc func handleDataMessage( notification: NSNotification) {
        let userInfo: [AnyHashable : Any]
        userInfo = notification.object as! [AnyHashable : Any]
        print("Entire message \(userInfo)")
        self.notifyListeners("OnRemoteNotification", data: ["data":userInfo])
    }
}

Finally from the TypeScript side of things I needed to register an OnRemoteNotification listener:

    import { Plugins, PushNotification, PushNotificationActionPerformed } from '@capacitor/core';
    const { PushNotifications, Device, RemotePlugin, App } = Plugins;

    ...

        RemotePlugin.addListener('OnRemoteNotification', (notification: object) => {
           console.log("ON REMOTE NOTIFICATION: "+notification);
           this._onMessage(notification);
           });


While not data notifications, I also had issues with regular alert push notifications while my app was in the background. I solved these issues by 1) registering a listener with PushNotificationActionPerformed and 2) when my app became active I checked PushNotifications.getDeliveredNotifications()

Just want to confirm the issue at my end.
Env: Ionic 5 + Capacitor 2 + capacitor-fcm to support topics.

We are going to upgrade several apps from Ionic 3 + cordova to Ionic 5 + Capacitor but this issue needs to be fixed first.

Foreground notifications works perfectly on both iOS and Android.
Background notifications works on iOS only.
Notifications when the app is closed does not work on iOS or Android.
When I click on the notification the app does not even open on Android, just iOS. But I do not see that pushNotificationReceived is called.

A note on Android and background. I see in logcat that when the app goes in the background the app closes completely after less then a second. So it may be the case that if works in background but I have not been abel to test it.

2020-06-04 13:13:35.674 /xxxxx D/Capacitor: App paused
2020-06-04 13:13:36.041 /xxxxx D/Capacitor/App: Firing change: false
2020-06-04 13:13:36.041 /xxxxx V/Capacitor/App: Notifying listeners for event appStateChange
2020-06-04 13:13:36.041 /xxxxx D/Capacitor/App: No listeners found for event appStateChange
2020-06-04 13:13:36.041 /xxxxx D/Capacitor: App stopped
2020-06-04 13:13:36.045 /xxxxx D/Capacitor: Saving instance state!

@casper5822 Quick question. What do you mean by "and closed if i use notification type". Is there anything special we have to do to make it work when the app is closed?

I use firebase and there are two types of push notifications: notification and data.

Data notifications work if the app is in foreground or background
Notification type works if app is in foreground, background and if the app is closed because it is handled by android and the system tray ( action fires if user tap the notification popup)

@casper5822 Thanks for the quick reply. Okey, yes,then I understand.
After a new test on iOS right now I can see that the I do get notification event when the app is closed.

When I click the notification on Android when the app is closed I see the following i logcat:
2020-06-04 13:41:25.156 xxxxx E/FirebaseMessaging: Notification pending intent canceled

Is that a clue for anyone?

Is anyone working on this issue?

@spikeynick I have the same exact issue.

DATA-ONLY message never triggered the "pushNotificationReceived" event on iOS. We spent days on this. Ended up doing basically the same thing as you did except more dirty, only for this scenario. Thanks for confirming the issue!

I was struggling for a while with the same issue. I was using Amazon Pinpoint to send a notifications for Android. Once I changed "Standard Message" to "Raw Message" it actually worked in the foreground and background.

This is the payload:

{
    "APNSMessage": {
        "aps": {
            "alert": ""
        }
    },
   "GCMMessage": {
    "notification": {
      "title": "Hello Android",
      "body": "From PinPoint"
    }
  },
    "ADMMessage": {
        "data" : {
            "message": ""
        }
    },
    "BaiduMessage": {
        "title":"",
        "description": ""
    }
}

Screen Shot 2020-06-23 at 2 13 47 PM

I hope that will help someone.

Today i made some tests with this configuration:
capacitor android 2.0.0
capacitor core 2.0.0
Samsungs s7 edge
Ionic 4
stewwan capacitor fcm plugin
I used firebase with topics mode

Data notifications work in
Foreground
Background
(Method onpushnotificationReceived is correctly called)
Notification type work in
Background
Closed

So it seems working for me. I don't know on Ios

If someone need a solution who works, switch to phonegap push plugin and send the notification with an API, in the post message dont use "notification" field, pass the title, body, and other fields of notifications in the "data" field. If you do that, it works.

I have the same issue in version 2.2.0 . Actually when I open the app after a data notification was received (while the app was on the background) I can see the data (via an alert) but the listener is not triggered while on background/killed mode. Will there be a fix in future versions?

Im having the same issues as many above, and perhaps its the way im implementing the plugin however I am receiving all notifications using FCM whether the app is killed, launched and in the background. But when the app is killed and the user receives a notification and then launches the app (opening from a hard close with splash screen launching etc.) I cannot grab the "getDeliveredNotifications()" to retrieve notification data. Specifically I am trying to grab the badge count for UI purposes.

Just to let you know, I found the solution for our problem. Maybe it will help someone else.
Since we are upgrading from an Ionic 3 + cordova + fcm environment we are using the same code for sending the remote notifications.

The problem was that we were adding "click_action": "FCM_PLUGIN_ACTIVITY" to the payload.
After removing that line the notifications works in all situations: open, background and closed on Android.

Hello everyone, I don't know if my problem its the same, but I think this can be related and definitely something is wrong with the push notifications on capacitor 2, I'm using capacitor and all the dependencies on version 2.2.1.

I'm just sending a simple message, without data and images and everytime when I sent a message my app crash in foreground and also in background, but only crash when I send a message from Firebase.

I'm just running the tutorial on android and the same code base to test the notifications, but doesn't work for me
https://capacitorjs.com/docs/guides/push-notifications-firebase

I have other applications on capacitor 1.4 and works very well, but I can't make this works on capacitor 2.2.1

Crash report:

````

2020-07-05 20:14:46.260 19419-19576/com.ottapp.app W/com.ottapp.app: Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist, reflection, allowed)
2020-07-05 20:14:46.260 19419-19576/com.ottapp.app W/com.ottapp.app: Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist, reflection, allowed)
2020-07-05 20:14:46.260 19419-19576/com.ottapp.app W/com.ottapp.app: Accessing hidden method Landroid/os/WorkSource;->size()I (greylist, reflection, allowed)
2020-07-05 20:14:46.260 19419-19576/com.ottapp.app W/com.ottapp.app: Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
2020-07-05 20:14:46.260 19419-19576/com.ottapp.app W/com.ottapp.app: Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
2020-07-05 20:14:46.273 19419-19419/com.ottapp.app D/AndroidRuntime: Shutting down VM

--------- beginning of crash

2020-07-05 20:14:46.274 19419-19419/com.ottapp.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ottapp.app, PID: 19419
java.lang.NoSuchMethodError: No static method zza()Lcom/google/firebase/iid/zzaz; in class Lcom/google/firebase/iid/zzaz; or its super classes (declaration of 'com.google.firebase.iid.zzaz' appears in /data/app/com.ottapp.app-A_pHs4E22R-1hcvUCu-BXw==/base.apk)
at com.google.firebase.messaging.FirebaseMessagingService.zza(com.google.firebase:firebase-messaging@@20.1.2:7)
at com.google.firebase.messaging.zzc.onStartCommand(com.google.firebase:firebase-messaging@@20.1.2:22)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4121)
at android.app.ActivityThread.access$1900(ActivityThread.java:220)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1915)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
2020-07-05 20:14:46.326 19419-19419/com.ottapp.app I/Process: Sending signal. PID: 19419 SIG: 9

Hello everyone, I fix my problem reading the firebase repo and please feel free to try if this can solve your problems with push notifications:

In my case the notification never arrived because the app crashes on background when I recive the message. this was a problem inside firebase-messaging:20.1.2 and is solved in 20.1.4

here is the source https://github.com/firebase/firebase-android-sdk/issues/1339

I did this to fix the problem:

change the version located in android/variables.gradle from 20.1.2 to 20.1.4

ext { minSdkVersion = 21 compileSdkVersion = 29 targetSdkVersion = 29 androidxAppCompatVersion = '1.1.0' androidxCoreVersion = '1.2.0' androidxMaterialVersion = '1.1.0-rc02' androidxBrowserVersion = '1.2.0' androidxLocalbroadcastmanagerVersion = '1.0.0' firebaseMessagingVersion = '20.1.4' playServicesLocationVersion = '17.0.0' junitVersion = '4.12' androidxJunitVersion = '1.1.1' androidxEspressoCoreVersion = '3.2.0' cordovaAndroidVersion = '7.0.0' }

Then in android studio go to "Files / Sync Project with Gradle Files", remove your app from your device, compile again and works very well on background.

I think the default version of firebase messaging will be updated on the next versions of capacitor, but that works for me.

This is only my case, please feel free to try and thank you for your comments.

@ivancduran Indeed it works well on background, but still it does not work when the app is killed. It is supposed to wake it up should it be a data notification.

I tested it with the latest firebase messaging version (20.2.4) and capacitor (2.4.0), it is still not working, when the app is killed/closed.
This bug makes it impossible to use push actions with capacitor on android, if I understood this correctly https://github.com/ionic-team/capacitor/issues/1938#issuecomment-646065568 https://github.com/ionic-team/capacitor/issues/1928#issuecomment-572607628

any update on this open bug, please?

any update on this open bug, please?

https://github.com/ionic-team/capacitor/issues/2401#issuecomment-652624407

@jcesarmobile do you plan to fix this in capacitor v2.x?

image
still does not work...

let's move back to cordova lol

I guess FLutter dev's have same issue

if it was working, then is android
android studio needs to update

does anyone try update all librares from the project?

While the app is open or in background the notifications arrive without any problem but when the app is killed the messages stop arriving, then you open the app again and you receive all the pushes that you could not see while the app was closed.

What should happen is that when the app is totally closed or killed it should be able to continue receiving push messages.

Any update?

hopefully they fix that in the separate notification plugin in the capacitor 3. I really need to trigger a local notification based on silent push notification payload but that is not currently possible.

+1 My needs are pretty much the same as sav's above.

Hi all, I'm in the process to migrate an app from Ionic3+Cordova to Ionic5+Capacitor. Today was time to add push notification functionality and unfortunately I run into this issue.

I read all comments and I think it's worth to share with you my experience:

1) my callback function does not get called even when the app is put in background only (that is without killing it)
2) the issue happens on both Android and iOS
3) on iOS I don't get any badge although I set the following configuration in capacitor.config.json:

    "PushNotifications": {
      "presentationOptions": [
        "badge",
        "sound",
        "alert"
      ]
    }

My environment:

$ npx cap doctor
馃拪   Capacitor Doctor  馃拪 

Latest Dependencies:

  @capacitor/cli: 2.4.2
  @capacitor/core: 2.4.2
  @capacitor/android: 2.4.2
  @capacitor/electron: 2.4.2
  @capacitor/ios: 2.4.2

Installed Dependencies:

  @capacitor/cli 2.4.0
  @capacitor/core 2.4.0
  @capacitor/ios 2.4.0
  @capacitor/android 2.4.0
  @capacitor/electron not installed

[success] Android looking great! 馃憣
  Found 3 Capacitor plugins for ios:
    @capacitor-community/camera-preview (1.0.4)
    cordova-plugin-audioinput (1.0.2)
    cordova-plugin-email-composer (0.9.2)
[success] iOS looking great! 馃憣

I've run into the same issue as many people here: pushNotificationReceived not firing with a data notification while in background on iOS.

@spikeynick Any chance you have you the local plugin you created on npm? I'm not sure how to go about creating one and it seems like you solved this! Any additional help on how to implement what you did is appreciated!

Hi @adamrz, as per answer to #3736 this plugin does not support background notifications on iOS

@sertal70 understood thanks for the link. I'm hoping @spikeynick can share more detail around his solution as he seems to have implemented something to address this while we wait on the Ionic team

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Kepro picture Kepro  路  3Comments

mlynch picture mlynch  路  3Comments

danielsogl picture danielsogl  路  3Comments

natevw picture natevw  路  3Comments

bogdbo picture bogdbo  路  3Comments