index.js
...
const Navigation () => {
...
// noti
useEffect(() => {
notifee.onForegroundEvent(async ({ type, detail }) => {
console.log("App.js notifee onForegroundEvent==============");
if (type === EventType.PRESS) {
// 처리할 이벤트 추가
} else if (type === EventType.DISMISSED) {
// noti 삭제
notifee.cancelNotification(detail.notification.id);
notifee.cancelDisplayedNotification(detail.notification.id);
}
});
notifee.onBackgroundEvent(async ({ type, detail }) => {
console.log("App.js notifee onBackgroundEvent==============");
if (type === EventType.PRESS) {
// 처리할 이벤트 추가
} else if (type === EventType.DISMISSED) {
// noti 삭제
notifee.cancelNotification(detail.notification.id);
notifee.cancelDisplayedNotification(detail.notification.id);
}
});
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log("App.js setBackgroundMessageHandler=========");
console.log(remoteMessage);
await PushNoti.displayNoti(remoteMessage);
});
messaging().onMessage(async remoteMessage => {
let chat_id = '';
let topic_id = '';
console.log("App.js onMessage ====================");
chat_id = remoteMessage.data.chat_id;
topic_id = remoteMessage.data.topic_id;
let current_chat_id = navigationRef?.getCurrentRoute().params?.chat_id;
let current_topic_id = navigationRef?.getCurrentRoute().params?.topic_id;
if ((current_chat_id !== chat_id) && (current_topic_id !== topic_id)) {
await PushNoti.displayNoti(remoteMessage);
}
});
}, []);
...
}
PushNoti.js
import { Platform } from 'react-native';
import notifee, { AndroidImportance } from '@notifee/react-native';
const displayNotification = async message => {
var id = undefined;
if (message.data.data === undefined || message.data.data === null) {
if (message.data.chat_id !== '_') {
id = message.data.chat_id;
} else if (message.data.topic_id !== '_') {
id = message.data.topic_id;
}
} else {
id = message.data.data.filePath;
}
if (Platform.OS !== 'ios') { // ANDROID
await notifee.createChannel({
id: id,
name: name,
importance: AndroidImportance.HIGH,
sound: 'sound'
}).then(async result => {
await notifee.displayNotification({
id: id,
title: message.data.title,
body: message.data.body,
android: {
channelId: result,
smallIcon: 'ic_stat_name',
color: '#5E9441',
sound: 'sound',
timestamp: Date.now(),
showTimestamp: true,
},
chat_id: message.data.chat_id,
topic_id: message.data.topic_id,
data: message.data
});
})
} else { // IOS
notifee.displayNotification({
id: id,
title: message.data.title,
body: message.data.body,
chat_id: message.data.chat_id,
topic_id: message.data.topic_id,
data:message.data,
ios: {
sound: 'default',
}
});
}
};
export default {
displayNoti: remoteMessage => displayNotification(remoteMessage),
};
id를 설정해준 이유는 새로운 메시지를 수신했을 때 id를 이용하여 해당 notification을 최근 수신한 메시지로 업데이트 해주기 위함이다.
https://notifee.app/react-native/docs/overview
https://notifee.app/react-native/docs/displaying-a-notification#updating-a-notification