80 lines
2.5 KiB
Dart
80 lines
2.5 KiB
Dart
import 'package:firebase_core/firebase_core.dart';
|
|
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
|
|
import '../firebase_options.dart';
|
|
import 'msn_api.dart';
|
|
|
|
/// Background handler must be a top-level function.
|
|
@pragma('vm:entry-point')
|
|
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
|
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
|
debugPrint('FCM background: ${message.messageId}');
|
|
}
|
|
|
|
final FlutterLocalNotificationsPlugin _localNotifications = FlutterLocalNotificationsPlugin();
|
|
|
|
bool _fcmInitialized = false;
|
|
|
|
/// Call after Firebase.initializeApp. Registers token with [registerPushToken] if API available.
|
|
Future<void> initializeFcmAndLocalNotifications(MsnApi api) async {
|
|
if (_fcmInitialized) return;
|
|
_fcmInitialized = true;
|
|
|
|
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
|
|
|
|
const androidInit = AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
const iosInit = DarwinInitializationSettings();
|
|
await _localNotifications.initialize(
|
|
const InitializationSettings(android: androidInit, iOS: iosInit),
|
|
);
|
|
|
|
final messaging = FirebaseMessaging.instance;
|
|
await messaging.setForegroundNotificationPresentationOptions(
|
|
alert: true,
|
|
badge: true,
|
|
sound: true,
|
|
);
|
|
|
|
await messaging.requestPermission(alert: true, badge: true, sound: true);
|
|
|
|
FirebaseMessaging.onMessage.listen((RemoteMessage msg) async {
|
|
final n = msg.notification;
|
|
final title = n?.title ?? 'IYKYKA';
|
|
final body = n?.body ?? msg.data['body'] as String? ?? '';
|
|
const androidDetails = AndroidNotificationDetails(
|
|
'iykyka_chat',
|
|
'채팅',
|
|
channelDescription: '새 메시지',
|
|
importance: Importance.defaultImportance,
|
|
priority: Priority.defaultPriority,
|
|
);
|
|
const details = NotificationDetails(android: androidDetails);
|
|
await _localNotifications.show(
|
|
msg.hashCode,
|
|
title,
|
|
body,
|
|
details,
|
|
);
|
|
});
|
|
|
|
try {
|
|
final token = await messaging.getToken();
|
|
if (token != null && token.isNotEmpty) {
|
|
await api.registerPushToken(token);
|
|
debugPrint('FCM token registered with server');
|
|
}
|
|
} catch (e) {
|
|
debugPrint('FCM getToken/register skipped: $e');
|
|
}
|
|
|
|
FirebaseMessaging.instance.onTokenRefresh.listen((token) async {
|
|
try {
|
|
await api.registerPushToken(token);
|
|
} catch (e) {
|
|
debugPrint('FCM token refresh register failed: $e');
|
|
}
|
|
});
|
|
}
|