Ionic 2 Push Notifications with FCM - android

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.

Related

Local Notification with Notifee does not displaying in Android

I am having an issue where the local notification is not displaying in android though it is displaying in IOS. I have created permissions and battery optimization check to see if that is the problem. The notification does make a sound and appear shows a little square in the upper left that if I click and drag does show the local notification. I am using an emulator right now and I have tried it on a real device.
This is the way I am calling the notification.
<Button
title="Trigger Push Notification"
size="large"
onPress={() => onDisplayNotification('default', 'Default Channel', 'Spotback
Android', 'Local push notification')}
/>
This is is the Notifee component.
import notifee, { AndroidStyle, AuthorizationStatus, Notification } from '#notifee/react-native';
import { Alert } from 'react-native';
export const onDisplayNotification = async (id, name, title, body, smallIcon?) => {
// Request permissions (required for iOS)
await notifee.requestPermission();
const settings = await notifee.getNotificationSettings();
const batteryOptimizationEnabled = await notifee.isBatteryOptimizationEnabled();
if (batteryOptimizationEnabled) {
// 2. ask your users to disable the feature
Alert.alert(
'Restrictions Detected',
'To ensure notifications are delivered, please disable battery optimization for the app.',
[
// 3. launch intent to navigate the user to the appropriate screen
{
text: 'OK, open settings',
onPress: async () => await notifee.openBatteryOptimizationSettings(),
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
],
{ cancelable: false }
);
}
if (settings.authorizationStatus == AuthorizationStatus.AUTHORIZED) {
console.log('Notification permissions has been authorized');
} else if (settings.authorizationStatus == AuthorizationStatus.DENIED) {
console.log('Notification permissions has been denied');
}
// }
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id,
name,
});
await notifee.displayNotification({
title,
body,
android: {
channelId,
smallIcon,
pressAction: {
id,
},
},
});
};
Please change your channel id (default) and channel name (Default Channel) to something else like:
id: custom_channel
name: custom_channel

Why is notification navigation routing not working when app is in background using FCM in Ionic Angular app

I have installed FCM notification plugin and added following code in
FCM.onNotification().subscribe(data => {
if (data.wasTapped) {
this.route.navigateByUrl(`${data.routeUrl}`);
console.log("Received in background");
} else {
this.localNotifications.schedule({
title: data.title,
text: data.body,
foreground: true
})
this.localNotifications.on("click").subscribe((notification: any) => {
this.navCtrl.navigateForward([data.routeUrl]).then((entry) => {
}).catch((err) => {
console.log('Error while navCtrl:- ' + JSON.stringify(err));
});
})
console.log("Received in foreground");
};
});
With this I am able to navigate to a screen from the path provided in the body of notification when app is open but when app is in closed state or in background I'm unable to navigate to that screen
Please help me out regarding this issue
Regards

React Native PushNotification onNotification method

I am Getting notification from server. After receiving the notification, When I click on it, then again the same notification is coming. More I click on it more the notifications are coming.
My question is whether I am following the right approach in the above code? If not then please suggest me the correct one. How to handle the click of notification? So, that i can show the particular view on its click.
I'm using the following link
https://github.com/zo0r/react-native-push-notification
Thanks in advance :)
PushNotification.configure({
onNotification: function (notification) {
console.log('NOTIFICATION:', notification)
PushNotification.localNotification({
largeIcon: "ic_launcher",
title: notification.title,
message: notification.message,
});
},
senderID: "my sender ID",
popInitialNotification: true,
requestPermissions: true,
});
I have tried the following approach to solve this problem
PushNotification.configure({
onNotification: function (notification) {
console.log('NOTIFICATION:', notification)
const clicked = notification.userInteraction;
if (clicked) {
ToastAndroid.show(notification.message,ToastAndroid.CENTER);
} else {
PushNotification.localNotification({
largeIcon: "ic_launcher",
title: "Test",
//message: JSON.stringify(xyz.notificationResponse.bookingId),
});
}
ToastAndroid.show(notification.message,ToastAndroid.CENTER);
},
senderID: "your sender id",
popInitialNotification: true,
requestPermissions: true,
});

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?

Application stops When receive a notification from Firebase Notifications

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)); }

Categories

Resources