ionic-team / capacitor-plugins

Official plugins for Capacitor ⚑️
485 stars 563 forks source link

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

Closed nschipperbrainsmith closed 3 years ago

nschipperbrainsmith commented 4 years ago

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)

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:

Other Information

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

jcesarmobile commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

@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 commented 4 years ago

@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 commented 4 years ago

Any update please ?

ga27 commented 4 years ago

Still waiting...

saricden commented 4 years ago

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:

I'm sending notifications from my server via FCM.

saricden commented 4 years ago

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 commented 4 years ago

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

casper5822 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

@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 commented 4 years ago

Is anyone working on this issue?

jcarignan commented 4 years ago

@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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 3 years ago

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 commented 3 years ago

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.

savgiannis commented 3 years ago

@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 commented 3 years ago

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

paragghadge commented 3 years ago

any update on this open bug, please?

ga27 commented 3 years ago

any update on this open bug, please?

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

yacut commented 3 years ago

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

rodrigorellana commented 3 years ago

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?

dvoraJDuarte commented 3 years ago

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?

savgiannis commented 3 years ago

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.

DarrenAllen commented 3 years ago

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

sertal70 commented 3 years ago

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! πŸ‘Œ
adamrz commented 3 years ago

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!

sertal70 commented 3 years ago

Hi @adamrz, as per answer to ionic-team/capacitor#3736 this plugin does not support background notifications on iOS

adamrz commented 3 years ago

@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

spencerfontein commented 3 years ago

Also looking for a solution so that pushNotificationReceived is executed when the app is in the background on iOS, any update about a plugin?

Linknpay commented 3 years ago

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.

Thank you so much. It helped me because I am using Pinpoint too and I was sending "data" in RawContent instead of "notification". Hope it will help other people using Capacitor + Pinpoint

harikvpy commented 3 years ago

Me too

anthonyjuarezsolis commented 3 years ago

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

anthonyjuarezsolis commented 3 years ago

remote.swift

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

spikeynick commented 3 years ago

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

EinfachHans commented 3 years ago

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

AntoniusGolly commented 3 years ago

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 commented 3 years ago

@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 commented 3 years ago

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

santekotturi commented 2 years ago

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

santekotturi commented 2 years ago

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 commented 2 years ago

@skotturi no we are still on v2