728x90
https://claude.ai/chat/82111d91-6054-448b-b830-a5d7a3a84c1c
# FCM 푸시 알림 시스템 코드 구현 과정
## 1. 필요한 패키지 import
```dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
```
## 2. NotificationHandler 클래스 구현
```dart
class NotificationHandler {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future initialize() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
Future showNotification(String title, String body) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your_channel_id',
'your_channel_name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
);
}
}
```
## 3. 백그라운드 메시지 핸들러 구현
```dart
@pragma('vm:entry-point')
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
// 여기에 백그라운드 알림 처리 로직 추가
}
```
## 4. main 함수에서 Firebase 및 FCM 초기화
```dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
final notificationHandler = NotificationHandler();
await notificationHandler.initialize();
// ... 나머지 초기화 코드
runApp(const ProviderScope(child: MyApp()));
}
```
## 5. MyApp 클래스에서 알림 클릭 핸들러 구현
```dart
class _MyAppState extends ConsumerState {
@override
void initState() {
super.initState();
FirebaseMessaging.onMessageOpenedApp.listen(_handleNotificationClick);
}
void _handleNotificationClick(RemoteMessage message) {
if (message.data['type'] == 'new_room') {
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(routeProvider).push('/room_details', extra: message.data['roomId']);
});
}
}
// ... build 메서드 및 기타 코드
}
```
## 6. FCM 토큰 관리 (PushNotificationService 클래스에 구현)
```dart
class PushNotificationService {
Future initialize() async {
// ... 기존 초기화 코드
String? fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
await updateFCMToken(fcmToken);
print("FCM Token: $fcmToken");
}
FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
updateFCMToken(token);
print("FCM Token refreshed: $token");
});
}
Future updateFCMToken(String token) async {
// Firestore에 토큰 저장 로직
}
}
```
## 7. 알림 전송 기능 (서버 측 Cloud Function)
```javascript
exports.sendPushNotification = functions.https.onCall(async (data, context) => {
const { userId, title, body } = data;
// Firestore에서 사용자의 FCM 토큰 조회
const userDoc = await admin.firestore().collection('users').doc(userId).get();
const fcmToken = userDoc.data().fcmToken;
const message = {
notification: { title, body },
token: fcmToken,
};
try {
const response = await admin.messaging().send(message);
console.log('Successfully sent message:', response);
return { success: true };
} catch (error) {
console.error('Error sending message:', error);
throw new functions.https.HttpsError('internal', 'Error sending push notification');
}
});
```
이 과정을 통해 FCM을 이용한 푸시 알림 시스템의 핵심 구성 요소들을 구현하였습니다.
각 부분은 모듈화되어 있어 유지보수와 확장이 용이하며, Firebase의 다양한 기능을 활용하여
효율적인 실시간 메시징 시스템을 구축하였습니다.
# Firebase Cloud Messaging (FCM)을 이용한 푸시 알림 시스템 구현
## 1. 프로젝트 설정
- Firebase 프로젝트 생성 및 Flutter 앱 등록
- FlutterFire CLI를 사용하여 Firebase 설정 파일 생성
- 필요한 의존성 추가 (firebase_core, firebase_messaging, flutter_local_notifications)
## 2. Firebase 초기화
- main() 함수에서 Firebase.initializeApp() 호출
- DefaultFirebaseOptions 사용하여 플랫폼별 설정 적용
## 3. FCM 토큰 관리
- FCM 토큰 획득 및 저장 로직 구현
- 토큰 갱신 시 처리 로직 추가
## 4. 백그라운드 메시지 핸들러 구현
- _firebaseMessagingBackgroundHandler 함수 정의
- FirebaseMessaging.onBackgroundMessage에 핸들러 등록
## 5. 포그라운드 메시지 처리
- FirebaseMessaging.onMessage.listen을 사용하여 포그라운드 메시지 처리
- 로컬 알림 표시 로직 구현 (flutter_local_notifications 사용)
## 6. 알림 클릭 핸들러 구현
- FirebaseMessaging.onMessageOpenedApp.listen을 사용하여 알림 클릭 이벤트 처리
- 특정 화면으로 네비게이션 로직 추가
## 7. NotificationHandler 클래스 구현
- 로컬 알림 초기화 및 표시 로직 캡슐화
- 앱 시작 시 NotificationHandler 초기화
## 8. 푸시 알림 전송 기능 구현
- Cloud Functions를 사용하여 서버 측 알림 전송 로직 구현
- 클라이언트에서 알림 전송 요청 기능 추가
## 9. 권한 요청 및 처리
- 푸시 알림 권한 요청 로직 구현
- 사용자 권한 상태에 따른 처리 로직 추가
## 10. 테스트 및 디버깅
- 다양한 시나리오에서 푸시 알림 테스트 (포그라운드, 백그라운드, 종료 상태)
- 로그 추가 및 문제 해결
## 11. 사용자 경험 최적화
- 알림 채널 설정 및 커스터마이징
- 알림 그룹화 및 우선순위 설정
이 과정을 통해 안정적이고 효과적인 푸시 알림 시스템을 구현하였으며,
사용자 참여도 향상 및 실시간 정보 전달 기능을 앱에 성공적으로 통합하였습니다.
728x90
'♠♠기술 구현' 카테고리의 다른 글
fcm 구현 과정 (1) | 2024.10.05 |
---|---|
페이스북 로그인 과정 (2) | 2024.10.05 |
FCM관련 여러가지 엮인것들 정리 (1) | 2024.10.01 |
fcm 기본개념 다시 잡기 (0) | 2024.10.01 |
fcm 구독으로 방향 바꾸기 (1) | 2024.09.30 |