- React Native Push Notifications
- рџЋ‰ Version 7.x is live ! рџЋ‰
- Supporting the project
- Changelog
- Installation
- Issues
- Pull Requests
- iOS manual Installation
- Android manual Installation
- If you use remote notifications
- If you don’t use autolink
- Usage
- Example app
- Handling Notifications
- Local Notifications
- Scheduled Notifications
- Get the initial notification
- Custom sounds
- Channel Management (Android)
- List channels
- Channel exists
- Channel blocked
- Delete channel
- Cancelling notifications
- 1) cancelLocalNotification
- 2) cancelAllLocalNotifications
- 3) removeAllDeliveredNotifications
- 4) getDeliveredNotifications
- 5) removeDeliveredNotifications
- 6) getScheduledLocalNotifications
- Abandon Permissions
- Notification priority
- Notification visibility
- Notification importance
- Show notifications while the app is in foreground
- Notification while idle
- Repeating Notifications
- Android
- Notification Actions
- Set application badge icon
- Android Only Methods
- Android Custom Notification Handling
- Customizing Notification Creation
- Handling Custom Payloads
- Checking Notification Permissions
- Implementing React Native Push Notifications in Android Apps
- Requirements
- Install and Set Up react-native-push-notifications
- Configure Local Push Notifications
- Configure Remote Notifications
- Conclusion
React Native Push Notifications
React Native Local and Remote Notifications for iOS and Android
рџЋ‰ Version 7.x is live ! рџЋ‰
Check out for changes and migration in the CHANGELOG:
Supporting the project
Maintainers are welcome ! Feel free to contact me рџ‰
Changelog
Changelog is available from version 3.1.3 here: Changelog
Installation
NOTE: If you target iOS you also need to follow the installation instructions for PushNotificationIOS since this package depends on it.
NOTE: For Android, you will still have to manually update the AndroidManifest.xml (as below) in order to use Scheduled Notifications.
Issues
Having a problem? Read the troubleshooting guide before raising an issue.
Pull Requests
iOS manual Installation
The component uses PushNotificationIOS for the iOS part. You should follow their installation instructions.
Android manual Installation
NOTE: firebase-messaging , prior to version 15 requires to have the same version number in order to work correctly at build time and at run time. To use a specific version:
In your android/build.gradle
NOTE: localNotification() works without changes in the application part, while localNotificationSchedule() only works with these changes:
In your android/app/src/main/AndroidManifest.xml
If not using a built in Android color ( @android:color/
If your app has an @Override on onNewIntent in MainActivity.java ensure that function includes a super call on onNewIntent (if your MainActivity.java does not have an @Override for onNewIntent skip this):
If you use remote notifications
Make sure you have installed setup Firebase correctly.
Then put your google-services.json in android/app/ .
The Firebase Android library firebase-core is no longer needed. This SDK included the Firebase SDK for Google Analytics.
Now, to use Analytics or any Firebase product that recommends the use of Analytics (see table below), you need to explicitly add the Analytics dependency: com.google.firebase:firebase-analytics:17.3.0 .
If you don’t use autolink
In your android/app/build.gradle
Manually register module in MainApplication.java (if you did not use react-native link ):
Usage
DO NOT USE .configure() INSIDE A COMPONENT, EVEN App
If you do, notification handlers will not fire, because they are not loaded. Instead, use .configure() in the app’s first file, usually index.js .
Example app
Example folder contains an example app to demonstrate how to use this package. The notification Handling is done in NotifService.js .
Please test your PRs with this example app before submitting them. It’ll help maintaining this repo.
Handling Notifications
When any notification is opened or received the callback onNotification is called passing an object with the notification data.
Notification object example:
Local Notifications
Scheduled Notifications
Get the initial notification
Custom sounds
In android, add your custom sound file to [project_root]/android/app/src/main/res/raw
In iOS, add your custom sound file to the project Resources in xCode.
In the location notification json specify the full file name:
Channel Management (Android)
To use channels, create them at startup and pass the matching channelId through to PushNotification.localNotification or PushNotification.localNotificationSchedule .
NOTE: Without channel, notifications don’t work
In the notifications options, you must provide a channel id with channelId: «your-channel-id» , if the channel doesn’t exist the notification might not be triggered. Once the channel is created, the channel cannot be updated. Make sure your channelId is different if you change these options. If you have created a channel in another way, it will apply options of the channel.
If you want to use a different default channel for remote notification, refer to the documentation of Firebase:
For local notifications, the same kind of option is available:
List channels
You can list available channels with:
Channel exists
You can check if a channel exists with:
Channel blocked
You can check if a channel blocked with:
Delete channel
You can delete a channel with:
Cancelling notifications
1) cancelLocalNotification
The id parameter for PushNotification.localNotification is required for this operation. The id supplied will then be used for the cancel operation.
2) cancelAllLocalNotifications
Cancels all scheduled notifications AND clears the notifications alerts that are in the notification centre.
3) removeAllDeliveredNotifications
Remove all delivered notifications from Notification Center
4) getDeliveredNotifications
Provides you with a list of the app’s notifications that are still displayed in Notification Center
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | Function which receive an array of delivered notifications. |
A delivered notification is an object containing:
- identifier : The identifier of this notification.
- title : The title of this notification.
- body : The body of this notification.
- category : The category of this notification (optional).
- userInfo : An object containing additional notification data (optional).
- thread-id : The thread identifier of this notification, if has one.
5) removeDeliveredNotifications
Removes the specified notifications from Notification Center
Parameters:
Name | Type | Required | Description |
---|---|---|---|
identifiers | array | Yes | Array of notification identifiers. |
6) getScheduledLocalNotifications
Provides you with a list of the app’s scheduled local notifications that are yet to be displayed
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | function | Yes | Function which receive an array of delivered notifications. |
Returns an array of local scheduled notification objects containing:
Name | Type | Description |
---|---|---|
id | number | The identifier of this notification. |
date | Date | The fire date of this notification. |
title | string | The title of this notification. |
message | string | The message body of this notification. |
soundName | string | The sound name of this notification. |
repeatInterval | number | (Android only) The repeat interval of this notification. |
number | number | App notification badge count number. |
data | any | The user info of this notification. |
Abandon Permissions
Revokes the current token and unregister for all remote notifications received via APNS or FCM.
Notification priority
(optional) Specify priority to set priority of notification. Default value: «high»
Notification visibility
(optional) Specify visibility to set visibility of notification. Default value: «private»
Notification importance
(optional) Specify importance to set importance of notification. Default value: Importance.HIGH
Constants available on the Importance object. import PushNotification,
Show notifications while the app is in foreground
If you want a consistent results in Android & iOS with the most flexibility, it is best to handle it manually by prompting a local notification when onNotification is triggered by a remote push notification on foreground (check notification.foreground prop).
Watch out for an infinite loop triggering onNotification — remote & local notification will trigger it. You can overcome this by marking local notifications’ data.
Notification while idle
(optional) Specify allowWhileIdle to set if the notification should be allowed to execute even when the system is on low-power idle modes.
On Android 6.0 (API level 23) and forward, the Doze was introduced to reduce battery consumption when the device is unused for long periods of time. But while on Doze the AlarmManager alarms (used to show scheduled notifications) are deferred to the next maintenance window. This may cause the notification to be delayed while on Doze.
This can significantly impact the power use of the device when idle. So it must only be used when the notification is required to go off on a exact time, for example on a calendar notification.
Repeating Notifications
(optional) Specify repeatType and optionally repeatTime (Android-only) while scheduling the local notification. Check the local notification example above.
Property repeatType can only be month , week , day , hour , minute .
NOTE: repeatTime do not work with iOS.
Android
Property repeatType could be one of month , week , day , hour , minute , time .
The interval used can be configured to a different interval using repeatTime . If repeatType is time , repeatTime must be specified as the number of milliseconds between each interval. For example, to configure a notification every other day
Notification Actions
This is done by specifying an actions parameters while configuring the local notification. This is an array of strings where each string is a notification action that will be presented with the notification.
For e.g. actions: [‘Accept’, ‘Reject’]
When you handle actions in background ( invokeApp: false ), you can open the application and pass the initial notification by using use PushNotification.invokeApp(notification) .
Make sure you have the receiver in AndroidManifest.xml :
Notifications with inline reply:
You must register an action as «ReplyInput», this will show in the notifications an input to write in.
To get the text from the notification:
For iOS, you can use:
And use the category field in the notification.
Documentation here to add notification actions.
Set application badge icon
Works natively in iOS.
Uses the ShortcutBadger on Android, and as such will not work on all Android devices.
Android Only Methods
Subscribe to a topic (works only with Firebase)
Unsubscribe from a topic (works only with Firebase)
Android Custom Notification Handling
Unlike iOS, Android apps handle the creation of their own notifications. React Native Push Notifications does a «best guess» to create and handle incoming notifications. However, when using 3rd party notification platforms and tools, the initial notification creation process may need to be customized.
Customizing Notification Creation
If your notification service uses a custom data payload format, React Native Push Notifications will not be able to parse the data correctly to create an initial notification.
For these cases, you should:
- Remove the intent handler configuration for React Native Push Notifications from your android/app/src/main/AndroidManifest.xml .
- Implement initial notification creation as per the instructions from your Provider.
Handling Custom Payloads
Data payloads of notifications from 3rd party services may not match the format expected by React Native Push Notification. When tapped, these notifications will not pass the details and data to the onNotification() event handler. Custom IntentHandlers allow you to fix this so that correct notification objects are sent to your onNotification() method.
Custom handlers are added in Application init or MainActivity.onCreate() methods:
Checking Notification Permissions
callback will be invoked with a permissions object:
- alert : boolean
- badge : boolean
- sound : boolean
Источник
Implementing React Native Push Notifications in Android Apps
Nov 22, 2019 · 8 min read
Relevant push notifications are a great way to boost a user’s engagement towards an application. According to some analysis, push notifications increase app engagement by 88%. It’s also curious to see that the click-through rate for push notifications in Android (4.06%) is much higher than in iOS (1.7%).
In this tutorial, you are going to learn how to implement push notifications as an app feature using React Native and Firebase. We will be testing out the notification feature on an Android device, but you can go ahead and try it out on iOS yourself.
There a re two main ways you can send push notifications to your app users: local and remote. Local notifications are sent from a React Native application, while remote push notifications are sent from the server or a push notification service such as Firebase Cloud Messaging service (FCM). We will explore both approaches.
Requirements
To follow this tutorial, please make sure you have the following installed on your local development environment and have access to the services mentioned below:
- Nodejs (>= 10.x.x ) with npm/yarn installed.
- react-native-cli
- Windows/Linux users must be running an Android emulator or a real device via USB
- Active Firebase project
To know more about how to set up a development environment for React Native using react-native-cli, please refer to the official documentation.
You can find the complete code for this tutorial at this GitHub repository.
Install and Set Up react-native-push-notifications
The react-native-push-notifications library helps you set up controllers to consume local or remote notifications for iOS and Android devices. To begin, follow the instructions from the terminal window. Create a new React Native project and then install this library.
For iOS devices, this library depends on the manual installation instructions mentioned at PushNotificationIOS — an API that is maintained by react-native-community.
For Android devices, you are going to make the following edits in the appropriate files mentioned below. These modifications allow us to link native capabilities. First, open the file android/build.gradle and add the following:
Next, open android/app/build.gradle and add the following:
In the above step, you are adding native bindings to allow the Firebase backend to send and receive notifications remotely. Do note that, if you are not looking forward to using remote notifications, you can ignore the above step. However, the following step is important for both types of notifications to work. Open the android/app/src/main/AndroidManifest.xml file. Before the tag, add the following.
Lastly, go to android/app/src/res/values/colors.xml . If the file does not exist, create it. This file determines the color of the notification on an Android device. For example, the notification can be white:
Note: To use this library with Expo, you have to eject the Expo SDK app.
Configure Local Push Notifications
In this section, you are going to write a configure function such that, when a button is pressed, a local notification is triggered. Create a new file src/services/LocalPushController.js . Start by importing PushNotification from the library you initialized in the previous step.
Add PushNotification.configure() to the file. This accepts an object with a required method onNotification . This method handles what happens after the notification is opened or received. Since it is a required method, it has to be invoked whether the notification is local or remote. The demo application only invokes a console statement stating the properties of the local notification object used in the current demo app.
Next, export LocalNotification in the snippet below — which gets invoked when a button pressed by the user or as the value of the onPress attribute.
PushNotification.localNotification has plenty of properties for each mobile platform (such as iOS or Android). From the above snippet, properties like vibrate , vibration , bigText , subText are Android only. However, properties like actions , title , message , playSound & soundName are cross-platform.
Import this method in the App.js file. Import LocalNotification from the src/services/LocalPushController.js file. Then, inside the functional App component, add a handler method handleButtonPress to invoke only when the user presses the button.
Now, from a terminal window, run react-native run-android . Make sure you have a device connected via USB and have USB debugging enabled, or you can test on an Android Emulator.
The output of the above code snippet should look like this:
When the button is pressed, it displays the notification, vibrates the device, and plays a default notification sound.
Expanding the notification displays the message from bigText . Pressing the notification results in triggering the console statement from onNotification method.
You can add scheduled notifications by using the PushNotification.localNotificationSchedule(details: Object) method or you can repeat notifications after a particular time too. Read how to do this or add more customizations in the module’s official docs.
Configure Remote Notifications
To test out how remote notifications work, let us integrate the Cloud Messaging Service using Firebase. To follow the steps below, make sure you have an active Firebase project.
From the main Dashboard page, go to Project Settings. In the Your apps section, click on Add app and set up a new Android app.
Next, it will ask you to register the application.
Download the file google-services.json and save it at the location android/app/ inside your React Native project.
Then, open the android/app/build.gradle file and add the following.
Next, create a new service file called RemotePushController.js inside the src/services/ directory. This file contains all the configuration to handle a remote push notification. Inside the mandatory onNotification method, let us again display the result of the remote notification in the console.
It also requires a mandatory Android property called senderID . This can be fetched form Project Settings > Cloud Messaging.
Also, the Cloud Messaging service works based on using a Token between the app and the notification service. The onRegister method registers the remote server and obtains this token. You can view this by adding a console statement.
The controller component returns null to avoid having any effects on the final layout. Add this method inside the App.js file as shown below:
To test it out, go to Cloud Messaging section and compose a notification.
Click the button Send test message. You will have the following output.
The Log in the terminal is shown for the same notification.
You can customize the title, message and another behavior of the Firebase Cloud Messaging service to send notifications at a particular time or date by composing the notification.
Conclusion
Congratulations! You have successfully implemented both ways to send a push notification in a React Native app.
Go ahead and try to implement a scheduled notification as a challenge.
Finally, don’t forget to pay special attention if you’re developing commercial React Native apps that contain sensitive logic. You can protect them against code theft, tampering, and reverse engineering by following our guide.
Originally published on the Jscrambler Blog by Aman Mittal.
Источник