How to setup FCM Push Notification with React Native…
If you are new to firebase and FCM this article will be useful to setup FCM Push Notification with React Native application. We will be using react-native-firebase(doc: https://rnfirebase.io/docs/v5.x.x/getting-started) module to retrieve token for the push notifications.
Prerequisites
First, create the Firebase account and download the google-services.json
file from the console.
- Access your firebase account and go to the project settings from the top gear icon.
- Create an app if you don’t have it already.
- Go to the Cloud Messages section and add a server key
- Download the
google-services.json
file from the General Page(refer 2nd point). Copy the google-services.json to theandroid/app/
folder of your react-native project.
Configuring react-native-firebase modules
If you can visit the documentation you will be able to follow the steps. But I’m gonna add here the specific steps that you need to setup it in Android application.
1. Install the library
npm install --save react-native-firebase // or yarn add react-native-firebase
2. Add gradle dependency under android/app/build.gradle
dependencies { // ... implementation "com.google.android.gms:play-services-base:16.0.1" implementation "com.google.firebase:firebase-core:16.0.7" implementation "com.google.firebase:firebase-messaging:17.4.0" }
Check for the existing first two lines of the dependencies and choose the correct library for it. You can use following mvn repositories to find the correct version
When finding the peer version, try to match it with the release date since most are working properly within a particular period of releases.
3. Add the RNFirebaseMessagingPackage to your android/app/src/main/java/com/[app name]/MainApplication.java
// ... import io.invertase.firebase.RNFirebasePackage; import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line public class MainApplication extends Application implements ReactApplication { // ... @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNFirebasePackage(), new RNFirebaseMessagingPackage() // <-- Add this line ); } }; // ... }
4. Update android manifest file.
<application ...> <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <!-- For background messaging --> <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" /> </application> //For RNFB versions less than 5.2.0 only; add the instance ID service: <application ...> <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application>
Finally try build the application with above configurations
Troubleshooting
Most of the time you will get an error like following.
The library com.google.android.gms:play-services-basement is being requested by various other libraries at [[15.0.1,15.0.1]], but resolves to 16.1.0.Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.
If you get the different version error and check whether you have strict versions in the android/build.gradle
def googlePlayServicesVersion = '15.0.1' configurations.all { resolutionStrategy { eachDependency { DependencyResolveDetails details -> if (requested.group == 'com.google.android.gms') { details.useVersion "$googlePlayServicesVersion" } Obsolete under new firebase if (requested.group == 'com.google.firebase') { details.useVersion "$googlePlayServicesVersion" } } } }
This will set the google.android.gms version to be strict to a defined version.
Comment it out if you want it to use the versions of your modules and use the module version defined of the the android/app/build.gradle file.
Still if you get this error add the following line to the bottom of the android/app/build.gradle
file. But I highly urge you not to do so. But it can be tolerated since there arent any mediator who controls the versions of the modules that we use. Maybe we should have something like that in future.
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
Implementing FCM Push Notification with React Native.
Go to your codebase and add following.
import firebase, { Notification, RemoteMessage } from 'react-native-firebase'; // add following code to an appropriate place. // implement notifications as needed if (Platform.OS === 'android') { try { const res = await firebase.messaging().requestPermission(); const fcmToken = await firebase.messaging().getToken(); if (fcmToken) { logger.log('FCM Token: ', fcmToken); const enabled = await firebase.messaging().hasPermission(); if (enabled) { logger.log('FCM messaging has permission:' + enabled) } else { try { await firebase.messaging().requestPermission(); logger.log('FCM permission granted') } catch (error) { logger.log('FCM Permission Error', error); } } firebase.notifications().onNotificationDisplayed((notification: Notification) => { // Process your notification as required // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification. logger.log('Notification: ', notification) }); this.notificationListener = firebase.notifications().onNotification((notification: Notification) => { logger.log('Notification: ', notification) }); } else { logger.log('FCM Token not available'); } } catch (e) { logger.log('Error initializing FCM', e); } }
Background Notifications
If you need to display background notifications, you will have to add following HeadlessTask on index.js
file of your codebase.
import { AppRegistry } from 'react-native'; import App from './App'; import firebase, { RemoteMessage } from 'react-native-firebase'; // Move to a proper place const handleFCMNotification = async (message: RemoteMessage) => { console.log('FCM OFFLINE: ', message); return Promise.resolve(); } AppRegistry.registerComponent('myapp', () => App);// your main app component // FCM background message task AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => PushNotificationService.handleFCMNotification);
How to Test
Go to your Firebase Console and go to the Cloud Messaging under Grow section.
Then select Send Your First Message.
Add test title and notification text, which is the message body. Click on Send Test Message
Add the token retrieved from the frontend logs when running your app.
Fill the other details and click on Review and Then Publish.
This message should be then appearing on the intended device as a notification.
Troubleshooting
You might get following error when requesting the token or any Firebase FCM Push Notification with React Native.
The [[DEFAULT]] firebase app has not been initialized!
Solved the issue by removing xmlns:tools="http://schemas.android.com/tools"
and tools:node="replace"
from AndroidManifest.xml. It should be two lines in separate places.
More
If you are into react native, feel free to check this tutorial on configuring AWS AppSync Graphql for react-native apps
123 COMMENTS
Thanks for the post!
I´m having an issue with my implementation adn I was waodering if you could help.
The issue is that on any of the receiving notification events I get title and body undefined, even with notifications with payload. Do you have any clue?
Hey sorry for the late reply. If you had tested using the firebase test it should have the both title and the body.
Thank you for the thorough and well-written tutorial.
(y) thanks!
I have my notification records in Salesforce. Do I still need to do this even I’m not sending notifications from firebase?
Well, um not sure whether you will need it for salesforce. You dont need to apply any of this if you are not using notifications.
[…] How to setup FCM Push Notification with React Native App JDK 14 – The new features in Java 14 Coder Kai A humble developer android heap heap limit allocation failed ios memory node react-native […]
I think other web site proprietors should take this website as an model, very clean and fantastic user genial style and design, as well as the content. You are an expert in this topic!
whoah this blog is wonderful i love reading your posts. Keep up the great work! You know, many people are hunting around for this info, you can aid them greatly.
I believe that avoiding ready-made foods could be the first step to help lose weight. They may taste fine, but highly processed foods include very little vitamins and minerals, making you try to eat more only to have enough electricity to get through the day. Should you be constantly eating these foods, converting to whole grains and other complex carbohydrates will let you have more energy while taking in less. Good blog post.
Thank you for another excellent article. Where else could anybody get that kind of information in such a perfect way of writing? I have a presentation next week, and I’m on the look for such information.
Best view i have ever seen !
Cialis Onadron
The Preschool Academy 2800 Atlanta Hwy 353-8183 buy cialis online in usa
Lu HH, Li Q, Xu BH, Zhang P, Yuan P, Wang JY, Cai RG lasix not urinating Carefully observe patient for serotonin syndrome during treatment initiation and dose adjustment
MBD was identified as a risk factor for breast cancer before it became widely used to measure density at the time of screening nolvadex pct for sale
I think this is one of the most significant information for me.
And i am glad reading your article. But want to remark on some general things, The site style is great, the articles is
really great : D. Good job, cheers
viagra cialis online We quantified the expression of selected genes by real time PCR using SYBR Green as the detection method and the Step One sequence detection system Applied Biosystems Inc
Your article is a great example of how storytelling can be used to convey important messages. Thank you for sharing your story with us.
I appreciate the practical solution that you have offered in this article.
I agree with many of the points you made in this article and appreciate your perspective.
very informative articles or reviews at this time.
I love how you combined your knowledge and experience in this article.
I like how you emphasize the importance of this topic in this article.
Your article is a valuable resource for anyone interested in this topic. I appreciate the way you presented the information in a well-structured and concise manner.
I am very impressed with the knowledge and research you put into writing this article.
price medication
canadian pharmacy prednisone
onlinepharmacy.com
Your article is a valuable resource for anyone interested in this topic. I appreciate the way you present the information in a way that is both informative and easy to understand.
ダッチワイフ 本物のダッチワイフは20年後に何に似ていますか?なぜ男性の性的パートナーを過ぎた膨脹可能な大人のおもちゃ?セックス人形を利用することの健康上の利点はネチズンのアーティキュレーションを説明しました:セックス人形は私の人生を変えました
Al great deal for a web developer. Details: https://zetds.seychellesyoga.com/var_montero
Al great deal for a web developer. Details: https://zetds.seychellesyoga.com/var_montero
Al great deal for a web developer. Details: https://zetds.seychellesyoga.com/var_montero
The offer is still valid. Details https://zetds.seychellesyoga.com/jml
Content for your website https://zetds.seychellesyoga.com/info
Web Development Wizards https://zetds.seychellesyoga.com/info
Can provide a link mass to your website https://zetds.seychellesyoga.com/info
Your site’s position in the search results https://zetds.seychellesyoga.com/info
Free analysis of your website https://zetds.seychellesyoga.com/info
Content for your website https://zetds.seychellesyoga.com/info
Web Development Wizards https://zetds.seychellesyoga.com/info
Can provide a link mass to your website https://zetds.seychellesyoga.com/info
Your site’s position in the search results https://zetds.seychellesyoga.com/info
Free analysis of your website https://zetds.seychellesyoga.com/info
SEO Optimizers Team https://zetds.seychellesyoga.com/info
I offer mutually beneficial cooperation https://zetds.seychellesyoga.com/info
Cool website. There is a suggestion https://zetds.seychellesyoga.com/info
I really liked your site. Do you mind https://zetds.seychellesyoga.com/info
Here’s what I can offer for the near future https://zetds.seychellesyoga.com/info
You will definitely like it https://zetds.seychellesyoga.com/info
Content for your website https://ztd.bardou.online/adm
Web Development Wizards https://ztd.bardou.online/adm
Can provide a link mass to your website https://ztd.bardou.online/adm
Your site’s position in the search results https://ztd.bardou.online/adm
Free analysis of your website https://ztd.bardou.online/adm
SEO Optimizers Team https://ztd.bardou.online/adm
I offer mutually beneficial cooperation https://ztd.bardou.online/adm
Cool website. There is a suggestion https://ztd.bardou.online/adm
I really liked your site. Do you mind https://ztd.bardou.online/adm
Here’s what I can offer for the near future https://ztd.bardou.online/adm
Content for your website https://ztd.bardou.online/adm
Web Development Wizards https://ztd.bardou.online/adm
Can provide a link mass to your website https://ztd.bardou.online/adm
Leave a comment and let us know what your favorite blog post has been so far!
Your site’s position in the search results https://ztd.bardou.online/adm
Free analysis of your website https://ztd.bardou.online/adm
SEO Optimizers Team https://ztd.bardou.online/adm
I offer mutually beneficial cooperation https://ztd.bardou.online/adm
Cool website. There is a suggestion https://ztd.bardou.online/adm
Content for your website http://myngirls.online/
Web Development Wizards http://myngirls.online/
Can provide a link mass to your website http://myngirls.online/
Your site’s position in the search results http://myngirls.online/
Free analysis of your website http://myngirls.online/
This is my first time pay a quick visit at here and i am really happy to read everthing at one place
SEO Optimizers Team http://myngirls.online/
I offer mutually beneficial cooperation http://myngirls.online/
Content for your website http://fertus.shop/info/
Web Development Wizards http://fertus.shop/info/
Can provide a link mass to your website http://fertus.shop/info/
Your site’s position in the search results http://fertus.shop/info/
Free analysis of your website http://fertus.shop/info/
SEO Optimizers Team http://fertus.shop/info/
I offer mutually beneficial cooperation http://fertus.shop/info/
Cool website. There is a suggestion http://fertus.shop/info/
I really liked your site. Do you mind http://fertus.shop/info/
Here’s what I can offer for the near future http://fertus.shop/info/
ProDentim – unique blend of probiotics and essential nutrients offers a natural and effective way to promote and maintain healthy teeth and gums. With its carefully selected probiotic strains and essential nutrients, ProDentim provides a comprehensive approach to dental health that can help reduce the risk of dental problems and support overall oral health.
You will definitely like it http://fertus.shop/info/
The best prices from the best providers http://fertus.shop/info/
Additional earnings on your website http://fertus.shop/info/
Puravive is a unique supplement, totally different from anything you’ve tried. It has a special mix of eight unique plants and nutrients carefully picked to fix a new reason for unexpected weight gain and low BAT levels. Making BAT levels go up even a bit means your body can burn many more calories, making your metabolism super active, like a machine burning fat and boosting your energy.
Analytics of your website http://fertus.shop/info/
I have been struggling with this issue for a while and your post has provided me with much-needed guidance and clarity Thank you so much
I would like to post an article http://fertus.shop/info/
How to contact the administrator on this issue http://fertus.shop/info/
Alpilean proudly boasts a chemical-free, stimulant-free, and preservative-free formula, ensuring a secure and natural choice for those seeking weight loss solutions. Its composition makes it a safe and wholesome option for all individuals. Moreover, seamlessly integrating Alpilean into your daily routine is a breeze, requiring just two capsules a day. Since it collaborates harmoniously with your body’s innate processes, rest assured, there’s no need to fret about undesirable side effects or the dreaded cycle of yo-yo dieting.
Shall we exchange links? My website http://fertus.shop/info/
The offer is still valid. Details http://fertus.shop/info/
We offer cooperation on SEO optimization http://fertus.shop/info/
Content for your website http://fertus.shop/info/
Web Development Wizards http://fertus.shop/info/
Your site’s position in the search results http://fertus.shop/info/
Web Development Wizards http://fertus.shop/info/
Your blog has helped me become a more positive and mindful person I am grateful for the transformative effect your words have had on me
Your site’s position in the search results http://fertus.shop/info/
Sugar Defender introduces a meticulously curated ensemble of eight key ingredients, each strategically selected to champion healthy blood sugar levels and facilitate weight loss. These ingredients collaborate to enhance the supplement’s effectiveness through diverse mechanisms, including energy elevation, fat burning, and metabolism stimulation, all while providing direct support for maintaining healthy blood glucose levels. Here is an insightful overview of each ingredient along with its purported functionality according to the manufacturer:
SEO Optimizers Team http://fertus.shop/info/
Metanail Total Cleanse is our ultimate solution against internal fungus buildup While Metanail Serum Pro fights fungus from the outside, working in perfect sync with the serum,
As a fellow blogger, I can appreciate the time and effort that goes into creating well-crafted posts You are doing an amazing job
Pretty! This has been a really wonderful post. Many thanks for providing these details.
Your positive energy and enthusiasm radiate through your writing It’s obvious that you are truly passionate about what you do
Your article helped me a lot, is there any more related content? Thanks!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/uk-UA/register?ref=W0BCQMF1
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your article helped me a lot, is there any more related content? Thanks!
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your knowledge and expertise on various topics never ceases to amaze me I always learn something new with each post
As a fellow blogger, I can appreciate the time and effort that goes into creating well-crafted posts You are doing an amazing job
Your blog has become a part of my daily routine Your words have a way of brightening up my day and lifting my spirits