2020/12/10 - [React Native] - [React Native] Android 알람 구현하기 1(Push notification)-firebase
[React Native] Android 알람 구현하기 1(Push notification)-firebase
현재 진행중인 앱 프로젝트에서 메세지가 오거나 매칭이 완료되면 알람이 오는 기능을 구현하고 싶었다. 그래서 한번 배워보았다. firebase를 사용하였따 1. 프로젝트 생성 npx react-native init [파일
coding-hyeok.tistory.com
1. Install the messaging module
npm install --save @react-native-firebase/messaging
2. install the react-native-push-notification module
npm install --save react-native-push-notification
3. code
src 폴더내에 FCMService, LocalNotificationService.js 두개를 만들었다.
LocalNotificationService의 코드는 다음과 같다.
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import {Platform} from 'react-native';
class LocalNotificationService {
configure = (onOpenNotification) => {
PushNotification.configure({
onRegister: function (token) {
console.log(
'[LocalNotificationService] onRegister : localtoken',
token,
);
},
onNotification: function (notification) {
console.log('[LocalNotificationService] onNotification ', notification);
if (!notification?.data) {
return;
}
notification.userInteraction = true;
onOpenNotification(
Platform.OS === 'ios' ? notification.data.item : notification.data,
);
//Only call callback if not from foreground
if (Platform.OS === 'ios') {
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
requestPermissions: true,
});
};
unRegister = () => {
PushNotification.unregister();
};
showNotification = (id, title, message, data = {}, options = {}) => {
PushNotification.localNotification({
// Android only Properties
...this.buildAndroidNotification(id, title, message, data, options),
// IOS and Android properties
...this.buildIOSNotification(id, title, message, data, options),
// IOS and Android properties
title: title || '',
message: message || '',
playSound: options.playSound || false,
soundName: options.soundName || 'default',
userInteraction: false, //BOOLEAN : If the notification was opend by the user from notification area or not
});
};
buildAndroidNotification = (id, title, message, data = {}, options = {}) => {
return {
id: id,
authCancel: true,
largeIcon: options.largeIcon || 'ic_launcher',
smallIcon: options.smallIcon || 'ic_notification',
bigText: message || '',
subText: title || '',
vibrate: options.vibrate || true,
vibration: options.vibration || 300,
priority: options.priority || 'high',
importance: options.importance || 'high', // (optional) set notification importance, default : ??~
data: data,
};
};
buildIOSNotification = (id, title, message, data = {}, options = {}) => {
return {
alertAction: options.alertAction || 'view',
category: options.category || '',
userInfo: {
id: id,
item: data,
},
};
};
cancelAllLocalNotifications = () => {
if (Platform.OS === 'ios') {
PushNotificationIOS.removeAllDeliveredNotifications();
} else {
PushNotification.cancelAllLocalNotifications();
}
};
removeDeliveredNotificationByID = (notification) => {
console.log(
'[LocalNotificationService] removeDeliveredNotificationByID:',
notification,
);
PushNotification.cancelLocalNotifications({id: `${notificationId}`});
};
}
export const localNotificationService = new LocalNotificationService();
FCMService.js
import messaging from '@react-native-firebase/messaging';
import {Platform} from 'react-native';
class FCMService {
register = (onRegister, onNotification, onOpenNotification) => {
this.checkPermission(onRegister);
this.createNotificationListeners(
onRegister,
onNotification,
onOpenNotification,
);
};
registerAppWithFCM = async () => {
if (Platform.OS === 'ios') {
// await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true);
}
};
checkPermission = (onRegister) => {
messaging()
.hasPermission()
.then((enabled) => {
if (enabled) {
//User has permission
this.getToken(onRegister);
} else {
//User doesn't have permission
this.requestPermission(onRegister);
}
})
.catch((error) => {
console.log('[FCMService] Permission rejected ', error);
});
};
getToken = (onRegister) => {
messaging()
.getToken()
.then((fcmToken) => {
if (fcmToken) {
onRegister(fcmToken);
} else {
console.log('[FCMService] User does not have a device token');
}
})
.catch((error) => {
console.log('[FCMService] getToken rejected', error);
});
};
requestPermission = (onRegister) => {
messaging()
.requestPermission()
.then(() => {
this.getToken(onRegister);
})
.catch((error) => {
console.log('[FCMService] Request Permission rejected', error);
});
};
deleteToken = () => {
console.log('[FCMService] deleteToken');
messaging()
.deleteToken()
.catch((error) => {
console.log('[FCMService] Delete token error', error);
});
};
createNotificationListeners = (
onRegister,
onNotification,
onOpenNotification,
) => {
//실행중이지만 현재화면은 다른 앱이 실행중이거나 아무것도 실행하지않을때
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log(
'[FCMService] onNotificationOpenApp Notification caused app to open from background',
remoteMessage,
);
if (remoteMessage) {
const notification = remoteMessage.notification;
onOpenNotification(notification);
//this.removeDeliveredNotification(Notification.NotificationId)
} else {
console.log('background notification error', error);
}
alert(remoteMessage.body);
});
//Check whether an initial notification is available
//앱이 실행중이 아닐때
messaging()
.getInitialNotification()
.then((remoteMessage) => {
console.log(
'[FCMService] getInitialNotification casued app to open from quit state : fcmremoteMessage :',
remoteMessage,
);
if (remoteMessage) {
const notification = remoteMessage.notification;
onOpenNotification(notification);
//this.removeDeliveredNotification(notification.notificationId)
} else {
console.log('quit state notification error : ', error);
}
});
//실행중이고 현재 화면일때
this.messageListener = messaging().onMessage(async (remoteMessage) => {
console.log('[FCMService] A new FCM message arrived', remoteMessage);
if (remoteMessage) {
let notification = null;
if (Platform.OS === 'ios') {
notification = remoteMessage.data.notification;
} else {
notification = remoteMessage.notification;
}
onNotification(notification);
}
});
//Triggerd when have new token
messaging().onTokenRefresh((fcmToken) => {
console.log('[FCMService] New token refresh :', fcmToken);
onRegister(fcmToken);
});
};
unRegister = () => {
this.messageListener();
};
}
export const fcmService = new FCMService();
App.js
import React, {useEffect, useState} from 'react';
import {Text, StyleSheet, View, Button} from 'react-native';
import {fcmService} from './src/FCMService';
import {localNotificationService} from './src/LocalNotificationService';
export default function App() {
useEffect(() => {
fcmService.registerAppWithFCM();
fcmService.register(onRegister, onNotification, onOpenNotification);
localNotificationService.configure(onOpenNotification);
function onRegister(token) {
console.log('[App] onRegister : token :', token);
}
function onNotification(notify) {
console.log('[App] onNotification : notify :', notify);
const options = {
soundName: 'default',
playSound: true,
};
localNotificationService.showNotification(
0,
notify.title,
notify.body,
notify,
options,
);
}
function onOpenNotification(notify) {
console.log('[App] onOpenNotification : notify :', notify);
alert('Open Notification : notify.body :' + notify.body);
}
return () => {
console.log('[App] unRegister');
fcmService.unRegister();
localNotificationService.unregister();
};
}, []);
return (
<View style={styles.container}>
<Text>Push Test</Text>
<Button title="Test" onPress={() => alert('remoteMessage')} />
<Button
title="Press"
onPress={() => localNotificationService.cancelAllLocalNotifications()}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
index.js
/**
* @format
*/
import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as hyukpush} from './app.json';
import messaging from '@react-native-firebase/messaging';
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Message handled in the background!', remoteMessage);
});
function HeadlessCheck({isHeadless}) {
if (isHeadless) {
// App has been launched in the background by iOS, ignore
return null;
}
return <App />;
}
AppRegistry.registerComponent(hyukpush, () => HeadlessCheck);
hyukpush 부분을 각자의 appname으로 바꿔줘야한다.
이걸로 android는 끝이다. 한번 메세지를 보내보자
좌측에 성장 > Cloud Messagin을 누르면 위와 같은 페이지가 나온다.
새알림을 누르고
다음
안드로이드를 선택해주자
그리고 다음다음 완료를 눌러준다.
짜잔~!~!
모두 다함께 열코합시다 ㅎㅎㅎㅎㅎ
위 화면은 Background상태에서 실행한 것이다 ~
참고 사이트
Cloud Messaging | React Native Firebase
Installation and getting started with Cloud Messaging.
rnfirebase.io
github.com/zo0r/react-native-push-notification
zo0r/react-native-push-notification
React Native Local and Remote Notifications. Contribute to zo0r/react-native-push-notification development by creating an account on GitHub.
github.com
'React Native' 카테고리의 다른 글
[React Native] MAC/IOS 알람 구현하기 3(Push notification)-firebase (5) | 2020.12.10 |
---|---|
[React Native] MAC/IOS 알람 구현하기 2(Push notification)-firebase (0) | 2020.12.10 |
[React Native] MAC/IOS 알람 구현하기 1(Push notification)-firebase (0) | 2020.12.10 |
[React Native] Android 알람 구현하기 1(Push notification)-firebase (0) | 2020.12.10 |
[ReactNative]Mac - Android 설치(npx react-native run-android) (0) | 2020.11.18 |