- React Native Local iOS and Android Notifications
- Introduction
- Installation
- iOS Setup
- Android Setup
- Putting it all together!
- 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
React Native Local iOS and Android Notifications
Introduction
My requirements were simple I needed to incorporate Local notifications that I could schedule to to appear at a later time for both iOS and Android. I also needed these notifications to still display even if the app was closed. After some research I found that react-native-push-notification was my best bet. However, I found that this was a bit tricky to get up and running, but at long last I was successful. My struggle is your lucky day.
Installation
We are actually going to have to install two packages because the react-native-push-notification package utilizes push-notifications-ios in order to send iOS notifications. These packages also support Push Notifications but that is out of scope of this tutorial.
Since we are going to be using native features on the device we need to Manually Link these packages. To do that run the following commands. Linking allows you to use the native features of the device!
iOS Setup
Since we install a native module it is a good idea to run pod install in the iOS directory. This will give you access to the module we install through npm in xCode
Since we want to use both local and scheduled notifications we need to add some Objective-C code in the AppDelegate.m file of the application. For this you are going to want to navigate to the iOS directory in your app folder and open the .xcworkspace file. ( Notifications/ios/Notifications.xcworkspace ). Then open the AppDelegate.m .
First import the module that we installed through npm.
Then add the following code into the body.
Now is a good time to try and build the project in xCode. If you did everything correctly you should have a successful build. If not make sure that you ran pod install in the iOS directory of your application. Thats it for the iOS Setup!
Android Setup
Since we are going to want to use local scheduled notifications we are going to need to add some code to the android/app/src/main/AndroidManifest.xml file. Outside of the tag but within the tag add the following code:
Then add the following code within the tag:
That’s it for the Android Setup!
Putting it all together!
In order to keep things simple and clean let’s create a file call NotificationService.js . This file is where all of our Notification code will go. Add the following to that file:
Note: This is the absolute basics. Consult the Github repos for more information
Источник
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
Источник