framework/ReactNative
갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편10 – 앱 종료 후에도 반복 알림 유지하기 (Headless Task 활용)
octo54
2025. 5. 13. 11:52
반응형
갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편10 – 앱 종료 후에도 반복 알림 유지하기 (Headless Task 활용)
지금까지 반복 알림을 설정했지만,
앱이 완전히 종료되면 알림이 울리지 않는 문제를 겪었죠?
이번 글에서는 앱 종료 후에도 알림이 정상 작동하도록
Headless Task를 이용하여 문제를 해결하는 방법을 알아봅니다. 🔁🔔
✅ 1. Headless Task란?
- 앱이 종료된 상태에서도 실행되는 백그라운드 작업
- 주로 알림, 위치 추적, 데이터 동기화 등에 사용
- Android에서만 지원 (iOS는 별도 처리 필요)
✅ 2. Headless Task 활용 구조
단계 설명
1. 설정 | react-native-push-notification에 Headless Task 등록 |
2. 구현 | 별도 JS 파일에서 Task 처리 함수 작성 |
3. 등록 | 알림 설정 시 Headless Task와 연결 |
✅ 3. 라이브러리 설치
이미 react-native-push-notification 설치가 완료되었다면
추가 설치 없이 바로 사용할 수 있습니다.
✅ 4. Android 설정
📄 android/app/src/main/AndroidManifest.xml
✅ 5. Headless Task 파일 만들기
📄 NotificationTask.js
import PushNotification from 'react-native-push-notification';
const NotificationTask = async (taskData) => {
console.log('Headless Task 실행됨:', taskData);
PushNotification.localNotification({
channelId: 'default-channel-id',
title: '앱이 종료된 상태에서도!',
message: '이 알림은 백그라운드에서 실행됩니다.',
});
return Promise.resolve();
};
export default NotificationTask;
✅ 6. Headless Task 등록하기
반응형
📄 index.js
import { AppRegistry } from 'react-native';
import App from './App';
import NotificationTask from './NotificationTask';
import { name as appName } from './app.json';
import messaging from '@react-native-firebase/messaging';
// 앱 시작
AppRegistry.registerComponent(appName, () => App);
// Headless Task 등록
messaging().setBackgroundMessageHandler(NotificationTask);
✅ 7. NotificationService.js 수정
import PushNotification from 'react-native-push-notification';
// Headless Task 알림 설정
export const scheduleRepeatingNotification = (title, message, repeatType) => {
PushNotification.localNotificationSchedule({
channelId: 'default-channel-id',
title: title,
message: message,
repeatType: repeatType,
date: new Date(Date.now() + 10 * 1000), // 10초 후 시작
allowWhileIdle: true,
});
};
// 채널 생성
export const createNotificationChannel = () => {
PushNotification.createChannel(
{
channelId: 'default-channel-id',
channelName: 'Default Channel',
},
(created) => console.log(`채널 생성: ${created}`)
);
};
✅ 8. App.js에서 알림 설정
import React, { useEffect } from 'react';
import { View, Button, StyleSheet, Text } from 'react-native';
import { createNotificationChannel, scheduleRepeatingNotification } from './services/NotificationService';
export default function App() {
useEffect(() => {
createNotificationChannel();
}, []);
const handleAlarm = () => {
scheduleRepeatingNotification("종료 후에도 울림", "앱 종료 시에도 작동하는 알림입니다.", "day");
};
return (
<View style={styles.container}>
<Text style={styles.title}>앱 종료 후에도 알림 유지</Text>
<Button title="반복 알림 설정" onPress={handleAlarm} />
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
title: { fontSize: 24, marginBottom: 20 },
});
✅ 9. 앱 종료 후 테스트
- 앱 실행 → "반복 알림 설정" 버튼 클릭
- 앱을 완전히 종료 (Swipe Out)
- 설정한 시간에 알림이 정상 도착하는지 확인
✅ 10. 동작 원리 요약
단계 설명
앱 실행 | Headless Task 등록 |
앱 종료 후 알림 발생 | FCM 메시지 수신 시 Headless Task 실행 |
알림 전송 | PushNotification.localNotification() 호출 |
✅ 11. 주의사항
사항 설명
Android에서만 동작 | iOS는 Background Fetch로 별도 처리 필요 |
배터리 최적화 문제 발생 가능성 | 특정 기기에서는 알림이 지연되거나 누락될 수 있음 |
Firebase와 연동 시 설정 필요 | 앱 종료 상태에서 FCM 처리 시 별도 설정 필요 |
✅ 12. 이번 글에서 배운 것
- Headless Task를 활용한 반복 알림 구현
- 앱 종료 상태에서도 알림이 울리도록 설정
- Android에서의 알림 제약 사항 이해
- FCM과 연동하여 백그라운드 알림 처리
📘 다음 확장 예고
iOS에서도 반복 알림 유지하는 방법 (Background Fetch)
Firebase와 연동하여 클라우드 기반 반복 알림 관리
다양한 디바이스 환경에서 테스트 및 최적화
React Native Headless Task,React Native 앱 종료 알림,React Native 백그라운드 알림,React Native FCM Headless,React Native Push Notification 유지,React Native 앱 종료 후 알림,React Native 백그라운드 작업,React Native 알림 관리,React Native 알림 앱 만들기,React Native Firebase 알림 관리