React-native-notifications: Foreground Notifications are not working

Created on 10 Mar 2020  路  20Comments  路  Source: wix/react-native-notifications

Unable to receive foreground notifications on Android( didn't test on iOS ) with OS 10.
When app is minimized the notifications are working.
But the events are not being fired even I receive notification on background.
In foreground event is not getting fired and unable to receive notification.
Could anyone please suggest!

馃彋 stale

Most helpful comment

Being a newbie, it took me quite a while to understand the different suggestions mentioned by the experts above. Here is a summary of how I got it to work. A big thank you to all the experts above.

A. Edit the following file. Obviously, your changes will be lost if you reinstall/upgrade the React-Native-Notifications package. You might need to redo this step if the newly installed version still has this problem.
<YourProjectFolder>\node_modules\react-native-notifications\lib\android\app\src\main\java\com\wix\reactnativenotifications\core\notification\PushNotification.java

A.1 Remove the following:

    @Override
    public void onReceived() throws InvalidNotificationException {
        if (!mAppLifecycleFacade.isAppVisible()) {
            postNotification(null);
        }
        notifyReceivedToJS();
    }

Add the following.

    @Override
    public void onReceived() throws InvalidNotificationException {
        postNotification(null);
        notifyReceivedToJS();
    }

B. Update the following file
<YourProjectFolder>\android\app\src\main\AndroidManifest.xml

<manifest 
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.MyProject">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".MainApplication"
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:theme="@style/AppTheme">
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
            android:launchMode="singleTask"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>    
        </activity>

        <!-- You need to add the following <Service> section -->
        <service 
            android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" 
            android:exported="false"> 
            <intent-filter> 
                <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
            </intent-filter> 
        </service>

    </application>
</manifest>

This worked for me for:
react-native: 0.63.2
react-native-notifications: 3.3.0

All 20 comments

I'm experiencing the same issue for Foreground Notification on Android. It works on IOS, have you managed to fix it ?

Oh hey, I figured it out, you have to write your own MyFirebaseMessaging.java in Android Studio, and add it to Manifest. https://gist.github.com/jirawatee/85d4b46a89b9ae821b63c31f5d5189de, have a look at it

Foreground notification not working for Android.

I have checked the device logs & confirm message is received by app but event is not getting fire in RN.
D/RNFirebaseMsgService: onMessageReceived

Oh hey, I figured it out, you have to write your own MyFirebaseMessaging.java in Android Studio, and add it to Manifest. https://gist.github.com/jirawatee/85d4b46a89b9ae821b63c31f5d5189de, have a look at it

@dangkhoa2708 can you give one sample on how exactly you had resolved this issue ?

<service android:name=".MyFCMService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
I have a service named MyFCMService, and declared it in my Manifest. Here's mine, hope it helps
`public class MyFCMService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

    Log.d("MyFCMService", "From: " + remoteMessage.getFrom());

    if (remoteMessage.getData().size() > 0) {
        Log.d("MyFCMService", "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
        } else {
        }

    }

    if (remoteMessage.getNotification() != null) {
        Log.d("MyFCMService", "Message Notification Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification());
    }
}

private void sendNotification(RemoteMessage.Notification notification) {
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
            .setContentTitle(notification.getTitle())
            .setContentText(notification.getBody())
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent)
            .setContentInfo(notification.getTitle())
            .setLargeIcon(icon)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setSmallIcon(R.mipmap.ic_launcher);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                "channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT
        );
        channel.setDescription("channel description");
        channel.setShowBadge(true);
        channel.canShowBadge();
        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0, notificationBuilder.build());
}

}`

Hi @dangkhoa2708 ,
Thank you for the reply, I will work on as you suggested for android.
But for iOS, I am receiving deviceId(APNS Token) instead FCM token, Could you please help me to get FCM token.
I tried convert APNS to FCM token by using https://iid.googleapis.com/iid/v1:batchImport .
But always giving "error":"Not authenticated or unauthorized"
Could you please suggest

async register() { await messaging().registerForRemoteNotifications() if (Platform.OS == 'ios') { NativeModules.Workaround.getToken().then((e: string) => { console.log(e) }) } else { messaging() .getToken() .then((e: string) => { }) } }

I got FCM token using react-native-firebase v6. You can consult their site https://invertase.io/oss/react-native-firebase/v6/messaging/quick-start.

It got one error on IOS, so I did a trick with NativeModule as suggested on their GitHub issues. You might come across it, and I believe you can find it too. Or else, come back here lol :D

I added this code to subscribe to firebase service:
<service android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

<service android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

@xoapit
So you are able to get foreground notification to work ?

I added this code to subscribe to firebase service:
<service android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

I added this to my `/android/app/src/main/AndroidManifest.xml' and it works.

Oh hey, I figured it out, you have to write your own MyFirebaseMessaging.java in Android Studio, and add it to Manifest. https://gist.github.com/jirawatee/85d4b46a89b9ae821b63c31f5d5189de, have a look at it

Hi @dangkhoa2708, I added the class you made and it correctly displays notifications on foreground, thank you!!

But, after I added it to the manifest, I can't receive anymore the messages on the listener in the react native code, and I still need that to manage "silent" firebase notifications. How can I fix this?

But, after I added it to the manifest, I can't receive anymore the messages on the listener in the react native code, and I still need that to manage "silent" firebase notifications. How can I fix this?

Nevermind, fixed it. If anyone needs it, I just had to modify the class extending io.invertase.firebase.messaging.ReactNativeFirebaseMessagingService instead of com.google.firebase.messaging.FirebaseMessagingService

```
public class MyFirebaseMessagingService extends ReactNativeFirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// ...
}

