"react": "16.9.0",
"react-native": "0.61.5"
"@react-native-firebase/app": "^6.3.4",
"@react-native-firebase/messaging": "^6.3.4",
In Android if the app gets killed messaging().setBackgroundMessageHandler is not invoked.
So as of v6 notifications functionality is not available anymore I was planning to use react-native-firebase (only the messaging module) to get silent pushes and then using other lib to trigger a local notification to mimic react-native-firebase previous versions behaviour.
Btw I according to the doc messaging().setBackgroundMessageHandler is only available for Android.
How can I use react-native-firebase for getting notifications on iOS when the app is closed.
Thanks in advance.
Federico
import messaging from '@react-native-firebase/messaging';
export const firebasePushSetup = async () => {
await messaging().registerForRemoteNotifications();
const token = await messaging().getToken();
console.log('TOKEN =', token);
const granted = await messaging().requestPermission();
console.log('GRANTED =', granted);
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
return unsubscribe;
};
Click To Expand
#### `package.json`:
# N/A
#### `firebase.json` for react-native-firebase v6:
# N/A
### iOS
#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like:
# N/A
#### `AppDelegate.m`:
// N/A
Click To Expand
#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`:
// N/A
#### `android/app/build.gradle`:
// N/A
#### `android/settings.gradle`:
// N/A
#### `MainApplication.java`:
// N/A
#### `AndroidManifest.xml`:
<!-- N/A -->
Click To Expand
**`react-native info` output:**
OUTPUT GOES HERE
- **Platform that you're experiencing the issue on**:
- [ ] iOS
- [ ] Android
- [ ] **iOS** but have not tested behavior on Android
- [ ] **Android** but have not tested behavior on iOS
- [ ] Both
- **`react-native-firebase` version you're using that has this issue:**
- `e.g. 5.4.3`
- **`Firebase` module(s) you're using that has the issue:**
- `e.g. Instance ID`
- **Are you using `TypeScript`?**
- `Y/N` & `VERSION`
Think react-native-firebase
is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]
React Native Firebase
and Invertase
on Twitter for updates on the library.Could you show some code usage please?
Hi @Ehesp!
I code added under javascript title.
Btw I call the above code from a useEffect hook after the App module has been mounted.
Both messaging().onMessage() and messaging().setBackgroundMessageHandler() work as expected when the app is in foreground and in background respectively. As soon as I kill the app messaging().setBackgroundMessageHandler() stop responding.
As you can see the code aforementioned is based on the official doc (https://invertase.io/oss/react-native-firebase/v6/messaging/quick-start).
Am I missing something (like some service in the AndroidManifest.xml, although https://invertase.io/oss/react-native-firebase/v6/messaging/android does not say anything about it).
Cheers,
Federico
The setBackgroundMessageHandler
handler has to be created outside of your UI code. E.g:
// index.js
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
function App() {
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
return unsubscribe;
}, []);
// etc...
}
export default App;
@Ehesp thanks for your quick answer. Unfortunately I did what you suggested but it does not work either. See the code below:
index.js
import messaging from '@react-native-firebase/messaging';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
AppRegistry.registerComponent(appName, () => App);
I'm still able to get onMessage() and setBackgroundMessageHandler() when the app is in foreground and in background but no when it's killed in the case of the later one.
Cheers,
Federico
If you're killing your app via 'force stop' in the android apps UI then this is working as expected, force stopping an app there stops the app and all its running services.
Can you clarify what you mean by 'killed'
@Salakar indeed that's what I'm doing...
If that's the case then what's the option for the user to receive pushes if the app is closed (neither foreground nor background)?
App closed is not the same as app killed - if you swipe away your app from recents that is effectively closing the app - background messages will still continue to work after that.
Killing the app via force stop is not something the average user does on android to close an app, its a last resort thing.
@Salakar I'm sorry that I wasn't clear enough... With closing/killing the app I meant swiping the app off in the recent screen as you mentioned...
Once I do that the app stops receiving messages through messaging().setBackgroundMessageHandler().
Cheers,
Federico
What are you doing in the handler? If you're expecting to see a console log in your terminal it won't show there (its an isolated environment when running in the background). It may show in Android Studio Logcat though.
@Ehesp thanks for your comment! After reading your latest message I checked logcat and I found the cause of the error:
E/RNFirebaseMsgService: Background messages only work if the message priority is set to 'high'
So I included the priority set to high along with the data sent to FCM:
"priority": "high"
And I got it working!
Thank you very much for your help!
Btw the documentation provided is great but a working example will be highly appreciated by the users.
If you want I can submit a PR including a sample for them to use as a base for starting implementing the messaging module...
Cheers,
Federico
Awesome, yeah we're working through the docs at the moment (see https://github.com/invertase/react-native-firebase/issues/3217). I'll make sure this gets added :)
@federicomiralles What do you mean by checking logcat? Is that JS stack trace or the native android stack trace. And How to check logcat, is there any command for that?
@Kailash23 it's native Android tool for checking native logs.
The command is adb logcat provided you have the Android SDK envs set properly.
Check more details at https://developer.android.com/studio/command-line/logcat
@federicomiralles could you confirm where exactly you put the priority
key? Was it in the data
property:
{
tokens: [...],
data: {
priority: 'high',
}
}
Got it, in the android
key: https://firebase.google.com/docs/reference/admin/node/admin.messaging.AndroidConfig#priority
"Notification" messages are sent with a "high" priority by default, whereas data only are sent with "default".
@Ehesp it worked for me using this endpoint https://fcm.googleapis.com/fcm/send along with the following payload:
{
"to": "cjUyGxLa3pU...",
"data": {
"title": "Some title",
"body": "Some text"
},
"priority": "high"
}
Makes sense, thanks. Looks like the different API implementations are setup differently.
Thanks for the posts, everything works except that I got Invariant Violation: Module AppRegistry is not a registered callable module (calling startHeadlessTask)
error message in my logcat somehow. That happens after I swipe off my app and sending the data. Do I miss anything? I've set the priority
to high which helps me removing E/RNFirebaseMsgService: Background messages only work if the message priority is set to 'high'
error message.
I solved my problem, for those who use react native navigation make sure to call setBackgroundMessageHandler
outside of Navigation.events().registerAppLaunchedListener
@nastarfan
setBackgroundMessageHandler is not triggered even i put outside of Navigation.events().registerAppLaunchedListener.
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
Navigation.events().registerAppLaunchedListener(() => {
Navigation.setDefaultOptions({ ..... })
FYI I have documented this on the new docs setup, see #3217
@NweThazin what errors are you having?
Make sure you send data only message since that will not handle notification message with data payload. Also you need to set the priority
key to high
.
as of what @Ehesp pointed out, you can find more info on here (still WIP)
Hello everyone, I'd like to ask if this is a weird or expected behavior: I'm not seeing my setBackgroundMessageHandler
handler running but I can see that my app seems to start in Logcat everytime I send a notif.
I'm sending the notification using postman with this body {
"to" : "",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
},
"priority": "high"
}
I closed the app by swiping, and I'm currently idling my phone for 10 minutes just to see if there's any effect.
When you say "I'm not seeing my setBackgroundMessageHandler handler running", how are you checking whether it's running? It executes the code inside of its own task, so it wont act like a conventional log and show in the debugger.
I'm actually just expecting to see the console log message on the Logcat, I didn't check for errors and there don't seem to be any but I noticed that these services for zo0r/react-native-push-notification in my Manifest seem to be disrupting the background handler; without them the handler runs:
I am not knowledgable with native coding so I have no idea how to fix this or if it's a bug for this plugin or zo0r's; values are intended blank
Edit: I should have probably opened another issue for this
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" />
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name"
android:value=""/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description"
android:value=""/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@android:color/white"/>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<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.RNPushNotificationRegistrationService"/>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
@federicomiralles Where you call function firebasePushSetup.
I read document but not know how to call messaging().onMessage
Any updates about this issue? I have the same problem but with IOS, haven't tested Android yet. setBackgroundMessageHandler
is never triggered, I'm trying to get console.log message in the debugger and it never shows up.
There are no react-native-firebase problems right now with messaging on android or iOS that I know of, that do not either have a known workaround (#4299) or are simply an issue with operating system app lifecycle management making it impossible to open the app, so there are no updates that I know of
@Ehesp it worked for me using this endpoint https://fcm.googleapis.com/fcm/send along with the following payload:
{ "to": "cjUyGxLa3pU...", "data": { "title": "Some title", "body": "Some text" }, "priority": "high" }
I am getting this error: No task registered for key ReactNativeFirebaseMessagingHeadlessTask
I used priority too
Issue
"react": "16.9.0",
"react-native": "0.61.5"
"@react-native-firebase/app": "^6.3.4",
"@react-native-firebase/messaging": "^6.3.4",In Android if the app gets killed messaging().setBackgroundMessageHandler is not invoked.
So as of v6 notifications functionality is not available anymore I was planning to use react-native-firebase (only the messaging module) to get silent pushes and then using other lib to trigger a local notification to mimic react-native-firebase previous versions behaviour.
Btw I according to the doc messaging().setBackgroundMessageHandler is only available for Android.
How can I use react-native-firebase for getting notifications on iOS when the app is closed.Thanks in advance.
Federico
Project Files
Javascript
import messaging from '@react-native-firebase/messaging'; export const firebasePushSetup = async () => { await messaging().registerForRemoteNotifications(); const token = await messaging().getToken(); console.log('TOKEN =', token); const granted = await messaging().requestPermission(); console.log('GRANTED =', granted); messaging().setBackgroundMessageHandler(async remoteMessage => { console.log('Message handled in the background!', remoteMessage); }); const unsubscribe = messaging().onMessage(async remoteMessage => { console.log('FCM Message Data:', remoteMessage.data); }); return unsubscribe; };
Click To Expand
I am getting this error: No task registered for key ReactNativeFirebaseMessagingHeadlessTask
I used priority too
@Ehesp it worked for me using this endpoint https://fcm.googleapis.com/fcm/send along with the following payload:
{ "to": "cjUyGxLa3pU...", "data": { "title": "Some title", "body": "Some text" }, "priority": "high" }
I am getting this error: No task registered for key ReactNativeFirebaseMessagingHeadlessTask
I used priority too
Solved!!!
I just added the code :
messaging().setBackgroundMessageHandler() outside the Navigation.events().registerAppLaunchedListener()
Issue
"react": "16.9.0",
"react-native": "0.61.5"
"@react-native-firebase/app": "^6.3.4",
"@react-native-firebase/messaging": "^6.3.4",
In Android if the app gets killed messaging().setBackgroundMessageHandler is not invoked.
So as of v6 notifications functionality is not available anymore I was planning to use react-native-firebase (only the messaging module) to get silent pushes and then using other lib to trigger a local notification to mimic react-native-firebase previous versions behaviour.
Btw I according to the doc messaging().setBackgroundMessageHandler is only available for Android.
How can I use react-native-firebase for getting notifications on iOS when the app is closed.
Thanks in advance.
FedericoProject Files
Javascript
import messaging from '@react-native-firebase/messaging'; export const firebasePushSetup = async () => { await messaging().registerForRemoteNotifications(); const token = await messaging().getToken(); console.log('TOKEN =', token); const granted = await messaging().requestPermission(); console.log('GRANTED =', granted); messaging().setBackgroundMessageHandler(async remoteMessage => { console.log('Message handled in the background!', remoteMessage); }); const unsubscribe = messaging().onMessage(async remoteMessage => { console.log('FCM Message Data:', remoteMessage.data); }); return unsubscribe; };
Click To Expand
I am getting this error: No task registered for key ReactNativeFirebaseMessagingHeadlessTask
I used priority too
Solved!!!
I just added the code :
messaging().setBackgroundMessageHandler() outside the Navigation.events().registerAppLaunchedListener()
My code looks like this, copied from the docs:
```// index.js
import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
// Register background handler
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
AppRegistry.registerComponent('app', () => App);
```
I get "Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)" when I add the messaging() call here. The app works fine without the messaging call, but cannot receive notfications when app is killed. Everything works fine on iOS.
I do use react navigation, but don't use "Navigation.events().registerAppLaunchedListener()" anywhere.
anyone experienced this behavior?
Most helpful comment
@Ehesp thanks for your comment! After reading your latest message I checked logcat and I found the cause of the error:
E/RNFirebaseMsgService: Background messages only work if the message priority is set to 'high'
So I included the priority set to high along with the data sent to FCM:
"priority": "high"
And I got it working!
Thank you very much for your help!
Btw the documentation provided is great but a working example will be highly appreciated by the users.
If you want I can submit a PR including a sample for them to use as a base for starting implementing the messaging module...
Cheers,
Federico