Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug: PushNotifications not triggering code within pushNotificationReceived (data notification) #200

Closed
1 task done
nschipperbrainsmith opened this issue Feb 4, 2020 · 66 comments · Fixed by #271
Closed
1 task done

Comments

@nschipperbrainsmith
Copy link

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)

  • 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: ionic-team/capacitor#1928 (comment)

@jcesarmobile
Copy link
Member

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.

@dibyendusaha
Copy link

dibyendusaha commented Mar 23, 2020

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.

@DimosthenisK
Copy link

@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
Copy link

2bona commented Apr 10, 2020

@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

@thameurr
Copy link

Any update please ?

@ga27
Copy link

ga27 commented May 5, 2020

Still waiting...

@saricden
Copy link

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.

@saricden
Copy link

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.

@saricden
Copy link

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

@casper5822
Copy link

casper5822 commented May 23, 2020

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.

@spikeynick
Copy link

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()

@booktechas
Copy link

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?

@casper5822
Copy link

casper5822 commented Jun 4, 2020

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)

@booktechas
Copy link

booktechas commented Jun 4, 2020

@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?

@booktechas
Copy link

Is anyone working on this issue?

@jcarignan
Copy link

jcarignan commented Jun 22, 2020

@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!

@mock5
Copy link

mock5 commented Jun 23, 2020

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.

@casper5822
Copy link

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

@ga27
Copy link

ga27 commented Jul 1, 2020

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.

@savgiannis
Copy link

savgiannis commented Jul 3, 2020

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?

@derbra1513
Copy link

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.

@booktechas
Copy link

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.

@ivancduran
Copy link

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

@ivancduran
Copy link

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 firebase/firebase-android-sdk#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.

@savgiannis
Copy link

@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.

@yacut
Copy link

yacut commented Aug 4, 2020

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 ionic-team/capacitor#1938 (comment) ionic-team/capacitor#1928 (comment)

@paragghadge
Copy link

any update on this open bug, please?

@ga27
Copy link

ga27 commented Sep 10, 2020

any update on this open bug, please?

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

@yacut
Copy link

yacut commented Sep 25, 2020

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

@rodrigorellana
Copy link

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?

@anthonyjuarezsolis
Copy link

2021 and the problem persists, pushNotificationReceived does not fire in the foreground or background.

@anthonyjuarezsolis
Copy link

remote.swift

remote.swift in which folder did you create it? @spikeynick

@spikeynick
Copy link

@anthonyjuarezsolis it is in the same directory as AppDelegate.swift

@EinfachHans
Copy link

Hey there, for anyone getting here, i recently created a Plugin which does support data Notifications: https://github.com/EinfachHans/capacitor-firebase-push :)

@AntoniusGolly
Copy link

AntoniusGolly commented May 16, 2021

For me it was a mistake how I perceived FCM messaging is working.

Disclaimer: may not apply to the issue here, but some people browsing here like me could benefit...

For me, too, background notifications where not working. I learnt the hard way that it was an error how I implemented sending the messages in the background. According to this explanation there is a difference between notifications and data messages. Data messages are not expected to be handled by pushNotificationReceived!

Data messages are handled by the client, ie. when app in foreground.

When App is in background, usually no background tasks are listening to messages (as I thought) but the operating system takes over. This is where Notifications come into play.

All I needed to do is to extend my message payload to this in backend:

const notificationPayload = {
    tokens: tokens,
    data: {
        title: "My Message Title",
        body: "This is a great content."
    },
    notification: {
        title: "My Message Title",
        body: "This is a great content."
    }
};

The data part is for handling in the foreground (client).
The notification part is for handling in the background (OS).

Works like a charm, even if app is totally killed.

@fromage9747
Copy link

@AntoniusGolly Hi, I have had mine configured this way since I started watching this issue. I cannot change the colour of the LED or even get the sound to be set. Unfortunately, it doesn't work for me.

Even having the ability to add actions to the notification like mark as read for example. Just can't get it done.

The idea behind it is that when the notification is received in the background and executes "pushNotificationReceived" you can then implement local notifications in order to manipulate the colour, sound and actions of the notification.

At least that is what it is meant to do, but as this issue states, nothing is triggered on "pushNotificationReceived"

I have always received the notification in the background.

@richardkshergold
Copy link

@AntoniusGolly are you getting the OnNotificationReceived event to trigger on iOS when your app is in the background?

@santekotturi
Copy link
Contributor

@spikeynick I've tried implementing your approach in capacitor v3 but haven't got it working. Have you migrated to v3?

@santekotturi
Copy link
Contributor

I also tried following Firebase's docs, they have an article on receiving notifications in the background on iOS but I can't get it working with capacitor:

https://firebase.google.com/docs/cloud-messaging/ios/first-message

@spikeynick
Copy link

@skotturi no we are still on v2

@kainosnoema
Copy link

After digging into this quite a bit today, I discovered that the Capacitor push-notifications plugin (even the latest) only implements the userNotificationCenter(_:willPresent:withCompletionHandler:) protocol, which only handles iOS notifications that are received when the app is fully in the foreground, regardless of whether they're data only or not: https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter.

It should be possible to also implement UIApplication's didReceiveRemoteNotification protocol, which receives remote notifications even while the app is running in the background (and not fully closed). This would solve a lot of the complaints I've seen around how the plugin handles notifications. As it is, we'll have to implement this ourselves and pass it to the plugin as a workaround.

@adamrz
Copy link

adamrz commented Aug 16, 2021

@kainosnoema I have been struggling with this for ages and not being a native Swift developer, I have been unable to get workarounds to function properly. Any insight on what you did/will do to implement this would be greatly appreciated!

@ajincentfit
Copy link

@kainosnoema I've also been struggling with wonky iOS notifications. Regular notifications come through fine, but trying to implement local notifications via push notifications to do actionable notifications is wonky. If you end up solving this, a fork would be much appreciated.

@kainosnoema
Copy link

@ajincentfit honestly we'll probably end up doing just that—I have quite a bit of native Swift experience so can pull it off with some time. Will keep you posted.

I love Capacitor in most areas, so it's kind of wild to me that something so critical and core to mobile development has such poor support here at v3. 😢

@askilondz
Copy link

Ok this needs to be fixed. Background notifications is a critical feature for pretty much any push notifications scenario... this plugin is almost useless without it...this has been my biggest hiccup with Capacitor 3. Everyone has to do workarounds to make this plugin work and almost a year later nothing has changed.

@RRGT19
Copy link

RRGT19 commented May 6, 2022

Still not working :(

Installed Dependencies:

  @capacitor/android: 3.5.1
  @capacitor/ios: 3.5.1
  @capacitor/cli: 3.5.1
  @capacitor/core: 3.5.1
  @capacitor/push-notifications: "^1.0.9",
  @capacitor-community/fcm: "^2.0.2",

@LouieSankey
Copy link

@kainosnoema did you ever find a solution for this?.. I've been trying to implement a custom IOS plugin to solve the issue but I'm not having any luck.

@kainosnoema
Copy link

@LouieSankey unfortunately no. We're still dealing with a reduced experience here. I have a feeling one of the reasons Ionic isn't fixing this is because Apple doesn't actually allow the embedded web view (WKWebView) to run or make network requests while in the background, so there's not much in the JS you could do with background push. I wish they'd clarify though as it's very confusing and surprising.

Your best bet is to probably handle background push and do whatever fetching/processing you need to do on the native side, and pass it back to the web view when the app is foregrounded and restored.

@terryjiang2020
Copy link

Looks like there is no solution for this as @theproducer closed it with a PR which added a doc claiming this issue is not going to be fixed.

@morsagmon
Copy link

I'm receiving background notifications, but not foreground. The pushNotificationReceived listener is not kicking in.
However, the pushNotificationActionPerformed is kicking in upon tapping the notification.
This is with Android on Samsung Galaxy A32 and Xiaomi Rednote 8.
Angular 13 Ionic 6.

Any updates on this?

@fromage9747
Copy link

@morsagmon I had given up on this but since my push notification token expired and I needed to find a method of refreshing it, it set me out to research this again.

From recent research, it would appear that in order for this to work your push notifications need to be data only.

When they are data only they are "silent". The app receives them but then you need to handle them with local notifications. Which isn't too much of an issue as this now gives you the ability to add action buttons to your notifications as well as many other cool features.

Another thing to add is that it's best to not bother with the built-in ionic/capacitor PushNotifications plugin as this does not give you anyway to refresh a token. The only way for the user to refresh the token is to uninstall and reinstall the app. Not very good UX. So instead make use of @capacitor-firebase/messaging. This comes with two methods that you will use to refresh the token. DeleteToken() and getToken(). I am still in the process of implementing this but it all looks quite promising.

@morsagmon
Copy link

@fromage9747 Thanks for the input.
Not sure I know what is the @capacitor-firebase/messaging.
I am following this scheme:
https://capacitorjs.com/docs/guides/push-notifications-firebase
It is just that the pushNotificationReceived listener is not kicking in.

I have no problem with the token not being refreshed in the background.
Sure will appreciate to see what you come up with once it's working.

@anthonyjuarezsolis
Copy link

Has anyone found a solution?

@fromage9747
Copy link

Yeah, forget about the built in push notifications from capacitor/Ionic. Use angular firebase messaging and only send data messages so that they are silent. These will work in the background and foreground. Then when the message is received, you launch a local notification through ionic which also gives you more functionality and control like action buttons.

@morsagmon
Copy link

The following works for me.
Capturing in foreground (app is in focus):

import {ActionPerformed, PushNotifications, PushNotificationSchema, Token} from '@capacitor/push-notifications';

PushNotifications.addListener(
      'pushNotificationReceived',
      async (notification: PushNotificationSchema) => {
        const data = notification.data.data; //data.learnerId , data.notificationCode, ...
        console.log('Push received: ' + JSON.stringify(notification));
        //What to do next. Notification received on the device.
        //alert('Push notification received: ' + notification);
        this.processNotificationReceived(JSON.parse(data), false);
      });

And this captures a tap on a notification that was received when the app is in the background:

    PushNotifications.addListener(
      'pushNotificationActionPerformed',
      async (notification: ActionPerformed) => {
        const data = notification.notification.data.data;
        console.log('Action performed: ' + notification.notification);
        console.log('data: ', data);        
        //What to do next. data holds all payload fields of the notification object. JSON structure: notification.notification.data.user.learnerId
        //notificationCode: 1=HelperInvitation; 2=HelperResponse; 3=ChatInvitation; 4=ChatMessage (not used); 5=HelperEvent; 9=NotificationMessage
        this.processNotificationReceived(JSON.parse(data));
      }
    );

The only problem I still have is with background notifications - they are received, but only showing a small icon in the upper status bar of the receiving machine, not popping up a visible message. The user must swipe down to reveal notifications, and there it is - ready to be tappable.

From what I learned, this is controlled by the visibility property of android in the notification payload, but I could not get this to work - here's my notification function in Firebase (triggered by RTDB insert record):

const functions = require("firebase-functions");
const admin = require('firebase-admin'); //required to access the FB RT DB
const serviceAccount = require("./<my-service-account-file>.json");
const tgjs = require("./tigergraph");
const cors = require('cors')({origin: true});

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "<my-rtdb-url>"
});


exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
    .onCreate(async (snapshot, context) => {

      const learnerId = snapshot.val().learnerId;
      const learnerDeviceId = snapshot.val().learnerDeviceId;
      const learnerName = snapshot.val().learnerName;
      const learnerImage = snapshot.val().learnerImage;
      const helperId = snapshot.val().helperId;
      const helperDeviceId = snapshot.val().helperDeviceId;
      const caseInvitationId = snapshot.val().caseInvitationId;
      const title = snapshot.val().title;
      const body = snapshot.val().body;
      const imageLink = snapshot.val().imageLink

      let objData = {
          learnerId: learnerId,
          learnerDeviceId: learnerDeviceId,
          learnerName: learnerName,
          helperId: helperId,
          helperDeviceId: helperDeviceId,
          caseInvitationId: caseInvitationId,
          imageLink: imageLink,
          notificationCode: "1"
      }

      functions.logger.log('Image URL ' , learnerImage);

      //Notification payload
      const payload = {
        token: helperDeviceId,
        notification: {          
          "title": title,
          "body": body,                    
          "image": learnerImage,
          // click_action: 'com.skillblaster.app.helperinvitationnotification' //Tag associated with triggering an activity on the helper's app when background notification
        },        
        data:{
          data: JSON.stringify(objData)
        },
        android:{
          "priority":"high",
          "notification": {
            "notification_priority": "PRIORITY_HIGH", 
            "default_vibrate_timings": true,
            "default_light_settings": true,
            //"visibility": firebase.messaging.NotificationAndroidVisibility.PUBLIC   // <<<=== NOT WORKING!!!
          }
        },
        apns:{
          "headers":{
            "apns-priority":"5"
          },
          payload: {
            aps: {
              'mutable-content': 1
            }
          },
          fcm_options: {
            image: learnerImage
          }
        },
        webpush: {
          "headers": {
            "Urgency": "high"
          }
        }
      };


      //    //Send the notification  
      functions.logger.log('In sendHelperInvitation. helperDeviceId: ' , helperDeviceId);
      functions.logger.log('In sendHelperInvitation. payload: ' , payload);
      return admin.messaging().send(payload);

    });

@ionitron-bot
Copy link

ionitron-bot bot commented Sep 30, 2022

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of the plugin, please create a new issue and ensure the template is fully filled out.

@ionitron-bot ionitron-bot bot locked and limited conversation to collaborators Sep 30, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.