Application stops When receive a notification from Firebase Notifications - android

My application stops when you receive a notification, when the app is open, but when the application is not active, it receives 2 notifications.
Here is my initPushNotification():
initPushNotification(){
if(!this.platform.is('cordova')){
console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
return;
}
const options: PushOptions = {
android: {
senderID:"XXXXXXXXXXXX",
vibrate: true
},
ios: {
alert: "true",
badge: false,
sound: "true"
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((data:any)=>{
console.log("device token", data.registrationId);
//Here I send the device_token to my firebase database.
});
pushObject.on('notification').subscribe(()=>{
alert("new Message");
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error)); }

Related

How to correctly specify channel_id in FCM using cloud functions

Unfortunately, no answer yet. I am checking out postman, I hope I can use that to test quicker.
I manage to send a notification through my app, however, the notification always ends up in the silent notification of my phone, no sound, no vibration and no notification icon in the top left of the phone, only a notification in the drawer when I swipe down :(
In an attempt to fix / improve the situation I tried the following:
Create an android notification channel with id: high_importance_channel by using flutter_local_notifications package. The channel was created successful, because requesting an overview of the existing channels, showed the newly created channel (among the other channels). The new channel has importance: 5, enableVibration: true and playSound: true, so that should do the job.
Send a FCM through cloud functions with the following code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.chatNotification = functions.firestore
.document('chats/{groupId}/chat/{chatId}')
.onCreate( async (snapshot, context) => {
const message = {
"notification": {
"title": "Message Received",
"body": "Text Message from " + fromUserName,
},
"tokens": registrationTokens,
"android": {
"notification": {
"channel_id": "high_importance_channel",
},
},
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
}
But so far not luck, the notification still ends up in the silent notifications. What am I doing wrong?
There are 2 ways of doing it. Might work in your case.
Way 1:
var payload = {
notification: {
android_channel_id: 'AppChannel',
/*
https://stackoverflow.com/questions/62663537/how-do-i-add-a-channelid-to-my-notification
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
*/
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
sound: 'default',
},
data: {
route: '/someRoute',
},
};
try {
const response = await admin.messaging().
sendToDevice(deviceTokens, payload);
console.log('Notification sent succesfully.');
} catch (err) {
console.log('Error sending Notifications...');
console.log(err);
}
Way 2:
const message = {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.basemessage.md#basemessagenotification
*/
notification: {
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
},
data: {
route: '/someRoute',
},
android: {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidnotification.md#androidnotificationbodylockey
*/
notification: {
channelId: "AppChannel",
priority: 'max',
defaultSound: 'true',
},
},
token: deviceTokens,
};
// https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.messaging.md#messagingsend
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message, for LOVEs sake:', error);
});

Ionic 2 Push Notifications with FCM

I'm implementing Push Notifications on my Android Ionic 2 App with the Ionic Native FCM
When I'm receiving a notification in the foreground it works, but when I'm receiving a notification in the background and if I clicked on it, nothing happens.
app.component.ts
firebaseInit(){
//Firebase
this.fcm.subscribeToTopic('all');
this.fcm.getToken()
.then(token => {
console.log(token);
this.nativeStorage.setItem('fcm-token', token);
});
this.fcm.onNotification().subscribe(
data => {
console.log("NOTIF DATA: " + JSON.stringify(data));
if(data.wasTapped){
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
console.info('Received in bg')
}else{
let alert = this.alertCtrl.create({
title: data.subject,
message: "New memorandum",
buttons: [
{
text: 'Ignore',
role: 'cancel'
},
{
text: 'View',
handler: () => {
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
}
}
]
});
alert.present();
console.info('Received in fg')
}
});
this.fcm.onTokenRefresh()
.subscribe(token => {
console.log(token);
})
}
The if(data.wasTapped) condition doesn't go off once I clicked the notification from the system tray.
EDIT
The app opens but only in the Home Page not to the designated page that I set which is this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
I also cannot receive notifications when the app is killed or not running.
you could use push plugin instead of FCM.
this.push.createChannel({
id: "testchannel1",
description: "My first test channel",
importance: 3
}).then(() => console.log('Channel created'));
and then you could use pushObjects to specify the needs for your notification like sound, ion etc.
const options: PushOptions = {
android: {},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
After that it is easy for you to receive notifications whether you are using the app or not
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((registration: any) => this.nativeStorage.setItem('fcm-token', token));
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
you could use the option of forceShow:true in the pushObject init for the app to show the notification whether you are using the app or not.
And once you clicked the notification the notification payload is received by the app with the app home page set as default.

No custom icon or sound in Ionic Native Push

I am trying to get this working https://ionicframework.com/docs/native/push/
With FireBase Cloud Messaging
Here is the code
import { Push, PushObject, PushOptions, AndroidPushOptions, IOSPushOptions } from '#ionic-native/push';
pushsetup() {
const options: PushOptions = {
android: {
senderID: '**********',
icon: "notification",
iconColor: "blue",
sound: true,
vibrate: true,
forceShow: true
},
ios: {
alert: true,
badge: true,
sound: true
},
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
if (notification.additionalData.foreground) {
let youralert = this.alertCtrl.create({
title: 'New Push notification',
message: notification.message
});
youralert.present();
}
});
pushObject.on('registration').subscribe((registration: any) => {
//do whatever you want with the registration ID
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
How push looks now:
Unfortunately there is still no custom icon or sound or vibration :(
I copied the notification png, basically everywhere now in the android/res folder :)
Has anyone had any success with this? Do you actually have to use the AndroidPushOptions import anywhere?

Ionic push notification is not working if app is open

I am able to send push form apps.ionic.io and from postman when app is on background or screen is locked but not able to send notification when app is open.
My code is as
in run
var io = Ionic.io();
var push = new Ionic.Push({
"onNotification": function(notification) {
alert('Received push notification!');
},
"pluginConfig": {
"android": {
"icon": "ic_stat_icon"
}
},
"debug": true
});
push.register(function(token) {
console.log("registered");
console.log("Device token:",token.token);
});
and in controller
$ionicPush.register( {
canShowconsole.log: true, //Can pushes show an console.log on your screen?
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
console.log(notification);
// Handle new push notifications here
alert('Received push notification!');
return true;
}
}).then(function(t) {
return $ionicPush.saveToken(t);
}).then(function(t) {
console.log('Token saved:', t.token);
});
Try this thing in your app.js or controller file.
$rootScope.$on('cloud:push:notification', function(event, data) {
var msg = data.message;
console.log(msg);
// alert(msg.title + ': ' + msg.text);
var alertPopup = $ionicPopup.alert({
title: msg.title,
template: msg.text.toString()
});
});

Ionic push notifications on Android doesn't register token on Ionic.io

I want to implement push notification on Android using ionic.
I've followed the documentation from Ionic push in a tutorial from devdactic Devdactic push notifications android I see with that example in the platform is saved a token.
I've make all settings that I need including GCM service and register user to ionic platform, but no token is registered.
I run app in emulator and user is registered but no token is saved. After some modifiers I receive a token in console but is not ok.
In example token is different and push does't work. Does someone have an working example with Ionic Push based on last documentation?
this is what I use to register pushes, it is messy but hopefully can be of some use. It checks if the current user is authenticated, if they aren't then it signs them up with a UUID (i used a UUID generator plugin) and saves the token. Just make sure your app is set up with Ionic.io and this should work :)
var user = Ionic.User.current();
if (user.isAuthenticated()) {
var push = new Ionic.Push({
"debug": true,
"onNotification": function (notification) {
},
"onRegister": function (data) {
console.log(data.token);
return true;
},
"pluginConfig": {
"android": {
"icon": "icon"
},
"ios": {
"badge": true,
"sound": true,
"alert": true
}
}
});
} else {
var uid = uuid2.newuuid();
var details = {
'email': uid + '#example.com',
'password': 'secretpassword'
};
Ionic.Auth.signup(details).then(function () {
var options = { 'remember': true };
Ionic.Auth.login('basic', options, details).then(function () {
user = Ionic.User.current();
user.set('uid', uid);
user.save();
var push = new Ionic.Push({
"debug": true,
"onNotification": function (notification) {
},
"onRegister": function (data) {
console.log(data.token);
return true;
},
"pluginConfig": {
"android": {
"icon": "icon"
},
"ios": {
"badge": true,
"sound": true,
"alert": true
}
}
});
push.register(function (token) {
console.log("Device token:", token.token);
push.saveToken(token);
});
}, function () { });
}, function () { });
}
In order to send push notification you need Api key and project number and current device id.
I think you are struggling in getting the user device id in order to get the current your device id please reffer ng-Cordova
you can find a line
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification)
in this you can see the notification parameter it is an object inside that object you can find regid field in that you can get your current device id this will be work on only mobile not on browser.
so in order to use that device id, for example lets assume your going to post a login form with divece id like given below.
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
console.log(event);
console.log(notification);
switch(notification.event) {
case 'registered':
console.log(notification.regid.length);
if (notification.regid.length > 0 ) {
// alert('registration ID = ' + notification.regid);
console.log('registration ID = ' + notification.regid);
var loginPost = {
"UserName":username,
"PassWord":password,
"DeviceID":notification.regid
};
console.log(loginPost);

Categories

Resources