evollu / react-native-fcm

react native module for firebase cloud messaging and local notification
MIT License
1.73k stars 682 forks source link

Notification not showing when app is open #909

Closed sfm2222 closed 6 years ago

sfm2222 commented 6 years ago

I'm unable to show notification when app is open. I did that before and I know fcm library support it but I forgot how I did it last time without using local notification.

Currently I'm using standard method described in read me.

I've tried adding custom_notification in data payload along with the priority and show_in_foreground but nothing helped.

I'm able to show it using local notification but don't want to bcs I'm not sure how it will act in different scenarios. It can result in duplicate notification in certain cases.

showLocalNotification(notif) {
  FCM.presentLocalNotification({
    id: new Date().valueOf().toString(),         // (optional for instant notification)
    title: notif.title,      // as FCM payload
    body: notif.body,                // as FCM payload (required)
    show_in_foreground: true                     // notification when app is in foreground (local & remote)
  });
}
  FCM.on(FCMEvent.Notification, notif => {
  if (!notif.opened_from_tray) {
          this.showLocalNotification(notif);
      }
});
  1. What version of RN and react-native-fcm are you running?

        "react-native": "0.50.3",
    "react-native-fcm": "^10.0.3"
  2. What device are you using? (e.g iOS9 emulator, Android 6 device)? All devices android & iOS

  3. Is your app running in foreground, background or not running? foreground

evollu commented 6 years ago

try set priority: "high"

sfm2222 commented 6 years ago

@evollu already added it. Adding priority outside notification and data or inside nothing helped.


{                    to = deviceId,
                    badge = 0,
                    notification = new
                    {
                        title = "test",
                        body = "body", 
                        sound = "default",
                       // priority = "high",
                        badge = 0,
                      show_in_foreground = true,
                      //  content_available = true
                    },
                    data = new
                    {
                      //  custom_notification = new
                       // {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "Enabled",
                            fcmMessageType = notifType,
                            //priority = "high",
                                 show_in_foreground = true,
                            //  click_action = "fcm.ACTION.OPEN_NOTIFICATION",
                             //content_available = true
                       // }
                    },
                    content_available = true,
                   priority = "high",
                };
evollu commented 6 years ago

for android

