invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.71k stars 2.22k forks source link

[Android][Notification] getInitialNotification cant get notification data #1190

Closed jindada closed 5 years ago

jindada commented 6 years ago

Issue

application is closed, click the notification, app run and call getInitialNotification only can get notificationId image but when application is running, get data success from onNotificationOpened

Environment

  1. Application Target Platform: Android
  2. Development Operating System: macOS Sierra
  3. Build Tools: Android Studio 3
  4. React Native version: 0.55.3
  5. RNFirebase Version: 4.1.0
  6. Firebase Module: FCM notification
chrisbianca commented 6 years ago

What is the content of the notification that you're sending?

jindada commented 6 years ago

I send a data message ( high-level ) through firebase console image

I didn't configure the registerHeadlessTask('RNFirebaseBackgroundMessage', function) and I received the message when app is close, after the configuration registerHeadlessTask('RNFirebaseBackgroundMessage', function), there is no change

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.soufeel.soufeel"
    android:versionCode="1"
    android:versionName="1.0">

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

    <application
      android:name=".MainApplication"
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">
      <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" />

      <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

      <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
      </service>

      <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
          <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
      </service>

      <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>

      <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
          <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_launcher" />

      <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:value="#000" />

      <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="default-channel"/>

      <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
        <intent-filter>
          <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
        </intent-filter>
      </receiver>
      <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>

    </application>

</manifest>
componentDidMount() {
    this.notificationListener = firebase.notifications().onNotification(e => {
      const notification = new firebase.notifications.Notification()
        .setNotificationId(e._notificationId)
        .setTitle(e._title)
        .setBody(e._body)
        .setSound('default')
        .android.setChannelId('default-channel')
        .android.setSmallIcon('ic_launcher')
        .android.setPriority(firebase.notifications.Android.Priority.High)      
        .setData(e._data);

      firebase.notifications().displayNotification(notification)
    });

    firebase.notifications().onNotificationOpened((notificationOpen) => {
      console.log(notificationOpen)
      firebase.notifications().removeDeliveredNotification(notificationOpen.notification._notificationId)
    });

    firebase.notifications().getInitialNotification()
      .then((notificationOpen) => {
        console.log(notificationOpen)
      });
  }
Salakar commented 6 years ago

@jindada can you show the content of your notification from the firebase console

Nitingadhiya commented 6 years ago

same issue in android device, when click to notification window that time getinitial method call but we have getting null response. when we click to notification. react-native V : 0.56.0 react: 16.4.1

ghost commented 6 years ago

any one with a solution ? i can't get this to work ;s

RobertFOConnor commented 6 years ago

seem to be getting a similar issue :/ works for ios tho

schecter22107 commented 6 years ago

Anyone get this to work for android??? pls

rheng001 commented 6 years ago

Same issue here for Android. When app is opened foreground/background I get notifications just fine with if (notificationOpen). When the app is closed and I reopen it and use getInitialNotification

async componentDidMount() {
  const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
  if (notificationOpen) {
      alert("Opened from closed app");
  }
  else{
    alert("Not opened from closed app")
  }
} 

It always goes into the else statement

vhuerta commented 6 years ago

Im getting the same problem, when i open the notification on android device onNotificationOpened is called but the notification has an empty body and also and empty title and data, this is the same when the app is completely closed getInitialNotification returns empty values too.

vhuerta commented 6 years ago

Any update on this?

Huzaifaak commented 6 years ago

+1 Need solution for this..

Huzaifaak commented 6 years ago

If you console.log(NotificationOpen) it just shows undefined

babara2 commented 6 years ago

Same issue here.

getInitialNotification() is not working as expected for android.

sibelius commented 6 years ago

When the notification is received the data value contains that notification data

However, when I click in the notification, the data is empty

this only happens when the app is opened

when the app is closed, when I click the notification data is still there

mattmoreira commented 6 years ago

I got stuck on this issue for the last 4 hours.

It turns out that you've gotta send the message with the data object outside the notification object, as exemplified below:

const MESSAGE_CONFIG = {
  to: FCM_TOPIC,
  content_available: true,
}

export interface IMessage {
  to: string,
  content_available: boolean,
  data: IData,
  notification: INotification
}

export interface IData {
  url: string,
}

export interface INotification {
  title: string,
  body: string,
}

async function sendNotification(notification: INotification, data?: IData) {
  const message = { ...MESSAGE_CONFIG, notification, data } as IMessage
  await fcm.send(message)
}

After this change, the data started to appear on the getInitialNotification method return.

SpaghettiC0des commented 6 years ago

I'm expieriencing this also. The payload is null when I tap on a notification, but when I close then open the app. I get the payload of the previously opened notification

jankrah12 commented 6 years ago

Any solution? Many have asked the question but there does not seem to be a solution in any of the threads. getInitialNotification() is still null on android

