GCM Android notification received on device but not displaying - javascript

GCM Cloud messaging notifications for my Ionic Android app are not appearing in my device's home screen, despite the notification registering in the app itself.
I'm using the npm module node-gcm to send push notifications.
var gcm = require('node-gcm');
var message = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 10,
dryRun: false,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP."
}
});
var regIds = ['*device id*'];
var sender = new gcm.Sender('*api key*');
sender.send(message, { registrationIds: regIds }, function (err, result) {
if(err) console.error(err);
else console.log(result);
});
When I send a push notification to my device's ID, I get a successful response:
{ multicast_id: 8406385547051869000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1441962697347777%b67ee170f9fd7ecd' } ] }
I then get the following message in my Android Studio console:
V/GCMBroadcastReceiver﹕ onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver﹕ GCM IntentService class: com.plugin.gcm.GCMIntentService
V/GCMBaseIntentService﹕ Acquiring wakelock
V/GCMBaseIntentService﹕ Intent service name: GCMIntentService-GCMIntentService-5
D/GCMIntentService﹕ onMessage - context: android.app.Application#2dc6dbff
V/GCMBaseIntentService﹕ Releasing wakelock
In the Google Play Developer Console GCM Debugger, my notifications also to appear to have been confirmed.
0: 1441899623073525% b67ee170f9fd7ecd Confirmed
Other than this I receive no error message in the Android Studio console when a notification has been received.
The Ionic app itself registers the notification once I've sent one. However when I'm out of the app. no notification is displayed in the home screen.
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
alert(notification);
if (ionic.Platform.isAndroid() && notification.event == "registered") {
window.localStorage['token'] = notification.regid;
var params = {
deviceType: 'android',
tokenId: notification.regid
};
NotificationService.registerDevice(params);
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge);
}
//notifications payload
if (notification.foreground == '0') {
if (notification.view) {
$timeout(function () {
$state.go('app.notifications');
});
} else {
if (notification.id) {
NotificationService.markNotificationAsRead(notification.id).success(function () {
$rootScope.$emit('notifications-read');
});
}
if (notification.chat) {
$timeout(function () {
$state.go('app.message', {id: notification.chat});
});
} else if (notification.post) {
$timeout(function () {
$state.go('app.singlePost', {id: notification.post});
});
} else if (notification.group) {
$timeout(function () {
$state.go('app.group', {id: notification.group});
});
}
}
}
});

You must add icon field in your notification block:
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP.",
icon: "#drawable/ic_launcher"
}

I was having the same issue, using the sample provided at the node-gcm page. After struggling for quite some time i came across this blogpost: http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
and modified my code according to the example provided in the blog post.
i guess there is an issue with "notification" object on node-gcm code, using message.addData seems to make it work,
in short replacing the message creation and sending logic as below worked for my application :
// For Android
if (row.device === "Android" && row.deviceToken) {
console.log(row.deviceToken);
var sender = new gcm.Sender(serverApiKey);
var message = new gcm.Message();
message.addData('title','İş Geliştirme Platformu');
message.addData('message','Yeni İleti');
message.addData('msgcnt','1');
//message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
var registrationIds = [];
registrationIds.push(row.deviceToken);
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
res.send(200,result);
});
}

add your server IP to white list and try again:
console.developers.google.com > APIs & auth > credential > select your server key > and add your server IP

Related

request not updating (electron.js)

(sorry my english is poor)
Hi, i'm new with electron.js i'm building an app can get temp mails ... the app is working but the problem is the content not updating. when i send a email to the temp-mail this not appairs but if i close and open the app the inbox appairs... i don't know what is the problem.
Here is the code:
renderer.js
input_inbox.addEventListener("click", async () => {
const email_inbox = input_email.value; // get mail generate randomly and pass
window.TempMail.getInbox(email_inbox); // to the main process
window.TempMail.send('sending', (data) => {console.log(data)});
});
main.js
ipcMain.on("getInbox", (event, arg) => {
var address = new TempMail(arg); // get from renderer and create email
address.fetchEmails(function (err, body) {
console.log(body) // show the content in console.
mainWindow.webContents.send('sending', body.messages[0].from)
if (!body.messages[0]?.from === undefined) {
console.log(body.messages[0].from);
}
});
});
At this point, if i send an email to the generate email this not have inbox until close and open the app.
console.log before close and open the app.. :
{
address: 'PjrlERcEoEPU#1secmail.com#1secmail.com',
messageCount: 0,
messages: []
}
console.log after close and open the app:
{
address: 'PjrlERcEoEPU#1secmail.com',
messageCount: 1,
messages: [
{
from: 'my-email#gmail.com',
timestamp: '2022-09-04 20:03:04',
subject: 'skajj',
message: 'kjkjkj\n'
}
]
}

Show push message in chrome

