question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

onNotification not being triggered when app is killed

See original GitHub issue

I am experiencing a few issues that I would like some clarity on…

When sending a notification { ... } payload from the server, notifications come through but need some customization in order to come through properly.

Example payload sent from AWS SNS:

"notification": {
  "title": "Some title",
  "body": "Some message",
  "android_channel_id": "rn-push-notification-channel-id-4-default-300" <-- This one was odd but was the only way I could find to assign it to the appropriate channel
  "color": "#somehex" <-- Had to force this or the icon color in "Brief Notifications" would display as white
},
"data": {
  "route": "some route",
  "routeId": "route id"
}

Here is what I referenced to come up with that structure ⬆️ : https://firebase.google.com/docs/cloud-messaging/http-server-ref

With the above payload I am able to receive notifications in all app states (foreground/background/killed) but it was not triggering the onNotification which means I am unable to manually do anything when a notification is pressed.

Also, for some reason, the notification banner does not contain the app logo which is present when I presentLocalNotification.

When the payload is changed to a data-only payload, I get access to the onNotification function, however this causes a few problems.

Example payload sent from AWS SNS:

"data": {
  "title": "Some title",
  "message": "Some message"
  "route": "some route",
  "routeId": "route id"
}
  1. In my Android logs I get Cannot send to notification centre because there is no 'message' field in: Bundle[{userInteraction=false, id=707734631, data=Bundle[{message=Sample message for Android endpoints}], foreground=false}].
  2. Once the app is killed, notifications do not come through at all.

Here is some extra info:

AndroidManifest.xml

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

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

  <!-- start rn push notification -->
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <!-- end rn push notification -->

  <!-- file write permissions to save images -->
  <uses-permission android:name="READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="WRITE_EXTERNAL_STORAGE" />

  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/..." android:roundIcon="@mipmap/..." android:allowBackup="false" android:theme="@style/AppTheme">
    <activity android:name=".SplashActivity" android:theme="@style/SplashTheme" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:screenOrientation="portrait">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="..." />
      </intent-filter>
    </activity>

    <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:exported="true" android:screenOrientation="portrait" />

    <!-- start rn push notification -->
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService" android:exported="false">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>


    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_notification" />

    <meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false" />
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name" android:value="..." />
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description" android:value="..." />
    <!-- end rn push notification -->
  </application>
</manifest>

notifications.ts

import ApolloClient from 'apollo-client';
import {NormalizedCacheObject} from 'apollo-boost';
import RNPushNotification from 'react-native-push-notification';

const pushTokenCache: NotificationToken = {os: '', token: ''};

export const clearAllNotifications = () => {
  RNPushNotification.cancelAllLocalNotifications();
};

export const unregisterNotifications = () => {
  RNPushNotification.unregister();
  RNPushNotification.abandonPermissions();
};

export const notificationsEnabled = (): Promise<boolean> =>
  new Promise(resolve => {
    RNPushNotification.checkPermissions(({alert}) => resolve(Boolean(alert)));
  });

export const postPushToken = async (apolloClient: ApolloClient<NormalizedCacheObject>) => {
  ...
};

export const deletePushToken = async (apolloClient: ApolloClient<NormalizedCacheObject>) => {
  ...
};

const initializePushNotifications = (callback?: () => {}) => {
  RNPushNotification.configure({
    onRegister(token: NotificationToken) {
      pushTokenCache.os = token.os;
      pushTokenCache.token = token.token;

      callback && callback();
    },

    onNotification(notification: PushNotification) {
      if (notification.userInteraction) {
        ...
      }

      if (!notification.foreground) {
        RNPushNotification.localNotification({
          title: notification.data.title ?? 'Fallback Title',
          message: notification.data.message ?? 'Fallback message',
        });
      }
    },
    popInitialNotification: true,
    requestPermissions: true,
  });
};

export default initializePushNotifications;

App.tsx

import initializePushNotifications from 'services/notifications';
...

const App = () => {
  useEffect(() => {
    initializePushNotifications();
  }, []);

  return (...);
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:28

github_iconTop GitHub Comments

4reactions
alanlangloiscommented, Jul 28, 2020

Same here, the configure is not in a component. Works like a charm when the app is not killed (just set in background), but onNotification is not triggered when the app has been killed. Seeing the number of issues with “onNotification” I assume there is a problem here 😃

2reactions
TiavinaRakotobecommented, Jun 19, 2021

still getting this issue

Read more comments on GitHub >

github_iconTop Results From Across the Web

onNotification() is not fired when app is killed - Stack Overflow
I am not positive but when I remember correctly killing (alias force closing) an app disables the onNotification functionality in Android ...
Read more >
Push notification doesn't open specific screen when app is ...
I have a problem where I need to redirect user to specific post when he taps on notification, but that only works when...
Read more >
Events | Notifee
Please note, for iOS, the DELIVERED event is not fired for trigger notifications when the app is in the background. App open events....
Read more >
Notifications Not Shown - Mobile Push
Android App is Force Stopped. When an app is in a Force Stopped / Force Killed state most events including FCM messages for...
Read more >
Push.on('notification') not getting triggered when the app is killed
I want to trigger push.on('notification') method when I click on the notification when the application is not running, not even in ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found