Sending notifications via FCM when app is active - android

How can I leave a push message unread, even if the app is foreground?
I am creating an application using ionic. I use push notifications using firebase cloud messaging (cordova-plugin-fcm-with-dependecy-updated) to subscribe to messages, and backend for sending.
Example backend request:
{
"headers": {
"Authorization": "key = blahblah",
"Content-Type": "application / json",
"project_id": "111111111111"
},
"json": {
"registration_ids": [
"token"
],
"time_to_live": 1200,
"data": {
"title": "title",
"body": "body",
"sound": "default",
"badge": 1,
"click_action": "FCM_PLUGIN_ACTIVITY"
}
}
}
I also tried to send the notification key instead of the date key. Tried to add to root
{
...
"android": {
"ttl": "1200s",
"priority": "high",
"notification": {
"click_action": "FCM_PLUGIN_ACTIVITY"
}
},
...
"apns":{
"headers":{
"apns-priority":10,
"apns-expiration": date('U') + 1200
},
"payload":{
"aps":{
"badge":1,
"category":"FCM_PLUGIN_ACTIVITY"
}
}
}
}
The result is the same - when the application is in the background, the push is not displayed in the tray.
How can I leave push unread, if app in foreground, and call my actions at this.fcm.onNotification().subscribe(...) only on user's click?
p.s. I tried to use cordova-plugin-local-notification, but using this caused some conflict - subscribe action doesn't fire in ios

