[React Native] Android Notification 알람 주기(상단 팝업 안나옴 오류 해결)

장동현·2022년 1월 18일
2

ReactNative

목록 보기
11/12

이번에 만드는 작은 사이드 프로젝트에서 Firebase를 이용한 Notification을 줄 일이 생겼다.
사용 과정과 오류 해결에 대해 간단히 적어보려고 한다.

사용 모듈

@react-native-firebase/app
@react-native-firebase/messaging

사용법1 (Foreground)

useEffect(() => {
		const unsubscribe = messaging().onMessage(async (remoteMessage) => {
			console.log(remoteMessage);
		});

		return unsubscribe;
	}, []);
  • 위와 같이 useEffect hook에 notification 알림이 올 때 마다 로그를 찍도록 설정 하였다.

사용법2 (Background)

//filePath ./index.js

import 'expo-dev-client';
import { Alert, AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import 'react-native-gesture-handler';
import { registerRootComponent } from 'expo';

import App from './App';

// Register background handler
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
	console.log('Message handled in the background!', remoteMessage);

	Alert.alert('good');
});

// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
// the environment is set up appropriately
AppRegistry.registerComponent('app', () => App);
registerRootComponent(App);
  • 위와 같이 설정하면 background 즉 앱이 꺼지거나 비활성 상태라도 알람을 수신 할 수 있게 된다.

FCM을 이용한 알람 보내기

  • async 문에 구글 fcm을 이용하여 앱 내에서 이렇게 알람을 테스트 해볼 수 있다.
  • (추가) : android_channel_id를 default로 설정하면 기본으로 보내진다
	await fetch('https://fcm.googleapis.com/fcm/send', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			Authorization: `FCM 서버 키`,
		},
		body: JSON.stringify({
			to: '디바이스 토큰',
			data: {
				title: 'test',
				message: 'hihi',
				android_channel_id: 'high-priority',
			},
			notification: {
				title: '푸시테스트_notification',
				body: 'good work',
				sound: 'default',
				android_channel_id: 'high-priority',
			},
			android: {
				channel_id: 'high-priority',
			},
			priority: 'high',
		}),
	}).then((data) => console.log(data));

오류

  • 몇 시간을 허비 했던 오류가 있는데 바로 알람 배지가 표시가 안되는 것 이였다.
    알람에 대한 소리만 나고 카카오톡 알림처럼 아무런 알람이 오지 않아서 stackoverflow나 다른
    공식문서를 열심히 찾아 봤지만 결국 답은 핸드폰 설정에 있었다.
  1. 아이콘 길게 터치
  2. 애플리케이션 정보 -> 알림 터치
  3. 기타 터치
  4. 앱 아이콘 배지 활성

참고문서

React Native FireBase
Expo FCM Notification

profile
FE 개발자 장동현 입니다 😃

0개의 댓글