Push Notification not recievied on emulator using IBM MobileFirst - push-notification

I have integrated tutorial push notification application with my Android Project. Facing two issues with the app.
Issue 1:
My app registers for broadcast push notification sucessfully. And while invoking adapter to send broadcast notification, when application is in foreground it works perfectly fine.
When i press home key and then invoke adapter for broadcast notification notification, notification is not recieved on android emulator. It shows below error in logcat. Seems like GCM has pushed notification but its not sent to client.
07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): onReceive: com.google.android.c2dm.intent.RECEIVE
07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): GCM IntentService class: com.FinacleMobileApp.GCMIntentService
07-20 06:40:21.748: V/GCMBaseIntentService(1899): Acquiring wakelock
07-20 06:40:21.789: V/GCMBaseIntentService(1899): Intent service name: GCMIntentService-DynamicSenderIds-2
07-20 06:40:21.848: D/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:107 :: WLGCMIntentService: Received a message from the GCM server
07-20 06:40:21.848: V/GCMBaseIntentService(1899): Releasing wakelock
07-20 06:40:21.888: W/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:114 :: Unable to update badge while received push notification, becasue failed to parse badge number null, badge must be an integer number.
07-20 06:40:21.918: D/GCMIntentService(1899): GCMIntentService.addToIntentQueue in GCMIntentService.java:147 :: WLGCMIntentService: App is on foreground but init is not comeplete. Queue the intent for later re-sending when app is back on foreground.
07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): onReceive: com.google.android.c2dm.intent.RECEIVE
07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): GCM IntentService class: com.FinacleMobileApp.GCMIntentService
07-20 06:40:21.748: V/GCMBaseIntentService(1899): Acquiring wakelock
07-20 06:40:21.789: V/GCMBaseIntentService(1899): Intent service name: GCMIntentService-DynamicSenderIds-2
07-20 06:40:21.848: D/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:107 :: WLGCMIntentService: Received a message from the GCM server
07-20 06:40:21.848: V/GCMBaseIntentService(1899): Releasing wakelock
07-20 06:40:21.888: W/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:114 :: Unable to update badge while received push notification, becasue failed to parse badge number null, badge must be an integer number.
07-20 06:40:21.918: D/GCMIntentService(1899): GCMIntentService.addToIntentQueue in GCMIntentService.java:147 :: WLGCMIntentService: **App is on foreground but init is not comeplete.Queue the intent for later re-sending when app is back on foreground.
Issue 2:
In same application i am trying to register a Tag(OFFERS) for notification. I am invoking subscribe method for this tag. Code is as follows.NotificationCenter.js is used. when i invoke subscribeForTagNotification (higlighted below) function from my appcontroller. I get Cant Subscribe, notification token is not updated on the server.
Kindly let me know if i am missing anything. SubscribeforTagNotification function is called immediately after MF server connection call is initiated. My app used WL.client.init to make a connection with connectOnStartUp as true.
AppController.factory('NotificationCenter', ['$http', '$rootScope', '$q', '$location', '$timeout',
function($http, $rootScope, $q, $location, $timeout) {
if (WL.Client.Push) {
WL.Logger.debug("Ganesh Notification center on ready to subscribe");
//WL.Client.connect({onSuccess: connectSuccess, onFailure: connectFailure});
WL.Logger.debug("Ganesh connection waiting complete");
WL.Client.Push.onReadyToSubscribe = function() {
WL.SimpleDialog.show("Tag Notifications", "Ready to subscribe", [ {
text : 'Close',
handler : function() {}
}
]);
};
}
function doSubscribeSuccess() {
WL.Logger.debug("Ganesh doSubscribeSuccess");
WL.SimpleDialog.show("Tag Notifications", "Subscribed to tag",[{
text:'Close',handler :function(){}
}]);
}
function doSubscribeFailure() {
WL.Logger.debug("Ganesh doSubscribeFailure");
WL.SimpleDialog.show("Tag Notifications", "Subscribed to tag",[{
text:'Close',handler :function(){}
}]);
}
WL.Client.Push.onMessage = function (props, payload) {
WL.SimpleDialog.show("Tag Notifications", "Provider notification data: " + JSON.stringify(props), [ {
text : 'Close',
handler : function() {
WL.SimpleDialog.show("Tag Notifications", "Application notification data: " + JSON.stringify(payload), [ {
text : 'Close',
handler : function() {}
}]);
}
}]);
};
return {
init: function() {
},
**subscribeForTagNotification:function()**{
WL.Logger.debug("Ganesh doSubscribe feature"+WL.Client.Push.isTagSubscribed("OFFERS"));
if (WL.Client.Push && !WL.Client.Push.isTagSubscribed("OFFERS")) {
WL.Logger.debug("Ganesh doSubscribe feature entered");
WL.Client.Push.subscribeTag("OFFERS", {
onSuccess: doSubscribeSuccess,
onFailure: doSubscribeFailure
});
}
}
};
}]);
IBM MobileFirst version: 6.3.0.00-20141127-1357
Platform:Android