I use ionic and cordova in my app.
I am using the plugin [cordova-plugin-firebasex] (https://github.com/dpa99c/cordova-plugin-firebasex) to receive push.
To send the push, use the following json:
{
"registration_ids": [
"token"
],
"notification":{
"title":"Ionic 4 Notification",
"body":"Notification sent from POSTMAN",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"notification_icon"
},
"data":{
"email":"teste#gmail.com"
},
"priority":"high"
}
For android, the "notification" field that displays a notification when the application is in the background.
If you are in foreground, you have to display a notification yourself using the plugin [cordova-plugin-local-notifications] (https://github.com/katzer/cordova-plugin-local-notifications)
My code:
constructor(private firebaseCordova: FirebaseX) {}
private initializePushApp() {
this.checkNotificationPermission(false);
this.onMessageApp();
}
checkNotificationPermission(requested) {
try {
this.firebaseCordova.hasPermission().then(hasPermission => {
if (hasPermission) {
this.getTokenApp();
} else if (!requested) {
this.firebaseCordova.grantPermission().then(value => {
this.checkNotificationPermission(true);
});
} else {
// Denied
console.log("Notifications won't be shown as permission is denied");
}
});
} catch (e) {
console.error(e);
}
}
onMessageApp() {
try {
this.firebaseCordova.onMessageReceived().subscribe(data => {
this.showNotificationCordova(data);
});
} catch (e) {
console.error(e);
}
}
showNotificationCordova(notification) {
if ('background' === notification.tap) {
// click on notification in background
alert(notification.title);
} else {
this.clickNotificationSub = this.localNotifications.on('click').subscribe(data => {
// click on notification in foreground
alert(notification.title);
});
this.localNotifications.hasPermission().then(permission => {
if (permission) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
this.localNotifications.requestPermission().then(value => {
if (value) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
console.log("Notifications won't be shown as permission is denied");
}
});
}
});
}
}
When you enter this condition 'background' === notification.tap` the notification was clicked in the background

Related

Is there a way to send firebase push notification to both iOS and android using nodejs?

I have written this code with nodejs to send a push notification from a nodejs server to a specific user of a mobile application:
const { admin } = require("../config/Firebase");
const sendNotification = async (req, res) => {
const requestBody = req?.body;
const registrationToken = requestBody?.registrationToken; // get it from mobile app
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
description: "Notification description",
},
android: {
notification: {
imageUrl: "https://foo.bar.pizza-monster.png",
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: "https://foo.bar.pizza-monster.png",
},
},
webpush: {
headers: {
image: "https://foo.bar.pizza-monster.png",
},
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
try {
admin.messaging().send(data.message);
res.status(200).json({ notificationStatus: "success" });
} catch (error) {
console.log("Error while sending notification: ", error);
res.status(500).json({ notificationStatus: "failed" });
}
};
But it works only for android devices. So i would like to know if there a config or something like that which makes the server sends it to both iOS and android devices ?

FCM Status bar icon not showing

I am trying to add a white icon for push notifications sent via FCM admin. Per the guides here, I should be able to just add in the "icon" key and its corresponding URL to the notification. However, it is not working. My default app Icon gets used instead when the notification is received on my phone. Any idea why it's not working? Here is my code
var message = {
notification: {
title: "title here",
body: "body message here"
},
android: {
notification: {
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "https://firebasestorage.googleapis.com/xxxxx"
}
},
data: {
tab: "message",
subsection: "notification"
},
token: registrationToken
};
// send the push notification
var sentMessage = admin.messaging().send(message)
.then(function (response) {
console.log("Successfully sent message: ", response);
})
.catch(function (error) {
console.log("Error sending message: ", error);
});

Cannot get notifications when my Ionic 3 app is in foreground ( For iOS ), Android works fine

The payload I am sending is fine, searched for this a lot, Android foreground notifications are working fine. And in iOS, when the app is in the background or app is closed, I receive notification correctly.
But when the app is in the foreground, I don't get the notification, neither the .on('notification', ()=>{}) is triggered. Any ideas would be helpful.
Already gone through a lot of stuff.
const options: PushOptions = {
android: {},
ios: {
"sound": "true",
"alert": "true",
"badge": "true",
"clearBadge": "true"
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification')
.subscribe((notification: any) => {
// {
// additionalData: {
// typeData: {}//Sent from server,
// coldstart: "false",
// foreground: "false"
// }
// }
let alertme = this.alert.create({
title : "GOT NOTIFIED",
subTitle : JSON.stringify( notification ),
buttons : [{
text: 'Ok',
handler: () => {
}
}]
});
alertme.present();
});

Ionic notification in android

I used blow code for ionic notification I have used fcm (firebase cloud messaging)
I Received push Notifications when the app is close but I didn't receive notification when the app is open(running) in android
app.js
.config(function($ionicCloudProvider) {
$ionicCloudProvider.init({
"core": {
"app_id": "xxxxxx"
},
"push": {
"sender_id": "xxxxxxxxxxxx",
"pluginConfig": {
"ios": {
"badge": true,
"sound": true
},
"android": {
"badge": true,
"iconColor": "#343434"
}
}
}
});
})
controler.js
$ionicPush.register().then(function(t) {
return $ionicPush.saveToken(t);
}).then(function(t) {
console.log('Token saved:', t.token);
alert(t.token);
});
$rootScope.$on('cloud:push:notification', function(data) {
console.log("dbhfd")
var msg = data.message;
console.log("dbhfd")
alert(msg.title + ': ' + msg.text);
$state.go('message');
});
use localnotification when new notification received in the foreground
this.fcm.onNotification().subscribe(data => {
if(data.wasTapped){
console.log("Received in background");
} else {
console.log("Received in foreground");
this.localNotifications.schedule({
id: 1,
title: ""+data.title+"",
text: ""+data.body+""
});
};
});
hi,
when the app is opened you will not get any notifications even you can check with Facebook or any other apps.if app is closed then only you will receive notifications that's not an issue i think you achieved your goal
If you want to integrate with firebase + push notifications then you can follow this link
here!
And in this push notifications link just keep register() function & related code in App.tsx then you will get notifications foreground and background.
And if you want to produce local notifications then follow this link here!

how to set action on ionic push notification

I have implemented an android app using ionic. i want to implement push notification with some action like accept and reject.
I used phonegap pluginpush for push notification.
But when i clicked on them nothing happens.
sent notification
POST /push/notifications HTTP/1.1
Host: api.ionic.io
Content-Type: application/json
Authorization: Bearer xxxxxxxxxxxxxx
{
"tokens": ["token1","token2"],
"profile": "profile",
"notification": {
"title": "data updated ",
"message":"allow sync immediatly",
"android": {
"data": {
"image": "www/img/icon.png",
"vibrationPattern": [100, 1000, 500, 500],
"notId": 121,
"actions": [
{ "title": "Approve ", "callback": "accept", "foreground": true},
{ "title": "Reject", "callback": "reject", "foreground": true}
]
}
}
}
}
javascript
angular.module('app')
.factory("notificationService", function ($http, $q, $ionicPlatform, baseUrl, $ionicPush, $localStorage, USER) {
window.approve = function(data){ alert("Approve Triggered"); }
window.reject = function(data){ alert("Reject Triggred"); }
var notification = function () {
$ionicPlatform.ready(function () {
$ionicPush.init({
"debug": true,
"onNotification": function (notification) {
alert("notification received");
var payload = notification.payload;
},
"onRegister": function (data) {
saveGcmToken(USER.parentId(), data);
},
"pluginConfig": {
"android": {
"badge": true,
"sound": true,
"alert": true,
"icon": "icon",
'forceShow' : true,
//"iconColor": "#948438"
},
"ios": {
"badge": true,
"sound": true,
"forceShow" : true,
"alert": true
}
}
});
$ionicPush.register({
canShowAlert: true,
canSetBadge: true,
canPlaySound: true,
canRunActionsOnWake: true,
});
});
}
function saveGcmToken(parentId, token) {
var data = {};
angular.extend(data, {
id: parentId,
name: token._token
});
$http({
method: 'PUT',
contentType: 'application/json',
data: data,
url: baseUrl + "/add-app-token"
}).success(function (response) {
alert("response from notification service" + JSON.stringify(response));
}).error(function (response) {
alert("Error " + JSON.stringify(response));
});
}
return {
notification: notification
}
})
try this update your alert function.
"onNotification": function (notification) {
alert('message = '+notification.message+' title = '+notification.title + ' actions = '+notification.android.data.actions+ ' notId = '+notification.android.data.notId);
}
For details visit : http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
https://www.npmjs.com/package/phonegap-plugin-push-pgb

Categories

Resources