I'm trying to create a push notification like whatsApp or Gmail where the user avatar's is present in the notification. Is there a way to do it in react-native, especially using expo?
this is my payload for fcm
{
"GCM": "{ \"notification\": { \"title\": \"Sender1\" }, \"text\": \"test message\" } }"
}
This is an example which I got from Google which I'd like to achieve.
Answer (Source): How to set the app icon as the notification icon in the notification drawer
by user #manikanta
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Set Large icon does the trick.Comment below if you have any further info
If you're using React Native (react-native-firebase):
const notif = new firebase.notifications.Notification({
show_in_foreground: true,
})
.android.setSmallIcon('#mipmap/ic_notification') // app icon
// source image might be:
// URL
// android resource e.g. #mipmap/ic_launcher
let source_image = "";
notif.android.setLargeIcon(source_image) // user avatar
Source: https://rnfirebase.io/docs/v5.x.x/notifications/reference/AndroidNotification#setLargeIcon
Related
I've made an app using react native firebase 5.6.0. I'm getting notifications from firebase and displaying them with this piece of code:
this.notificationListener = firebase
.notifications()
.onNotification((notification: Notification) => {
notification.android
.setChannelId('channel')
.android.setSmallIcon('ic_launcher')
.android.setPriority(firebase.notifications.Android.Priority.Max)
.android.setColor('#121243');
firebase.notifications().displayNotification(notification);
});
The problem is push notifications showing even when the app is on foreground and running. I want them to only show when the app is on background.
I've solved the problem using AppState
this.notificationListener = firebase
.notifications()
.onNotification((notification: Notification) => {
if (AppState.currentState != 'active') {
notification.android
.setChannelId('channel')
.android.setSmallIcon('ic_launcher')
.android.setPriority(firebase.notifications.Android.Priority.Max)
.android.setColor('#121243');
firebase.notifications().displayNotification(notification);
}
});
So if the app is in active state the notification won't show.
I'm trying to get notifications and update launcher icon badge on IOS with React-Native/RNFirebase when app is closed. But unfortunately it seems RNFirebase doesn't have any support for it. onNotification() listener doesn't seem working when app is closed. (background modes/push notifications are enabled on XCode)
Is there any workaround for that to update launcher icon badge when notification received and app is closed?
If your app is closed, you can check if it was opened by a notification using:
firebase.notifications().getInitialNotification()
here is a sample using it:
const notificationOpen = await firebase
.notifications()
.getInitialNotification();
if (notificationOpen && notificationOpen.notification) {
let { title, body, data } = notificationOpen.notification;
if (!title && !body) {
title = data.title;
body = data.body;
}
const notification: Notification = notificationOpen.notification;
//firebase.notifications().removeDeliveredNotification(notification.notificationId);
this.handleNotificationActions(
title,
body,
data,
navigator,
t,
"background"
);
}
I am new to React Native and need to implement a functionality where the app needs to send the user a notification every day at a certain time. The data to be shown for each day is stored in a json file on the client side and will not change. The notifications are on a schedule. Given that I was hoping there could be a way to just trigger a notification from the app itself.
Does anyone know of a way to achieve this without having to detach the app from expo? I can't use 'react-native-push-notification'without running react-native link and that requires me to detach the app. Is that right?
Is this possible?
Thanks :)
You can do this with expo using the scheduleLocalNotificationAsync function (have a look at these docs for more details). Make sure you have permission to send notifications first. Note that if the notification triggers when the app is in the foreground you won't see a notification but you can still listen to this event.
i. Ask for permission
import { Permissions } from 'expo';
// ... somewhere before scheduling notifications ...
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
await Permissions.askAsync(Permissions.NOTIFICATIONS);
}
ii. Schedule the notification
import { Notifications } from 'expo';
const notification = {
title: 'Hi there!',
body: 'Tap me to open the app.',
android: { sound: true }, // Make a sound on Android
ios: { sound: true }, // Make a sound on iOS
};
const options = {
time: Date.now() + 10000, // Schedule it in 10 seconds
repeat: 'day', // Repeat it daily
};
// ... somewhere after requesting permission ...
const id = Notifications.scheduleLocalNotificationAsync(notification, options)
// If you want to react even when your app is still in the
// foreground, you can listen to the event like this:
Notifications.addListener(() => {
console.log('triggered!');
});
iii. Cancel the scheduled notification
You can use the returned id of the scheduleLocalNotificationAsync function to cancel the notification.
import { Notifications } from 'expo';
// ... get the id of the scheduled notification ...
Notifications.cancelScheduledNotificationAsync(id)
I am using react-native-fcm library for android device. I am getting notification properly when my application is running, but when my application is in the background or killed then I am getting notification data in JSON format similarly in an image I shared here.
componentDidMount() {
// iOS: show permission prompt for the first call. later just check permission in user settings
// Android: check permission in user settings
FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission rejected'));
/*FCM.getFCMToken().then(token => {
console.log('Token',token)
// store fcm token in your server
});*/
this.notificationListener = FCM.on(FCMEvent.Notification, async(notif) => {
console.log('FCM notification', notif)
this.sendRemote(notif)
});
// initial notification contains the notification that launchs the app. If user launchs app by clicking banner, the banner notification info will be here rather than through FCM.on event
// sometimes Android kills activity when app goes to background, and when resume it broadcasts notification before JS is run. You can use FCM.getInitialNotification() to capture those missed events.
// initial notification will be triggered all the time even when open app by icon so send some action identifier when you send notification
/*FCM.getInitialNotification().then(notif => {
console.log('FCM', notif)
this.sendRemote(notif)
//console.log('Initial Notification',notif)
});*/
FCM.getInitialNotification().then((notif: any) => {
// for android/ios app killed state
console.log("ifAny",notif)
if (notif) {
console.log("Any",notif)
// there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
}
});
}
sendRemote(notif) {
var data = notif.fcm.body;
var title = notif.fcm.title;
FCM.presentLocalNotification({
title: 'App Name',
body: title,
big_text: title,
large_icon: 'ic_launcher',
priority: 'high',
sound: "default",
click_action: this.clickActions(notif),
show_in_foreground: true,
wake_screen: true,
local: true,
param: notif.notify_about,
paramData: data
});
}
notify_about:'',
fcm:{action:null,
body:"{data:'',time:''}",
color:null,
icon: '',
tag:null,
title:"Notification title"}
this is my data format which I am sending from the server.
Here I want to show only data body. But when the app is killed or in the background, it shows the complete body in the notification.And Its working fine when the app is running.
I am working on a react native project which wants to receive the FCM push notification. And I am using the react-native-fcm module. What I want to do is to show the notification manually.
In this module, there is a function
import {Platform} from 'react-native';
import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
FCM.on(FCMEvent.Notification, async (notif) => {
console.log(notif);
});
where the 'notif' should be the message that was received by the device. However, I cannot receive the console.log(notif); is never called when the notification was sent to the device.
What I want to do is to use the following function to show the notification by handling the notif json manually.
FCM.presentLocalNotification({
id: "UNIQ_ID_STRING", // (optional for instant notification)
title: "My Notification Title", // as FCM payload
body: "My Notification Message", // as FCM payload (required)
sound: "default", // as FCM payload
priority: "high", // as FCM payload
click_action: "ACTION", // as FCM payload
badge: 10, // as FCM payload IOS only, set 0 to clear badges
number: 10, // Android only
ticker: "My Notification Ticker", // Android only
auto_cancel: true, // Android only (default true)
large_icon: "ic_launcher", // Android only
icon: "ic_launcher", // as FCM payload, you can relace this with custom icon you put in mipmap
});
I also realize that the message sent for FCM also would affect how the module to show the message. For more details, check FCM.
I guess my FCM setup should be correct as I can receive the notification. My react-native app can receive the notification if I send the message with key "notification". Like:
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
But the console.log(notif); in the previous function still haven't been called.
I also tried to send the notification with payload
"data" : {
"title" : "Mario",
"body" : "PortugalVSDenmark"
}
But the console.log(notif); is still not been called.
Does anyone know about the mechanism how react-native-fcm and firebase-cloud-messaging work?
Thank you so much!
Please use below code to get FCM token, which should be registered with firebase. After successful registration, You will receive the remote notifications in "notif".
FCM.on(FCMEvent.RefreshToken, (token) => {
console.log("registration token:" + token);
// fcm token may not be available on first load, catch it here
});