Delete previous notification(s) using react-native-push-notification - android

I'm writing an app that sends a local push notification every fifteen minutes while a background timer is running via react-native-push-notification. If notification n isn't acted on by the user, when notification n+1 is pushed, I'd like to delete notification n.
The things I've tried so far are to set popInitialNotification to true when running PushNotification.configure() and setting ongoing to true when calling PushNotification.localNotification(). I've also tried adding an id when calling localNotification() and then calling PushNotification.cancelLocalNotifications({id: myId}), but the documentation explicitly says that cancelLocalNotifications() only cancels scheduled notifications (and I'm pretty sure it means only future ones).
componentWillMount() {
PushNotification.configure({
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
});
}
doPushNotification() {
if (AppState.currentState !== 'active') {
PushNotification.localNotification({
vibration: 500,
message: 'my message',
ongoing: true,
});
}
}
Currently I'm only working on the Android version, but soon I'll work on the iOS version, so a general solution (or the solution for each) would be most helpful.
I'm not totally sold on react-native-push-notification, either, if there's a better React Native library out there; I just haven't found one.
Edit
I figured it out for Android. Setting the id when calling PushNotification.localNotification() to the same value as the previous notification will overwrite the notification.
I'm still installing XCode on my Mac, so I can't test the current behavior on iOS just yet. However, the react-native-push-notification readme says that id is an Android-only option (as is ongoing). I may still need help getting the iOS notifications to do what I want.

The docs for react-native-push-notification state that you can cancel a ios local notification using userInfo like this:
PushNotification.localNotification({
...
userInfo: { id: '123' }
...
});
PushNotification.cancelLocalNotifications({id: '123'});
I have tested this, and it works.
For android, this somehow worked:
Creating the notification :
PushNotification.localNotificationSchedule({
message: message ,
date: new Date(date),
repeatType: "minute",
id: JSON.stringify(id),
userInfo: { id: JSON.stringify(id) }
});
PushNotification.cancelLocalNotifications({ id: id});
Having the id stringified worked with cancelling the android push notification.

you can add this code inside handleAppStateChange(appState)
if (appState === 'active') {
PushNotification.cancelAllLocalNotifications()
}

if you are useing react-native-push-notification lib.
then you can use this code in componentDidMount section
PushNotification.getDeliveredNotifications((all) => {
console.log(all, "notification liast");
PushNotification.removeAllDeliveredNotifications();
});
here you can get all notification list and clear all list after open your app.
these code work for me in ANDROID device (i did not test it in IOS device)

Below code works on both iOS and Android :
We need to stringify id so that it works in android and the date must be created from Date class not from some library like moment.
const LocalNotificationSchedule = (id, afterSec, message) => {
PushNotification.localNotificationSchedule({
id: id+'',
message: message,
date: new Date(Date.now() + afterSec * 1000),
playSound: true,
soundName: 'default',
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
ignoreInForeground: false
})
}
const CancelLocalNotifications = (id) => {
PushNotification.cancelLocalNotifications({id: id+''})
}

Try to delete the notification with cancelLocalNotifications.

Related

How to launch specific screen on tap of local notification in react native

I'm currently using this library in react-native to schedule local notification, when i tap of notification either from notification centre or from top of the app, i want to redirect the user to specific screen. Currently react-native-push-notification lib using old UILocalNotification classes which are already deprecated.
Below is my code to configure local notification.
onNotification is a callback method triggers when user launches the app from notification centre for iOS and similarly onAction is for Android.
/**
* To configure for local notifications
*/
export function localNotificationConfigure() {
PushNotification.configure({
onNotification: async function (notification) {
console.log('notification.data', notification.userInteraction);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
onAction: async function (notification) {
console.log('notification', notification.userInteraction);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',
});
}
Is there any way that i can achieve this. Is it because of lib using UILocalNotification which is deprecated and i'm not able to get the action back in the code. Any help is appreciated.
This link helped me in achieving my desired functionality.

Alert from timer in background mode

I have not really done much with background mode before and I have not used push notifications before.
What am trying to achieve is to give the user a warning they are going to be auto logged out 5 minutes before it happens and give them a chance to refresh their token.
It works fine when the app is active in the foreground. I pop up an alert and get them to click “ok” otherwise after 5 mins it logs out.
I have added
#ionic-native/background-mode
to my project and enabled background mode but I am not sure how to get the app to alert the user.
Is there a way to do this? Or can I only run "non UI" tasks from the background
Could I use a push notification locally from the app to notify the user rather than an alert or do push notifications only work from a server?
I used local notifications:
https://capacitor.ionicframework.com/docs/apis/local-notifications
import { Plugins } from '#capacitor/core';
const { LocalNotifications } = Plugins;
LocalNotifications.schedule({
notifications: [
{
title: 'Title',
body: 'Body',
id: 1,
schedule: { at: new Date(Date.now() + 5000) },
sound: null,
attachments: null,
actionTypeId: '',
extra: null
}
]
});

cordova fcm push notifications using firebase functions issue

I am using firebase function and sending the notification like below
let pushPayload = {
notification: {
title: 'Doodles Notification',
body: "push testing",
sound: 'default',
badge: '1'
}
};
//push tokens need to be of customer as well as all the admins in the system. fetch admin push tokens
admin.messaging().sendToDevice(pushToken, pushPayload).then(
(resp) => {
console.log("push notification sent using test method")
return
}
).catch(
(err) => {
console.log("Error sending push notification:" + JSON.stringify(err))
return
}
)
The client side ionic app has method like below:
this.fcm.onNotification().subscribe(data => {
console.log("push message is:" + JSON.stringify(data))
alert(data.aps.alert.body)
});
on ios this all works great. however on android, the console.log prints
{"wasTapped":false}
I am ok with the above expected property but where is the data? The firebase documentation is confusing around it and I am sort of lost what is the correct payload I need to use that works with both ios and android.
Your pushPayload also needs to have a data array to pass data. I believe you also need speech marks around your keys:
"notification":{
"title":"Doodles Notification",
"body":"push testing",
"sound":"default",
"badge":"1"
},
"data":{
"Key1":"Test",
"Key2":"More data"
}
Documentation

Targeted push notifications not working if one installation device is not found.

Good Evening Everyone,
Using the following code I get target push notifications just fine:
Parse.Cloud.afterSave("Classroom", function(request){
var teacherThatPosted = request.object.get("userIDs");
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.containedIn("objectId", request.object.get("userIDs"));
Parse.Push.send({
where: pushQuery,
data: {
alert: "Test",
sound: "default"
}
}, {
success: function() {
console.log("SUCCESS");
},
error: function(error) {
console.log(error);
}
});
});
The issue I am having is when a device is added to the installation list and the user deletes the app, phone ID in the install list is no longer valid, so no one will receive notifications. Once, I remove that deleted user from the install list manually, everyone receives notifications just fine. Also, once that user from the installation list is removed, all of the push notifications that are sent push through.
So my question, Is there a way to handle this issue? If so, how?

Cordova PushPlugin not working when app is in foreground

I'm using Cordova 3.5.0-0.2.6 to cerate an Android application and using PushPlugin 2.2.1 to push notifications.
Everything works fine and get the notifications in my droid notifications bar when the app is in background, but when it's in foreground nothing happens when it get the notification. Wanted to make it play a sound or even show a popup alert to let the user know he has a new notification. Copied the example code from the plugin's github page (https://github.com/phonegap-build/PushPlugin) but it isn't working. The corresponding part of the code is this:
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground)
{
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/android_asset/www/"+ soundfile);
my_media.play();
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
window.location = 'iframe.html?url=' + e.payload.url;
if (e.coldstart) {
//$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
} else{
//$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
}
Not sure where the beep.wav file should be placed, I placed it into the www folder, but I'm 100% sure that's the place to put it.
Any one had this problem before? Any idea what I might be missing here?
Thanks,
Luciano
For android please add property "forceShow": "true" and it should work..
example code is below:
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx",
"forceShow": "true",
"icon": "icon",
"sound": true,
"vibration": true,
"badge": true
},
"browser": {
},
"ios": {
"senderID": "xxxxxxxxx",
"icon": "icon",
"gcmSandbox": true,
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
but when it's in foreground nothing happens when it get the notification
This is the default behavior of PushPlugin. It creates a notification and the associated sound only when the application is in the background or closed.
Wanted to make it play a sound or even show a popup alert to let the user know he has a new notification.
The easiest solution would be to use Cordova Plugin Dialogs. All you would have to do is:
switch( e.event )
{
case 'message':
if (e.foreground) {
navigator.notification.beep(1);
}
.
.
}
Note that this beep will be the message tone configured by the user on his/her device.
Not sure where the beep.wav file should be placed, I placed it into the www folder
Not sure either, but I think it is the www directory too.
See also: Android won't play push sound while app not running

Categories

Resources