I want to show push notification using a service worker. In the developer tools -> Application -> Service workers I have the test text "a": "test message", I press the push and get the following error:
serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute
'showNotification' on 'ServiceWorkerRegistration': No notification
permission has been granted for this origin.
How can I fix this? When you click on the push button, should the notification pop up?
For Push messages, you need two API's setup Notification API and Push API.
First things first, ask permission of the client for notification. Unless that is granted nothing works. So in your index.js/App.js place this snippet:-
function askForNPerm() {
Notification.requestPermission(function(result) {
console.log("User choice", result);
if (result !== "granted") {
console.log("No notification permission granted!");
} else {
configurePushSub();// Write your custom function that pushes your message
}
});
}
Once you are allowed with the permission, then call your Push function that has message to display.
It's Work. You also need to check if your browser has permission.
self.addEventListener('push', (event) => {
const options = {
body: 'This notification was generated from a push!',
icon: '',
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
actions: [
{
action: 'explore', title: 'Explore this new world',
icon: ''
},
{
action: 'close', title: 'Close',
icon: ''
},
]
};
event.waitUntil(
self.registration.showNotification('Title', options)
)
});

React Native Firebase, Notification not showing when the app is in foreground, only on Android 8 or later with bundle build

I have an app with react-native-firebase notification, the message is sucessfully received and the notification is successfully created and displayed on Android Nougat or older, on Android Oreo or later I have adding channelId it works well when using react-native run-android, but when using bundle (cd android && ./gradlew installRelease) my notification is not displayed only in foreground on Android Oreo or later, on background works. Didn't know the problem is on message listener or when creating notification. Here is my code...
I call function below after having permissions, to listening message when the app is in foreground
export const listening_message = () => {
return firebase.notifications().onNotification((notification) => {
display_notification({
notification_param: {
sound: 'default',
show_in_foreground: true,
},
title: notification.title,
subtitle: notification.subtitle,
body: notification.body,
data: notification.data,
});
});
}
then this is the code to display notification
async function display_notification(parameter) {
let realmUser = await Realm.open(RealmData.User);
if(realmUser.objects(RealmDataName.User).length > 0) {
let realmNotification = await Realm.open(RealmData.NotificationID);
if(realmNotification.objects(RealmDataName.NotificationID).length == 0) {
realmNotification.write(() => {
realmNotification.create(RealmDataName.NotificationID, {
id: 0,
})
});
}
if(realmNotification.objects(RealmDataName.NotificationID).length == 0) {
realmNotification.write(() => realmNotification.create(RealmDataName.NotificationID, {id: 0}));
}
const channel = new firebase.notifications.Android.Channel(
'channelId',
'Channel Name',
firebase.notifications.Android.Importance.High
).setDescription('Description of the channel');
firebase.notifications().android.createChannel(channel);
let new_notification = new firebase.notifications.Notification(parameter.notification_param)
.setNotificationId(realmNotification.objects(RealmDataName.NotificationID)[0].id.toString())
.setTitle(parameter.title)
.setSubtitle(parameter.subtitle)
.setBody(parameter.body)
.setData({
id: realmNotification.objects(RealmDataName.NotificationID)[0].id.toString(),
...parameter.data,
});
if(Platform.OS == "android") {
new_notification.android.setVibrate(1000)
.android.setSmallIcon('ic_launcher')
.android.setColor('#000000');
if(Platform.Version <= 25) {
new_notification.android.setPriority(firebase.notifications.Android.Priority.High);
} else {
new_notification.android.setChannelId("channelId");
}
} else if(Platform.OS == "ios") {
new_notification.ios.setBadge(1);
}
firebase.notifications().displayNotification(new_notification);
realmNotification.write(() => realmNotification.objects(RealmDataName.NotificationID)[0].id++);
}
}

Pubnub.subscribe not working

I am trying to implement a simple chat in my AngularJs 1.4.5 web app using pubnub.
I am following the steps as given in the pubnub tutorial.
$scope.channel = 'chat_for_trial';
$scope.uuid = 'user1';
Pubnub.init({
publishKey: 'demo',
subscribeKey: 'demo',
uuid: $scope.uuid
});
// Send the messages over PubNub Network
$scope.messageContent = {message: ''};
$scope.sendMessage = function() {
// $scope.messageContent = data;
// Don't send an empty message
if (!$scope.messageContent.message || $scope.messageContent.message === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent.message,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
// Reset the messageContent input
$scope.messageContent.message = '';
};
//get messages
$scope.messageContent.messages = [];
// Subscribing to the ‘messages-channel’ and trigering the message callback
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
// Listening to the callbacks
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, m) {
$scope.$apply(function () {
console.log("i am here")
$scope.messageContent.messages.push(m)
});
});
I can send message to the channel chat_for_trial but when checking the occupancy in pubnub console, the subscribed uuid is not listed.
When I sending the message from console it is not displayed in the web app. But data sent from web app can be seen in the pubnub console.
I am working with pubnub: 4.20.1, pubnub-angular: 4.1.0, angularjs: 1.4.5
I would like to know what I am missing here.
The issue was due to the mismatch of the pubnub and pubnub-angular version from the tutorial and the one installed using bower in my application.
The tutorial was for sdk v3 and the current sdk version v4.
Refer this link for working with pubnub sdk v4.

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

Categories

Resources