// ...

}

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

The issue has been closed for inactivity.

I still have the same issue on Android. For RN 0.61.5

from ./node_modules/react-native-notifications/lib/android/app/src/main/java/com/wix/reactnativenotifications/core/notification/PushNotification.java

change this code

public void onReceived() throws InvalidNotificationException {
        if (!mAppLifecycleFacade.isAppVisible()) {
            postNotification(null);
        }
        notifyReceivedToJS();
    }

to

public void onReceived() throws InvalidNotificationException {
        postNotification(null);
        notifyReceivedToJS();
    }

Being a newbie, it took me quite a while to understand the different suggestions mentioned by the experts above. Here is a summary of how I got it to work. A big thank you to all the experts above.

A. Edit the following file. Obviously, your changes will be lost if you reinstall/upgrade the React-Native-Notifications package. You might need to redo this step if the newly installed version still has this problem.
<YourProjectFolder>\node_modules\react-native-notifications\lib\android\app\src\main\java\com\wix\reactnativenotifications\core\notification\PushNotification.java

A.1 Remove the following:

    @Override
    public void onReceived() throws InvalidNotificationException {
        if (!mAppLifecycleFacade.isAppVisible()) {
            postNotification(null);
        }
        notifyReceivedToJS();
    }

Add the following.

    @Override
    public void onReceived() throws InvalidNotificationException {
        postNotification(null);
        notifyReceivedToJS();
    }

B. Update the following file
<YourProjectFolder>\android\app\src\main\AndroidManifest.xml

<manifest 
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.MyProject">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".MainApplication"
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:theme="@style/AppTheme">
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
            android:launchMode="singleTask"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>    
        </activity>

        <!-- You need to add the following <Service> section -->
        <service 
            android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" 
            android:exported="false"> 
            <intent-filter> 
                <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
            </intent-filter> 
        </service>

    </application>
</manifest>

This worked for me for:
react-native: 0.63.2
react-native-notifications: 3.3.0

Being a newbie, it took me quite a while to understand the different suggestions mentioned by the experts above. Here is a summary of how I got it to work. A big thank you to all the experts above.

A. Edit the following file. Obviously, your changes will be lost if you reinstall/upgrade the React-Native-Notifications package. You might need to redo this step if the newly installed version still has this problem.
<YourProjectFolder>\node_modules\react-native-notifications\lib\android\app\src\main\java\com\wix\reactnativenotifications\core\notification\PushNotification.java

A.1 Remove the following:

    @Override
    public void onReceived() throws InvalidNotificationException {
        if (!mAppLifecycleFacade.isAppVisible()) {
            postNotification(null);
        }
        notifyReceivedToJS();
    }

Add the following.

    @Override
    public void onReceived() throws InvalidNotificationException {
        postNotification(null);
        notifyReceivedToJS();
    }

B. Update the following file
<YourProjectFolder>\android\app\src\main\AndroidManifest.xml

<manifest 
  xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.MyProject">
  <uses-permission android:name="android.permission.INTERNET" />
  <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <activity
          android:name=".MainActivity"
          android:label="@string/app_name"
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
          android:launchMode="singleTask"
          android:windowSoftInputMode="adjustResize">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>    
      </activity>

      <!-- You need to add the following <Service> section -->
      <service 
          android:name="com.wix.reactnativenotifications.fcm.FcmInstanceIdListenerService" 
          android:exported="false"> 
          <intent-filter> 
              <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
          </intent-filter> 
      </service>

  </application>
</manifest>

This worked for me for:
react-native: 0.63.2
react-native-notifications: 3.3.0

This solution works well, thanks for sharing!

@Bilal-Abdeen This was incredibly helpful! I followed everything in your comment and I am good now!

@Bilal-Abdeen Thanks for sharing, this also worked for me!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

omerman picture omerman  路  5Comments

Mimble-Wimble picture Mimble-Wimble  路  3Comments

WhereBeTheDan picture WhereBeTheDan  路  5Comments

veedeo picture veedeo  路  6Comments

ghost picture ghost  路  3Comments