For Push notification to be working on Emulator you need to have
Target : Google API else it wont work on you Emulator.
i hope you get what i am trying to say target refers to the AVD
(Anddroid Virtual Device Target) for your created Virtual device.

If your organization has a firewall that restricts the traffic to or from the Internet, you must go through the following steps:
Configure the firewall to allow connectivity with GCM so that your GCM client apps can receive messages. The ports to open are 5228, 5229, and 5230. GCM typically uses only 5228, but it sometimes uses 5229 and 5230. GCM does not provide specific IP, so you must allow your firewall to accept outgoing connections to all IP addresses that are contained in the IP blocks listed in Google ASN of 15169. For more information, see Implementing an HTTP Connection Server.
Ensure that your firewall accepts outgoing connections from MobileFirst Server to android.googleapis.com on port 443.

Related

How to receive FCM push notifications in service worker in Chrome Extension

I'm sending an FCM push notification from a Firebase backend to a Chrome Extension. I get it to show successfully in my Chrome Extension when it's in focus. I want it to show even if the Extension isn't in focus, but I can't get the service worker that's supposed to handle the notification even to fire.
I followed the Google tutorial to set up my JavaScript Chrome Extension client. I already tried this solution to not include a "notification" payload in my message, and this solution to register the worker manually (even though the tutorial doesn't say anything about either), but to no avail.
My service worker firebase-messaging-sw.js looks like this:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
This is the POST request I use to send notifications (obviously with the correct SERVER_KEY and USER_TOKEN values):
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=<SERVER_KEY>
Cache-Control: no-cache
{
"data": {
"title": "Firebase",
"body": "Firebase is awesome",
"click_action": "http://localhost:5000/",
"icon": "http://localhost:5000/firebase-logo.png"
},
"to": "<USER_TOKEN>"
}
How do I get the service worker to receive the push notification and display it?
Thanks in advance :)
You can use Push API in service worker (firebase-messaging-sw.js):
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-messaging.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
this.onpush = event => {
console.dir(event.data.json());
// Here you can use event.data to compose Notification
// #see https://www.w3.org/TR/push-api/#pushmessagedata-interface
};

firebase cloud messaging: setBackgroundMessageHandler not called

I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.

cordova-plugin-fcm - FCMPlugin is not defined