{                    to = deviceId,
                    badge = 0,
                    data = new
                    {
                          custom_notification = new
                          {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "default",
                            fcmMessageType = notifType,
                            priority = "high",
                            show_in_foreground = true
                       // }
                    },
                    content_available = true
                };
sfm2222 commented 6 years ago

@evollu it's not working even :/

sfm2222 commented 6 years ago

@evollu The only way notification shows in foreground on both android and iOS is local notification. But on iPhone local notification is even showing multiple times. Sample project is also not showing notification in foreground. Tried using different payloads it didn't helped either.

Can you suggest any solution to this issue?

evollu commented 6 years ago

for iOS it creates notification automatically so calling local notification will just create another notification. what do you mean not working for the android payload?

sfm2222 commented 6 years ago

I mean for android & iOS it is not showing the notification from top when user is using the app. I've tried the following payloads:

  1. {                    to = deviceId,
                    badge = 0,
                    data = new
                    {
                          custom_notification = new
                          {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "default",
                            fcmMessageType = notifType,
                            priority = "high",
                            show_in_foreground = true
                        }
                    },
                    content_available = true
                };
  2. {                    to = deviceId,
                    badge = 0,
                    notification = new
                    {
                        title = "test",
                        body = "body", 
                        sound = "default",
                        priority = "high",
                        badge = 0,
                      show_in_foreground = true,
                    },
                    data = new
                    {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "Enabled",
                            fcmMessageType = notifType,
                            show_in_foreground = true,
                    },
                    content_available = true,
                   priority = "high",
                };
  3. {                    to = deviceId,
                    badge = 0,
                    notification = new
                    {
                        title = "test",
                        body = "body", 
                        sound = "default",
                        priority = "high",
                        badge = 0,
                      show_in_foreground = true,
                    },
                    data = new
                    {
    custom_notification = new
                          {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "Enabled",
                            fcmMessageType = notifType,
                            show_in_foreground = true,
    }
                    },
                    content_available = true,
                   priority = "high",
                };

But if it is local notification it displays the notification when user is using the app. For iOS it shows multiple.

evollu commented 6 years ago

payload 2 and 3 should work on iOS. can you add breakpoint on https://github.com/evollu/react-native-fcm/blob/master/Examples/simple-fcm-client/ios/SimpleFcmClient/AppDelegate.m#L65 and see if notification ever make to your phone?

sfm2222 commented 6 years ago

@evollu yes this lines get hit even alert(JSON.stringify(notif)) shows data but only notification don't shows while app is in use or open.

sfm2222 commented 6 years ago

@evollu UPDATE: For android it worked. iOS is required to still fix.

notification shows in android while app is in foreground using the below payload. I just removed the sound:"Enabled" and changed it to "default". I think my device was on silent mode and FCM can't change the sound settings and it just don't shows the notification.


{                    to = deviceId,
                    badge = 0,
                    notification = new
                    {
                        title = "test",
                        body = "body", 
                        sound = "default",
                        priority = "high",
                        badge = 0,
                      show_in_foreground = true,
                    },
                    data = new
                    {
  custom_notification = new
                          {
                            badge = 0,
                            title = "title",
                            body = "body",
                            sound = "default",
                            fcmMessageType = notifType,
                            show_in_foreground = true,
}
                    },
                    content_available = true,
                   priority = "high",
                };

But for iOS still notification not shows in foreground. Now I'm curious why is this happening. Can you explain the below lines bit bcs my code don't enter in this block while in foreground. Alert outside the block shows notification data in iOS.


 alert(JSON.stringify(notif)) //shows notification data. 

 if(Platform.OS ==='ios' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification){
      // this notification is only to decide if you want to show the notification when user if in foreground.
      // usually you can ignore it. just decide to show or not.
      notif.finish(WillPresentNotificationResult.All)
      return;
    }
evollu commented 6 years ago

sound: "Enabled" means "look for a sound called Enabled.mp3 and use it for notification sound, which will blow up notification

you say it doesn't go into the if condition. Can you show what was the actual value?

sfm2222 commented 6 years ago

@evollu this condition doesn't satisfy when iOS app is open notif._notificationType === NotificationType.WillPresent as notification type is remote notification. The iOS device I'm using for testing has OS version 9.

evollu commented 6 years ago

@sfm2222 finally .... iOS9 can't show foreground notification. it just get ignored

sfm2222 commented 6 years ago

I just noticed the OS version as well. I'll try on the latest version and will get back to you. Thank You. @evollu

UPDATE: it worked! Thanks

xstable commented 6 years ago

K, have now create a Request in Postman to trigger the Messages:

auswahl_723

This works as far, as the Object I've send arrived at my App and is written to console: auswahl_724

But after all, it will not display if the app is in foreground.

Here my manifest-File:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.schwarzenbergfestival">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
            android:name=".MainApplication"
            android:label="@string/app_name"
            android:icon="@mipmap/ic_launcher"
            android:allowBackup="false"
            android:theme="@style/AppTheme">
        <receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
        <receiver android:enabled="true" android:exported="true"
                  android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>
        <meta-data android:name="com.google.firebase.messaging.default_notification_icon"
                   android:resource="@mipmap/ic_notif"/>
        <service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
                android:windowSoftInputMode="adjustResize"
                android:launchMode="singleTop"
        >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
    </application>

</manifest>

The Device is Android 8.0. Any Idea, whats wrong here?

evollu commented 6 years ago

@xstable are you targeting SDK 26? if so you need to use SDK-26 branch and register notification channel

xstable commented 6 years ago

Yes, you're right, I have this build.gradlew:

android {
    compileSdkVersion 27
    buildToolsVersion "28.0.0 rc2"

    defaultConfig {
        applicationId "com.schwarzenbergfestival"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 3
        versionName "0.1-alpha"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
xstable commented 6 years ago

@evollu How can I register Notification-Channels?

evollu commented 6 years ago

@xstable there is example in SDK-26 branch https://github.com/evollu/react-native-fcm/blob/sdk-26/Examples/simple-fcm-client/app/App.js#L38

chris-ryu commented 6 years ago

@evollu After registering notification channel in my Galaxy A8 Android 8, notification banner still not showing. But Nexus Emulator 6 shows notification banner well.

AndroidManifest.xml

App.js FCM.createNotificationChannel({ id: 'ccon_channel', name: 'CCON Channel', description: 'used for ccon', priority: 'high' });

compileSdkVersion 27 targetSdkVersion 27 buildToolsVersion '27.1.1'

evollu commented 6 years ago

samsung has extra settings? I don't have samsung phone, does anyone else have the same issue?

jmxxii commented 5 years ago

This works for me! Nodejs Im using firebase-admin to send my notifications. My iOS pay load is: let userToken = token; let message = { notification: { title: title, body: body, type: notification_type, sound : "default", badge: "1", vibrate: "1" }, data: { type: notification_type, targetScreen: "details", show_in_foreground: "true", id: userID, offerID: offerId, job_status: job_status } } let options = { content_available: true, priority: "high" }

For Android the payload is the same except for my "message" variable:

message = { notification: { title: title, body: body, type: notification_type, sound : "default", badge: "1", vibrate: "1" }, data: { custom_notification: {'body': '${body}', 'title': ${title}, 'type': ${notification_type}, 'id': '${userID}', 'offerID': '${offerId}', 'job_status': '${job_status}', 'sound': 'default', 'color':'#00ACD4', 'priority':'high', 'icon':'ic_notif', 'group': 'GROUP','id': 'id', 'show_in_foreground': true , 'badge':'1'}, } }

customNotification only accepts strings so make sure to wrap your object in parens. Note: make sure when you interpolate, your strings are actual strings. (ex. var food = "milk" will sometimes output without quotation or commas. Hence why I used this method instead '${food}'

tany123 commented 4 years ago

I was also facing the same issue but after adding lines of code in manifest mentioned in this link https://rnfirebase.io/docs/v4.2.x/messaging/android#Update-Android-Manifest, I was able to listen to notification inside my App.js

Follow the android setup steps mentioned in the link

inside App.js

    // subscribe listner inside componentDidMount
componentDidMount() {
    const channel = new firebase.notifications.Android.Channel(
        'Your channel ID',
        'Channel Name',
        firebase.notifications.Android.Importance.Max
    ).setDescription('A natural description of the channel');
    firebase.notifications().android.createChannel(channel);

    // the listener returns a function you can use to unsubscribe
    this.notificationListener = firebase.notifications().onNotification((notification) => {

        if (Platform.OS === 'android') {

            const localNotification = new firebase.notifications.Notification({
                sound: 'default',
                show_in_foreground: true,
            })
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .android.setChannelId('Your channel ID') // e.g. the id you chose above
                .android.setSmallIcon('ic_notification_icon_white') // create this icon in Android Studio
                .android.setColor('#000000') // you can set a color here
                .android.setPriority(firebase.notifications.Android.Priority.High);

            firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

        } else if (Platform.OS === 'ios') {

            const localNotification = new firebase.notifications.Notification()
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .ios.setBadge(notification.ios.badge);

            firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

        }
    });
}

//Remove listeners allocated in createNotificationListeners()
componentWillUnmount() {
    this.notificationListener();
}