[edit] found some answers here: https://github.com/invertase/react-native-firebase/issues/1027#issuecomment-390557446

luisfuertes commented 6 years ago

+1 with "react-native-firebase": "4.3.8", "react-native": "0.54.0"

Any update?

FadiAboMsalam commented 5 years ago

@jankrah12 the referred solution worked with me perfectly as it was the splash screen which was the issue and as you referred to the solution adding

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

inside the SplashActivity.java it worked !

Big Thank You

Huzaifaak commented 5 years ago

For those who can't access body, title of notifcation when app is background or closed:

On Android, unfortunately there is no way to access the title and body of an opened remote notification. You can use the data part of the remote notification to supply this information if it's required.

introin commented 5 years ago

For android — Use data part to send title and body and then handle while showing message Ex

 const notificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            const { data } = notificationOpen.notification;
            this.showAlert(data.title,data.body);
        }
stale[bot] commented 5 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

MrEdinLaw commented 5 years ago

Bump? Still not working...

mikehardy commented 5 years ago

Show a clean reproduction, or make a PR and we can try to reproduce or we'll have a fix...

MrEdinLaw commented 5 years ago

@mikehardy i have fixed it by running the firebase.auth after the getInitialNotification

luisfuertes commented 5 years ago

But my app dont user firebase login. How can if ix?

mikehardy commented 5 years ago

If anyone has combined react-native-splash-screen with react-native-firebase, and they implemented the splash screen with a separate launch activity, this will happen. There are workarounds but you should use splash-screen with a single Activity and it just works. Code here: https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454

mikehardy commented 5 years ago

This is an unfocused discussion now, and after confirming that react-native-splash-screen (which is very common) can interfere with this and testing a workaround for it (linked above) I'm going to close this. If people still have problem please follow the issue template completely and (ideally!) post a reproduction repo on github

SathishSaminathan commented 5 years ago

https://github.com/invertase/react-native-firebase/issues/1108#issuecomment-427006332 Try this..

inceabdullah commented 4 years ago

Same issue here for Android. When app is opened foreground/background I get notifications just fine with if (notificationOpen). When the app is closed and I reopen it and use getInitialNotification

async componentDidMount() {
  const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
  if (notificationOpen) {
      alert("Opened from closed app");
  }
  else{
    alert("Not opened from closed app")
  }
} 

It always goes into the else statement

Shoud be Opened from closed app.

sadikyalcin commented 4 years ago

2 years on and I'm facing the same issue. There are multiple issues regarding this and I've yet to find a solution. It works fine for iOS.

I am now not even getting the notifications when the app is dead and getting the No task registered for key ReactNativeFirebaseMessagingHeadlessTask warning.

constructor(props, context) {
    super(props, context);
    this.state = {
        store: authStore.getState(),
    };

    messaging().onMessage(async remoteMessage => {
        if (remoteMessage) {
            console.log('@onMessage()');
            this.showAlert(remoteMessage);
        }
    });

    messaging().setBackgroundMessageHandler(async remoteMessage => {
        console.log('Message handled in the background!');
        //console.log(remoteMessage);
    });

    messaging().onNotificationOpenedApp(remoteMessage => {
        // not firing
        console.log('@onNotificationOpenedApp(): ', remoteMessage);
        if (remoteMessage) {
            console.log('@onNotificationOpenedApp()');
            this.showAlert(remoteMessage);
        }
    });

    messaging()
        .getInitialNotification()
        .then(remoteMessage => {
            console.log('@getInitialNotification(): ', remoteMessage); // null
            if (remoteMessage) {
                console.log('@getInitialNotification()');
                this.showAlert(remoteMessage);
            }
    });
}
marcoburrometo commented 4 years ago

@jankrah12 the referred solution worked with me perfectly as it was the splash screen which was the issue and as you referred to the solution adding

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

inside the SplashActivity.java it worked !

Big Thank You

Thank you, saved my life :)

MahmonirB commented 4 years ago

I have this issue in Android. I don't use splash screen. react-native: "0.62.2" react-native-firebase: "~5.6.0"

mikehardy commented 4 years ago

@MahmonirB RNFBv5 is definitely no longer seeing support, if it is still reproduced on current versions of messaging and/or full featured local device notification packages, we can look into it. It seems to be working for me in my work project, in combo with react-native-boot-splash

yashnerkar commented 9 months ago

@jankrah12 the referred solution worked with me perfectly as it was the splash screen which was the issue and as you referred to the solution adding

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

inside the SplashActivity.java it worked ! Big Thank You

Thank you, saved my life :)

@jankrah12 the referred solution worked with me perfectly as it was the splash screen which was the issue and as you referred to the solution adding

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

inside the SplashActivity.java it worked !

Big Thank You

Its 2024, and I am still getting the same error. Man, you saved my life 🫡. I was banging my head from last 2 days. Thank you!