I am using Ionic 2, and am trying to get Push Notifications working.
I have registered my app with Firebase, and can push notifications to it successfully.
I now need to set up, so that I can push notifications from my app. So I decided to use the following Cordova Plugin (cordova-plugin-fcm).
Question 1
When I follow it's instructions, by doing the following in my Ionic app:
app.ts
declare var FCMPlugin;
...
initializeApp() {
this.platform.ready().then(() => {
...
FCMPlugin.getToken(
function (token) {
....
I get the following Error at runtime:
EXCEPTION: Error: Uncaught (in promise): ReferenceError: FCMPlugin is
not defined
How do I solve this please?
Question 2
In order to send notifications from your app, the Cordova Plugin (cordova-plugin-fcm) instructs the following:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", //Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"/topics/topicExample", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"" //Optional. Set for application filtering
}
This is not even Typescript or Javascript. So where does it go? I just don't understand. Any advise appreciated.
You should have FCMPlugin.js included in your HTML index file
find the path for js file into plugins directory of the app
Example : MyFCM\plugins\cordova-plugin-fcm\www\FCMPlugin.js
app.controller('AppCtrl', function(FCMPlugin,$scope,$cordovaToast,$cordovaDialogs,ionPlatform) {
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
console.log('I am working');
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$cordovaDialogs.alert(data.notification.body);
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
$cordovaDialogs.alert(data.notification.body);
//$cordovaToast.showShortCenter( JSON.stringify(data) );
}
},
function(msg){
$cordovaToast.showShortCenter('onNotification callback successfully registered: ' + msg);
},
function(err){
$cordovaToast.showShortCenter('Error registering onNotification callback: ' + err);
}
);
});
})

Check if App was opened from a push notification

I am required to send statistics if the app was opened or resumed from push notification.
How do I detect it in Titanium?
in particular, on iOS (on Android, I believe that the cgm module I am using has an event)
On iOS, for received notifications (within iOS App and not from lock screen, though they will be triggered when tapped/swiped on from lock screen), you can use the following:
For iOS Remote Notifications:
When registering for Push Notifications, use the call back function to listen for all incoming remote notifications.
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess, // TODO store the token
error: deviceTokenError, // TODO
callback: receivePush // function below
});
function receivePush(e) {
alert('Received push: ' + JSON.stringify(e));
// Do what you need for Analytics here
}
For iOS Local Notification with Actions (iOS 8+)
Ti.App.iOS.addEventListener("localnotificationaction",function(){
//my code
});
For iOS Local Notifications:
Ti.App.iOS.addEventListener('notification',function(){
// send analytics
});

push notification does not work for ios and azure with specific token

We are using Visual Studio to create an Apache Cordova app that is connected to an Azure Mobile Service . We are using the Cordova Push Plugin to receive Notifications in our app. We have created a JavaScript method in the Azure Mobile Service to send the notifications, this method is triggered by a scheduler. Please note that the intention is to send each Notification to a particular device.
The notifications work perfectly for Android devices but not for the iOS devices.
In iOS the notification is not received however the method in Azure Mobile Service always returns “Success”.
If we set the Device Token to "Null" , then it works for iOS devices (but sends to all devices not just one).
Could anyone please help us to resolve this issue?
this is Push.Send() method in Azure
push.send(result.DeviceID, payload, {
success: function(pushResponse){
//console.log("Sent push:", pushResponse);
//update notification sent time-start
var sqlUpdate = '';
mssql.query(sqlUpdate, {
success: function(results)
{
//response.json(statusCodes.OK, results);
},
error : function()
{
//response.send(statusCodes.INTERNAL_SERVER_ERROR);
}
})
//update notification sent time-end
},
error: function (pushResponse) {
//console.log("Error Sending push:", pushResponse);
}
});
and this is my App registration Method in the app
var pushNotification = window.plugins.pushNotification;
//alert("device.platform" + device.platform);
// Platform-specific registrations.
if (device.platform == 'android' || device.platform == 'Android') {
alert("device.platform : Android ");
// Register with GCM for Android apps.
pushNotification.register(
app.successHandler, app.errorHandler,
{
"senderID": GCM_SENDER_ID,
"ecb": "app.onNotificationGCM"
});
} else if (device.platform === 'iOS') {
// Register with APNS for iOS apps.
alert("device.platform : iOS ");
pushNotification.register(
app.tokenHandler,
app.errorHandler, {
"badge":"true",
"sound":"true",
"alert":"true",
"ecb": "app.onNotificationAPN"
});
}
else if(device.platform === "Win32NT"){
// Register with MPNS for WP8 apps.
alert("Device platform Windows")
pushNotification.register(
app.channelHandler,
app.errorHandler,
{
"channelName": "MyPushChannel",
"ecb": "app.onNotificationWP8",
"uccb": "app.channelHandler",
"errcb": "app.ErrorHandler"
});
}
// #endregion notifications-registration

Resources