I am developing an application using cordova and ibm mobile first 8 and wanted to integrate a push notification system.
I registre the device in the server and i can send the notification from the server to client app then the client app handle a received push notification by operating on its response object in the registered callback function :
var notificationReceived = function(message) {
alert(JSON.stringify(message));
};
Here is my issues :
alert issues
I don't want the alert to be displayed.
And I want that when I click on the notification A function is called.
how can i do this ? Please i need your help thanks .
In the code snippet you have in your question there is an alert. Remove the alert snippet and no alert dialog will be displayed...
You can then put there instead anything else you'd like, like logging the notification contents, or performing any other action, like calling a function.
var notificationReceived = function(message) {
myFunction();
};
function myFunction() {
...
}
Related
I have function in Firebase Cloud Functions which is used to send notifications to specific users within my app and has as the notificationContent the following code:
const notificationContent = {
notification: {
title: "My Notification Title",
body: "My Notification Body",
icon: "default",
sound : "default"
}
};
I have tried to use collapse_key: "unique_key" but it has no effect. I read the has an effect only when the device is offline. I also have used a tag: "unique" but every time a new notification arrives, it will override the oldest one.
I there any way in which I can achieve this with Firebase? If I receive more then one notification, to be grouped in a single one?
Thanks in advance!
If you want to use more customizable and advanced notification features.
You should only send FCM with data payload, and create notification at android client side.
Remember that if you send FCM with notification payload or notification + data payload, the notification will be created by android core system and BroadcastReceiver's onReceive method won't being called if your app is on background.
If you send FCM with data payload, it will call onReceive all the time, so you can produce custom notification manually at android client side. (most app uses latter method.)
I hope this link would be helpful.
I had this same confusion and realized I misunderstood what collapseKey and tag are for.
collapseKey will limit the number of notifications a client receives while they're offline, tag is what will stack notifications together in the drawer.
So for a typical cloud function, it should look like this:
const notification = {
notification: {
'title': 'Interesting title',
'body': 'Hello, world'
},
'data': {
'whatever': whatever,
},
'android':{
'collapseKey': collapseKey,
'priority': 'high',
'notification': {
'tag': tag,
}
},
'token': fcmToken
};
admin.messaging().send(notification)
Note that the "tag" parameter sits inside of the android notification, not the top-level notification.
The easiest and most flexible solution is to extend the FirebaseMessagingService and handle the notification yourself. But first instead of using notification on your notificationContent in your cloud function, you have to change that to data so that you send a data message instead of a notification message. The difference is that the notification message will have an implicit collapse key (the package name of the app), while the data message won't have one. But the data message needs to be handled on the client or else it won't be displayed.
Here's a sample of what you'll need for your FirebaseMessagingService:
public class MyFCMService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
//this notification was sent from the Firebase console, because in our cloud function, we are using the DATA tag, not the notification tag
//so here we have to handle the notification that was sent from the console
...
} else if (remoteMessage.getData().get(KEY) != null) {
//this data message was sent from our cloud function
//KEY is one of the keys that you are using on the cloud function
//in your example, you are using the keys: title, body, icon, sound
//display the notification to the user
...
notificationManager.notify(TAG, ID, notificationBuilder.build());
//you have to use the same TAG and the same ID on each notification if you want your 2nd notification to simply update the text of the first one, instead of showing as a new notification
}
}
}
PS. When you send a notification from your cloud function (well if you use the data tag, it's actually a data message, not a notification message), then this method will be called, regardless if the app is in the background or in the foreground. HOWEVER, when you send a notification from the firebase console, this method will be called ONLY if the app is in the foreground. If the app is in the background, the Firebase SDK will handle the notification and show it to the user. In some cases, it makes sense to show a notification only when the user is not running the app, for example if you want to advertise some new features of the app. In that case, what you can do is use a unique tag on the notification console (e.g. "display_in_foreground") and check that tag on the client. If you have set that to true, you can show the notification even to users that are currently running the app, or if it's false you can choose not to show the notification. This check will happen only if the app is in the foreground. If it's in the background, this won't be called at all and the SDK will handle to show the notification.
I am using cordova plugin add phonegap-plugin-push plugin for push notification
In forground notification works fine.and i can handle event also.
When my app is in background then i got notification as well but on click of push notification my event is not fire.
I am using below code
$cordovaPushV5.initialize(options).then(function() {
// start listening for new notifications
$cordovaPushV5.onNotification();
// start listening for errors
$cordovaPushV5.onError();
// register to get registrationId
if (PNdeviceToken == null) //becuase registration will be done only the very first
{
$cordovaPushV5.register().then(function(registrationId) {
// save `registrationId` somewhere;
window.localStorage.setItem('PNdeviceToken', registrationId);
$rootScope.fcmToken = registrationId;
console.log(registrationId)
alert("first time registered id -- " + registrationId)
})
} else {
$rootScope.fcmToken = PNdeviceToken;
alert("already saved registered id -- " + $rootScope.fcmToken)
}
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
console.log(event)
console.log(data)
})
When i tap on background push notiction then $cordovaPushV5:notificationReceived event not fire, How can I solve this problem?
How can i handle background push notification event?
I had the Same issue and got it resolved it after 2 days of research.
Handling the notification events is same whether the app is in foreground or background.
We have to set "content-available" : "1" in the data field while pushing notifications. Else it wont call notificationReceived event if app is in background.
Also note this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Docs Page on background notifications.
Quoting from there -
On Android if you want your on('notification') event handler* to be called when your app is in the background it is relatively simple.
First the JSON you send from GCM will need to include "content-available": "1". This will tell the push plugin to call your on('notification') event handler* no matter what other data is in the push notification.
*on('notification') event handler = $cordovaPushV5:notificationReceived event in your case.
See this answer for sending custom payload messages using PHP and NodeJS
I'm implementing push notifications in a Ionic 2 app for Android. For this, I'm using the following function:
registerPush() {
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t, {ignore_user: false});
}).then((t: PushToken) => {
this.push.rx.notification().subscribe(msg => {
// execute some code
});
});
}
With this, I'm able to receive push notifications sent from server. While the app is in foreground, the execute some code part is run without problems. While the app is in the background (I'm using the background plugin), the push notification is received, but when I click on it nothing happens.
I want to execute the notification code in this situation too, and open the app when I click it. Is there any way to achieve this?
UPDATE
I've read the plugin documentation and changed the code accordingly:
registerPush() {
this.pushNotifications = Push.init({ android: { senderID: "xxxxxxxx" } });
this.pushNotifications.on('registration', data => {
// send token to server
});
this.pushNotifications.on('notification', data => {
// handle notification
});
}
With this, and with content-available set to 1 in the notification sent from server, the app executes the code whether I'm inside it or not.
However, I'm still not able to put it in foreground when I click the notification.
I work in Ionic Application, where I need to open a specific page in the app when users tap on notification,
Code
push.on('notification', function(data) {
window.plugins.toast.showShortTop('You have received a new Application!');
window.location.hash = 'home/contactus';
});
Its work fine when an application start open first time. But the problem is that when application open and that time user get any notification application redirect to 'home/contactus' page every time.
Please Help.
Unfortunately, the push plugin raises the notification event when the notification is received and again when it's clicked.
Your best bet is to assign and track the ids of notifications sent to the app:
var receivedNotifications={};
push.on('notification', function(data) {
if(!receivedNotifications[id]){
receivedNotifications[id]=true;
return;
}
window.plugins.toast.showShortTop('You have received a new Application!');
window.location.hash = 'home/contactus';
});
Consider this scenario. I have an ionic / angular app and I am using the the ngcordova plugin for push notifications. Now let us say a push notification arrives when the app is in the background. User, views the notification in the App drawer and then clicks the notification for further information. I would like the user to navigate to a particular path using $location.path(). How can I tap into the notification click event?
Ok. Turns out that there is no need to tap into the notification click event.
You could check if the app is in foreground using:
notification.foreground
so, if
if(notification.foreground) {
//do something for the case where user is using the app.
$popup('A notification just arrived');
} else {
//do something for the case where user is not using the app.
$location.path('/tab/somepage');
}
I answered a similar question some days ago. Here's the link
What i did was when the notification arrives to the app i save some data from the playload to the localStorage and then in the resume event of the app i read this var from localStorage and change the state of the app and passing this var to the url i want.
When the app is in the background and receive the notification you can save the playload to the localStorage:
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
if (ionic.Platform.isAndroid() && notification.event == 'message') {
var newsid=notification.payload.newsid;
if (typeof newsid != 'undefined') {
// save the newsid to read it later in the resume event
$window.localStorage.setItem('goafterpush',newsid);
}
}
});
And then in the resume event you can read the previous saved playload and use that data to change the state of the app and redirect to another route:
$ionicPlatform.on("resume",function(event){
// read the newsid saved previously when received the notification
var goafterpush=$window.localStorage.getItem('goafterpush');
if (goafterpush) {
$window.localStorage.removeItem('goafterpush');
$state.go('app.newsdetail',{id:goafterpush});
}
});
This can simply be done if you are using phonegap-plugin-push.
Refer the blog article from here.
push.on('notification', function(data) {
if(data.additionalData.foreground){
//Do stuff you want to do if app is running on foreground while push notification received
}else{
//Do stuff you want to do if the app is running on background while the push notification received
}
});