Alert from timer in background mode - android

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
}
]
});

Related

Expo: don't show notification if app is open in foreground

I am developing a react-native messaging app with Expo. Every time a user receives a new message, I send a notification from my server.
Is there any way to not display the notification if the app is currently open?
Right now I am using this as soon as the notification is received:
Notifications.dismissNotificationAsync(notification.notificationId);
But there is a 0.5 second delay where the notification has time to appear in the tray and trigger a sound before it gets dismissed. I would like to not show it at all.
When a notification is received while the app is running, using setNotificationHandler you can set a callback that will decide whether the notification should be shown to the user or not.
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
When a notification is received, handleNotification is called with the incoming notification as an argument. The function should respond with a behavior object within 3 seconds, otherwise the notification will be discarded. If the notification is handled successfully, handleSuccess is called with the identifier of the notification, otherwise (or on timeout) handleError will be called.
The default behavior when the handler is not set or does not respond in time is not to show the notification.
If you don't use setNotificaitonHandler, the new notifications will not be displayed while the app is in foreground.
So you can simply set setNotificationHandler to null when your app is initialized.
Notifications.setNotificationHandler(null);
See Documentaition
The answer is yes to your question
Is there any way to not display the notification if the app is
currently open?
The default behavior of Notification in Expo is not to show notification if the App is in foreground. You must have implemented Notifications.setNotificationHandler similar to the following code -
// *** DON'T USE THE FOLLOWING CODE IF YOU DON'T WANT NOTIFICATION TO BE DISPLAYED
// WHILE THE APP IS IN FOREGROUND! ***
// --------------------------------------------------
// Sets the handler function responsible for deciding
// what to do with a notification that is received when the app is in foreground
/*
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
*/
If you don't use setNotificaitonHandler, the new notifications will not be displayed while the app is in foreground.
Use below code snippet. It works on press notification.
_handleNotification = async (notification) => {
const {origin} = notification;
if (origin === ‘selected’) {
this.setState({notification: notification});
}
//OR
if (AppState.currentState !== 'active') {
this.setState({notification: notification});
}
}
I assume you setup a simple FCM - Firebase cloud messaging
And use that to push messages to the client?
The official Expo guide has a section for receiving-push-notifications
This is the actual workflow of FCM (weird can be called as a common issue) that it'll handle the notifications by itself when the application is in the foreground.
The solution which i did for my project was to create a custom notification JSON rather than using their default template which won't be parsed by FCM.
{
"hello":" custom key and value",
"message":{
"SampleKey":"Sample data",
"data":{
"SampleKey" : "Sampledata",
"SampleKey2" : "great match!"},
}}
In console you can add your own custom JSON objects, and when you get the notification parse the notification by using these objects, then you will be able to override that issue.
You can also add a channel for the request to categorize your notifications
this.createNotificationListeners = firebase.notifications()
.onNotification((notification) => {
let{ hello,data,message} = notification;
});

FCM push notification is not working in android(Ionic project using cordova-plugin-fcm 2.1.1)

I am testing push notifications in an android project build using ionic 1. I have configured everything and getting the token from server for fcm.
in $ionicPlatform.ready of run() I have the following code.
if(window.FCMPlugin){
FCMPlugin.onNotification(function(data){
if (data.wasTapped) {
$ionicPopup.alert({
title: data.title,
template: '<p style="text-align:center">' + data.body + '</p>'
});
} else {
//received foreground
$ionicPopup.alert({
title: data.title,
template: '<p style="text-align:center">' + data.body + '</p>'
});
}
});
FCMPlugin.getToken(function(data){
//$scope.token = data;
console.log("token received");
},
function(err){
$ionicPopup.alert({
title: "Error",
template: '<p style="text-align:center">Error in getting FCM Token</p>'
});
});
}
The problem is when I send fcm notification targeting a single device I am not getting the notification. But, the status of the notification in fcm console says it as a completed one. I am not getting any notification or call back after sending the notification. I have searched for solutions a long time online, couldn't find a solution. Any help is really welcome!
Solved! The test device's wifi connection proxy was causing the problem. When using personal wifi connection the device was able to receive notifications.

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

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.

Why IONIC push notification looks like Javascript alert?

I am successfully able to send push notifications using IONIC Framework. But these notifications doesn't looks like I receive other android notifications, rather it these looks like normal Javascript alert.
Is there any setting to set push notification type like (alert or something else) ?
I go through the following link : https://devdactic.com/ionic-push-notifications-guide/
If someone has faced and resolved this, then please comment.
First screenshot shows push notification as Javascript alert.
Second screenshot shows default Android notification after locking phone's screen.
Third screenshot shows default Android notification after unlocking screen
I solved this problem by applying below code to $ionicPlatform.ready in my app.js file which shows notifications with onNotification event, if onNotification is not present then IONIC show default Javascript alert.
var push = new Ionic.Push({
onNotification: function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
pluginConfig: {
ios: {
alert: true,
badge: true,
sound: true
},
android: {
sound: true,
vibrate: true,
forceShow: true,
iconColor: "#601dc2"
},
}
});
While working with push notification you have Two possibilities to get notification One in the notification tray on the head of screen while your app is in background mode and Second when you are working with your app in foreground mode
First one is display like other notifications to notify that you got a notification for your app with message and logo whatever you set
But for other notification it is just use to get the data and message whatever you passed through it, and now its on you that how you want to show it in the application
Either you can set a div and hide show it when notification display with the design and position as you like or as per your app theme
<script>
function devicePushNotification(data)
{
if (data.additionalData.foreground == true)
{
$("#setNotificationText").text(data.message);
$("#setNotificationText").css("display","block");
}
}
</script>
<div style="width:50%;margin: 0 auto;display:none" id="setNotificationText">
</div>
Or you can just alert the message that you got a notification for anything you have passed like,
<script>
function devicePushNotification(data)
{
if (data.additionalData.foreground == true)
{
alert(data.message);
}
}
</script>
So, if you get the notification successfully, then you just have to create any well formed container to display it.
Hope this helps you

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?

Categories

Resources