Skip to content

Foreground Notifications are not working #525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ravikumarpitla opened this issue Mar 10, 2020 · 27 comments
Closed

Foreground Notifications are not working #525

ravikumarpitla opened this issue Mar 10, 2020 · 27 comments

Comments

@ravikumarpitla
Copy link

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!

@dangkhoa2708
Copy link

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

@dangkhoa2708
Copy link

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

@glintpursuit
Copy link

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

@glintpursuit
Copy link

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 ?

@dangkhoa2708
Copy link

dangkhoa2708 commented Mar 17, 2020

<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());
}

}`

@ravikumarpitla
Copy link
Author

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

@dangkhoa2708
Copy link

dangkhoa2708 commented Mar 18, 2020

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

@xoapit
Copy link

xoapit commented Mar 21, 2020

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>

@glintpursuit
Copy link

<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 ?

@stevenyap
Copy link

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.

@gcoro
Copy link

gcoro commented Apr 1, 2020

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?

@gcoro
Copy link

gcoro commented Apr 1, 2020

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);
        // ...
    }

    // ...
}

@stale
Copy link

stale bot commented May 1, 2020

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

@stale stale bot added the 🏚 stale label May 1, 2020
@stale
Copy link

stale bot commented May 9, 2020

The issue has been closed for inactivity.

@stale stale bot closed this as completed May 9, 2020
@AugustoAleGon
Copy link

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

@tomriddle7
Copy link

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();
    }

@Bilal-Abdeen
Copy link
Contributor

Bilal-Abdeen commented Jul 29, 2020

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();
    }

A.2 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 on:
react-native: 0.63.2
react-native-notifications: 3.3.0

@CarlosIMartin
Copy link

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!

@mslipenchuk267
Copy link

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

@chris-rodgers
Copy link

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

@Shirco
Copy link

Shirco commented Apr 26, 2021

The solution works well but if some people don't want to edit the source code of the lib to have an easier maintainability, there is another solution.

As shown in the previous solution, the problem is not that the notification is not detected but that it is not posted so it doesn't appear in the Notification Bar. But the library still notify the JS code that a notification arrived. You can get this notification using Notifications.events().registerNotificationReceivedForeground. Then since you have the data of the notification, you can post a locale notification using Notifications.postLocalNotification.

Here is my solution:

  if (Platform.OS === 'android') {
    Notifications.events().registerNotificationReceivedForeground(
      (notification, completion) => {
        // Remote notification are not displayed when on Foreground
        // So we have to post a local notification
        Notifications.postLocalNotification(notification.payload);
        completion({
          alert: false,
          sound: false,
          badge: false,
        });
      },
    );
  }

Ios foreground notification works for me so that's why I only do it for the Android part but you can use it for both and adapt it

Bilal-Abdeen added a commit to Bilal-Abdeen/react-native-notifications that referenced this issue Jul 14, 2021
To fix issue wix#525 (wix#525), I did 2 changes below. 

``` 
    @OverRide
    public void onReceived() throws InvalidNotificationException {
        // 1. removed the following if/else statement
        // if (!mAppLifecycleFacade.isAppVisible()) {
        //     postNotification(null);
        //     notifyReceivedBackgroundToJS();
        // } else {
        //     notifyReceivedToJS();
        // }
        
        // 2. added the following 2 statements, instead of the if/else statement above 
        postNotification(null);
        notifyReceivedToJS();        
    }
```
@Bilal-Abdeen
Copy link
Contributor

@mslipenchuk267 @wixmobile,

It seems that this issue still exists in version 4.3.1!? Am I missing something?!

  1. The changes, which were suggested in my comment above, to AndroidManifest.xml are NOT necessary anymore. It seems that they have been included in the library's AndroidManifest.xml. This is good.

  2. It seems that the changes to the PushNotification.java file are still required to get the foreground notifications display in Android!

@ilight
Copy link

ilight commented Feb 6, 2023

@mslipenchuk267 @wixmobile,

It seems that this issue still exists in version 4.3.1!? Am I missing something?!

1. The changes, which were suggested in my [comment above](https://github.com/wix/react-native-notifications/issues/525#issuecomment-665983357), to `AndroidManifest.xml` are NOT necessary anymore. It seems that they have been included in the library's AndroidManifest.xml. This is good.

2. It seems that the changes to the `PushNotification.java` file are still required to get the foreground notifications display in Android!

This seems to be the fix (still on react-native v0.67.5) for me but I don't know how to keep updating this file as I run through a CI/CD pipeline. Any thoughts?

@Bilal-Abdeen
Copy link
Contributor

@ilight I have decided to use https://rnfirebase.io/messaging/usage and https://github.com/invertase/notifee, instead of this library.

@kg-currenxie
Copy link

kg-currenxie commented Feb 22, 2023

@ilight to keep the changes every time after yarn install, look at https://github.com/ds300/patch-package

@ilight
Copy link

ilight commented Feb 22, 2023

@ilight to keep the changes every time after yarn install, look at https://github.com/ds300/patch-package

Yes we eventually did our own patch for this which seems to be working

@korzonkiee
Copy link

In my case, in turned out that there were 2 packages (react-native-moengage & react-native-notifications) that were using FirebaseMessagingService to receive push notifications in the foreground.

However it seems that only one service will receive push notification and the precedence will take the service that is declared earlier/higher in the AndroidManifest.xml. You can find the final AndroidManifest.xml file (after merges) here app/build/intermediates/merged_manifests/<buildVariantName>/AndroidManifest.xml

Similar issues: #1, #2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests