I’m trying to implement push notifications with react native app with this plugin react-native-push-notifications. what I succeed is to get notification when app is running(in foreground), but what I’m looking to do is to get local notification when app is closed(background), not running and when I get notification to go into the app.
This is my Code –
PushNotification.createChannel({
channelId: "alarm-channel",
channelName: "Alarm Channel",
importance: 4,
vibrate: true,
});
};
const [selectedDate, setSelectedDate] = useState(new Date());
const handleDatePicker = (dateTime) => {
const fireDate = dateTime;
PushNotification.localNotificationSchedule({
channelId: "alarm-channel",
title: 'title',
id: alarmNotifData.id,
message: 'message',
date: fireDate ,
soundName: "Default",
actions: ["Snooze", "Stop Reminder"],
importance: Importance.HIGH,
playSound: true,
allowWhileIdle: true,
invokeApp: false,
priority: "high",
timeoutAfter: 50000,
autoCancel: false,
vibrate: true,
vibration: 500,
});
};
handleDatePicker(selectedDate);
2
Answers
Use background services to run your code when app is closed. For Android, react-native has Headless.js but to do that you need to write some native code. Unfortunately react-native has no documentation for IOS right now.
For Android : https://reactnative.dev/docs/headless-js-android
A library that does this for both IOS & Android : https://www.npmjs.com/package/react-native-background-actions
If you’re looking to implement notifications in the background. I highly recommend adopting the
@notifee/react-native
package.Installation instructions
You can use React Native AppState to check whether or not you’re currently in the foreground of the app or in the background.
For iOS, I personally like to use
AppState.current === "inactive"
since its lifecycle is always active -> inactive -> background.For Android I use
AppState.current === "background"
since Android only has active -> backgroundFirst import AppState and notifee
Within your app setup code create a state variable for appState and set up an AppState listener
Then, somewhere in your code you can say.
In android if you’re experiencing that a new instance of your app is getting created when you open up a notification, make sure you check your
AndroidManifest.xml
. This took me hours to fix in the past.the whole activity in question for
AndroidManifest.xml
Good luck!