can someone please let me know where Im going wrong.
From what I can see on instructions....theres no amendments required to Android specific files if you are only using local notifications and also using autolinking....except for adding googlePlayServicesVersion = "<Your play services version>" // default: "+" to android/build.gradle....and <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> plus <uses-permission android:name="android.permission.VIBRATE" /> to AndroidManifest.xml
Below is my main source code
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log('onRegister token:', token);
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function(notification) {
console.log('onNotification:', notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// Should the initial notification be popped automatically
popInitialNotification: true,
requestPermissions: true,
});
userNowInactive = () => {
this.showNotification();
}
showNotification = () => {
PushNotification.localNotification({
//ios and android properties
title: 'Face2Face: Beacon Timer Expired',
message: 'Perhaps set your beacon timer for another hour?',
playSound: true,
soundName: 'sound.mp3',
//android only properties
channelId: 'your-channel-id',
autoCancel: true,
// largeIcon: 'ic_launcher',
// smallIcon: 'ic_launcher',
bigText: 'Face2Face: Beacon Timer Expired',
subText: 'Perhaps set your beacon timer for another hour?',
vibrate: true,
vibration: 300,
priority: 'high',
//ios only properties...is there any?
});
};
Did you create a channel?
It seems you need to create one to get it to work.
https://github.com/zo0r/react-native-push-notification#channel-management-android
To use channels, create them at startup and pass the matching channelId through to PushNotification.localNotification or PushNotification.localNotificationSchedule.
PushNotification.createChannel(
{
channelId: "channel-id", // (required)
channelName: "My channel", // (required)
channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
playSound: false, // (optional) default: true
soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
Related
When I installed the app for first time the push notification is not receiving, if I kill the app and open again the push notifications is working fine.
When I console the code and trigger the push notification manually through FCM , I found that the notification data is not receiving on the onMessage function and on getInitialNotification() the result shows as undefined.
Please check the below code for getting push notifications and also the packages and versions which I have used.
Packages :
"#react-native-firebase/messaging": "^7.5.0",
"#react-native-community/push-notification-ios": "^1.10.1",
"react-native-push-notification": "^8.1.1",
Code :
componentWillUnmount() {
if (Platform.OS === "ios" && this.messageListener1 && this.messageListener2) {
this.messageListener1();
this.messageListener2();
}
}
async requestUserPermission() {
const { navigate } = { ...this.props }
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
this.messageListener1 = messaging().onMessage(async remoteMessage => {
PushNotification.localNotification({
/* Android Only Properties */
id: remoteMessage.data.id, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
autoCancel: true, // (optional) default: true
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
group: remoteMessage.data,
userInfo: {
data: remoteMessage.data,
},
title: remoteMessage.notification.title,
message: remoteMessage.notification.body,
});
});
messaging()
.getInitialNotification()
.then(async remoteMessage => {
if (remoteMessage) {
if (await GlobalStorage.handleInitialNotification(remoteMessage)) {
navigate(remoteMessage);
PushNotification.cancelLocalNotifications({ id: remoteMessage.data.id });
}
}
});
this.messageListener2 = messaging().onNotificationOpenedApp(remoteMessage => {
GlobalStorage.handleInitialNotification(remoteMessage)
navigate(remoteMessage);
PushNotification.cancelLocalNotifications({ id: remoteMessage.data.id });
});
Note : There is no issues in getting the FCM token.
I faced the same problem.
I tried all the packages and the result is the same in all of them.
Here's the situation:
*Everything is fine with the Notification integration.
*When you install the application for the first time, there is no notification.
*When you open the application for the first time and kill it in the background and open it again and throw it into the background, everything works fine. You start receiving notifications.
It's really interesting. Has anyone experienced this and know what exactly is causing the issue?
The issue is only facing mainly on android device and here is solution I used to solve the issue
const { navigate,
} = { ...this.props }
PushNotification.configure({
onRegister: function (token) {
},
onNotification: function (notification) {
const clicked = notification.userInteraction ? notification.userInteraction : "";
notification.finish(PushNotificationIOS.FetchResult.NoData);
if (clicked) {
navigate(notification);s
PushNotification.cancelLocalNotifications({ id: notification.id });
} else if (!notification.foreground) {
navigate(notification);
PushNotification.cancelLocalNotifications({ id: notification.id });
}
else {
PushNotification.localNotification({
/* Android Only Properties */
channelId: "app_name", // (required)
channelName: "app_name", // (required)
id: notification.id, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
// autoCancel: true, // (optional) default: true
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
group: notification.data, // (optional) add group to message
priority: "high", // (optional) set notification priority, default: high
visibility: "private", // (optional) set notification visibility, default: private
importance: "high",
userInfo: {
id: notification.id,
name: "name",
title: notification.title,
message: notification.message,
data: notification.data
},
title: notification.title,
message: notification.message,
});
}
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
senderID: "",
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true
});
i am able to generate notification along with action buttons but how to call a onpress event based on the button pressed by user? here yes or no
thanks in advance
import PushNotification from 'react-native-push-notification';
function configure() {
PushNotification.configure({
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log('NOTIFICATION:', notification);
// process the notification
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish();
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
requestPermissions: true,
requestPermissions: Platform.OS === 'ios',
'content-available': 1,
});
}
function givenotification(title, message) {
PushNotification.localNotification({
channelId: 'channel',
message: message, // (required)
title: title,
message: message, // (required)
actions: ["Yes", "No"]
});
}
I have never used push notification directly,
for my notification i have use React Native Notifee that have this "displayNotification" inside when you try to log Notifee ..
I suggest you to try log "PushNotification" to find a function to display your notification.
You can setup the action as below code:
export const App = () => {
const [permissions, setPermissions] = useState({});
/**
* By calling this function, a notification with category `userAction` will have action buttons
*/
const setNotificationCategories = () => {
PushNotificationIOS.setNotificationCategories([
{
id: 'userAction',
actions: [
{id: 'open', title: 'Open', options: {foreground: true}},
{
id: 'ignore',
title: 'Desruptive',
options: {foreground: true, destructive: true},
},
{
id: 'text',
title: 'Text Input',
options: {foreground: true},
textInput: {buttonTitle: 'Send'},
},
],
},
]);
};
useEffect(() => {
PushNotificationIOS.addEventListener('notification', onRemoteNotification);
});
const onRemoteNotification = (notification) => {
const actionIdentifier = notification.getActionIdentifier();
if (actionIdentifier === 'open') {
// Perform action based on open action
}
if (actionIdentifier === 'text') {
// Text that of user input.
const userText = notification.getUserText();
// Perform action based on textinput action
}
};
};
For more, you can reach out to the official documentation of the library.
https://github.com/zo0r/react-native-push-notification
I am using "react-native-background-geolocation" for user location tracking when the app is in the background.
Then is it possible to set interval in this function when device powered-up again? (on boot)
I want to get the user location constantly in the background once user turn on device.
How to set "setInterval" on this?
That is my code.
componentWillMount = async () => {
// This handler fires whenever bgGeo receives a location update.
BackgroundGeolocation.onLocation(this.onLocation, this.onError);
// This handler fires when movement states changes (stationary->moving; moving->stationary)
BackgroundGeolocation.onMotionChange(this.onMotionChange);
// This event fires when a change in motion activity is detected
BackgroundGeolocation.onActivityChange(this.onActivityChange);
// This event fires when the user toggles location-services authorization
BackgroundGeolocation.onProviderChange(this.onProviderChange);
////
// 2. Execute #ready method (required)
//
BackgroundGeolocation.ready(
{
// Geolocation Config
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
// Activity Recognition
stopTimeout: 1,
// Application config
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app.
startOnBoot: true, // <-- Auto start tracking when device is powered-up.
// HTTP / SQLite config
url: 'http://yourserver.com/locations',
batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives.
headers: {
// <-- Optional HTTP headers
'X-FOO': 'bar',
},
params: {
// <-- Optional HTTP params
auth_token: 'maybe_your_server_authenticates_via_token_YES?',
},
},
(state) => {
console.log(
'- BackgroundGeolocation is configured and ready: ',
state.enabled,
);
if (!state.enabled) {
////
// 3. Start tracking!
//
BackgroundGeolocation.start(function () {
console.log('- Start success');
});
}
},
);
};
Been stuck for days on this one. So, I'm using this package for implementing local push notification:
https://github.com/zo0r/react-native-push-notification
I'm able to get local scheduled notification like this:
PushNotification.localNotificationSchedule({
date: new Date(Date.now() + 30 * 1000), // in 30 secs
/* Android Only Properties */
//id: ''+this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
ticker: "My Notification Ticker", // (optional)
autoCancel: true, // (optional) default: true
largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
subText: "This is a subText", // (optional) default: none
color: "blue", // (optional) default: system default
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
tag: "some_tag", // (optional) add tag to message
group: "group", // (optional) add group to message
ongoing: false, // (optional) set whether this is an "ongoing" notification
/* iOS only properties */
alertAction: "view", // (optional) default: view
category: null, // (optional) default: null
userInfo: null, // (optional) default: null (object containing additional notification data)
/* iOS and Android properties */
title: "Scheduled Notification", // (optional)
message: "My Notification Message", // (required)
playSound: true, // (optional) default: true
soundName: "default", // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
actions: '["Yes", "No"]', // (Android only) See the doc for notification actions to know more
foreground: false, // BOOLEAN: If the notification was received in foreground or not
userInteraction: true, // BOOLEAN: If the notification was opened by the user from the notification area or not
data: { type: "test" } // OBJECT: The push data
});
I want to call a function when user clicks on the notification and when the app opens. To achieve the following I did this in my App.js:
async componentDidMount() {
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
}
But onNotification function doesn't get called.
I've gone through the following questions on SO but no luck.
react-native push notification onNotification doesn't trigger
React Native Push Notification onNotification callback is inconsistent
Android onNotification never called in react-native-push-notification
I've also raised an issue on Github.
What can be the possible solution for this?
for those asking for a solution, I did something like this in my app.js's componentDidMount method:
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: notification => {
console.log(notification);
if (notification.action === "Take") {
//do something here
} else if (notification.action === "Skip") {
//do something here
} else if (notification.action === "Snooze") {
//do something here
}
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
Issue Description::
I am working on react native application and using react native firebase messaging service for push notification. I am having a problem on IOS platform. I am getting double notification popups for single event.
Steps I am following to generate the case::
After app installation if I am login and sending notification through FCM I just received a single popup. After this I logged out and login again, now this time I got double popups for single notification. In this case I am not clearing an app from background.
If after every logout I am clearing an app from background I just received a single popup for single event.
When I am logged out from the application, and forcefully sending notification from FCM, I am getting double popup on app initialization screen(login screen).
I am generating a new device token when user login and saving this token inside local storage, we are clearing local storage data on logout.
Code::
async mountDashboard() {
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
const fcmToken = await firebase.messaging().getToken();
await AsyncStorage.setItem(LocalStorageKeys.DEVICE_TOKEN, fcmToken);
if (fcmToken) {
//--- here we are saving our token and sendind data to API
}
}
// in Foreground
this.notificationListener = firebase.notifications().onNotification((notification) => {
new RegisterLocalNotification(notification);
});
// App in Foreground and background
let notificationHandler = new NotificationsHandler();
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
notificationHandler.handleNotification(notificationOpen.notification);
});
// app close notification handler
AppCloseNotificationHandler.getInstance().handleNotification();
}
componentDidMount() {
this.mountDashboard();
}
Environment::
Binaries:
Node: 10.15.0 - /usr/local/opt/node#10/bin/node
Yarn: 1.10.1 -/usr/local/bin/yarn
npm: 6.4.1 - /usr/local/opt/node#10/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
List item
npm Packages:
react: ^16.8.4 => 16.8.4
react-native: ^0.58.6 => 0.58.6
npm Global Packages:
react-native-cli: 2.0.1
react-native-firebase: 5.2.3
You have to unsubscribe from your listener when the component will unmount. If you don't do that you are subscribing two listeners.
componentWillUnmount() {
this.notificationListener(); // it's unsubscribing your listener
}
Make sure to send this payload via backend, I am using firebase admin SDK.
This will disable Notification By OS and trigger the local notification. I am using this package for local notification https://github.com/zo0r/react-native-push-notification
async function sendPushNotification(message) {
try {
await admin.messaging().sendToDevice(
['dCk27uEySymSdP_vA1C_QI:APA91bEZNyipZDjTLq0jrGnD0qcpKH2y3oTYg3GMgT0pSENNlJEiymOYXvxvnqTFtQaidDLt5KUgp4oDZsfLsQvfiVkL7m1bpMjekHsm-7x1ZDju4TYUMUZeUgYb0CyPwMhdr9RyzA1v'],
{
data: {
owner: 'a',
user: 'a',
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: 'high',
},
);
console.log('A');
}catch(e) {
console.log('Gagal mengirim pesan');
}
}
And this my code inside App.js that listen to the notification
RNFirebase.onMessage(RNFirebaseOnMessageHandler);
RNFirebase.setBackgroundMessageHandler(RNFirebaseOnMessageHandler);
And inside the handler, I use this
PushNotification.createChannel(
{
channelId: CHANNEL_ID,
channelName: CHANNEL_NAME,
channelDescription: CHANNEL_DESCRIPTION,
soundName: CHANNEL_SOUND,
importance: CHANNEL_IMPORTANCE,
vibrate: CHANNEL_VIBRATE,
},
(created) => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
);
PushNotification.localNotification({
channelId: CHANNEL_ID,
// #todo get ticker value from data payload
ticker: 'CreateOrderLandingScreen',
showWhen: true,
autoCancel: true,
largeIcon: CHANNEL_LARGE_ICON,
smallIcon: CHANNEL_SMALL_ICON,
bigText: 'aaaaa',
subText: CHANNEL_SUB_TEXT,
color: Colors.RED,
vibrate: true,
vibration: 300,
priority: 'high',
visibility: 'private',
invokeApp: true,
alertAction: 'view',
id: 0,
title:'aa',
message: 'aaaa',
userInfo: {},
playSound: false,
soundName: 'default',
});