티스토리 뷰

- FireBase Setting

https://firebase.google.com/?hl=ko

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

FireBase에 로그인하고 새프로젝트를 만들어주자

 

새프로젝트를 만들고

앱추가를 누른다.

 

-Android Setting

패키지 이름에는 android / app / src / main / AndroidManifest.xml 에 들어있는 package값 "com.~~~" 를 가져다 씁니다.

디버그 서명 인증서는 기존 터미널에서 android로 접근하여 

gradlew signingReport

위의 명령어를 입력하면 뭐가 주르륵 뜨는데

SH1을 가져와서 등록하면 됩니다.

 

이제 goole-services.json을 다운받아 android/app 안에 붙여넣습니다.

 

 

그후에

android/app/build.gradle에 추가합니다.

apply plugin: 'com.google.gms.google-services'
android {

   
defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "org.ourcodelabs.pushandselfauth"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
//        minSdkVersion flutter.minSdkVersion
        minSdkVersion 19
        multiDexEnabled true

android / app / src / main / AndroidManifest.xml 에 추가

<manifest
    ...
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
//기존 <meta-data/>에 추가하는게 아닌 새롭게 추가해야 합니다. 안그러면 name겹친다고 오류뜹니다.
<application
	...
    <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="important_channel" />

 

<application
	...
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
              android:exported="true">   
        </receiver>
<application
	...    
    <activity
            android:exported="true">

 

 

 

-iOS Setting

IOS는 GoogleService-info.plist를 설명대로 넣고 그냥 전부 다음누르고 끝내면 된다.

 

 

-Flutter 라이브러리 추가

flutter pub add firebase_messaging
flutter pub add flutter_local_notifications
flutter pub add get
flutter pub add firebase_core

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging fbMsg = FirebaseMessaging.instance;

  String? fcmToken =
      await fbMsg.getToken(vapidKey: "BGRA_GV..........keyvalue");
  //TODO : 서버에 해당 토큰을 저장하는 로직 구현
  print("token-------------------------: $fcmToken");
  //FCM 토큰은 사용자가 앱을 삭제, 재설치 및 데이터제거를 하게되면 기존의 토큰은 효력이 없고 새로운 토큰이 발급된다.
  fbMsg.onTokenRefresh.listen((nToken) {
    //TODO : 서버에 해당 토큰을 저장하는 로직 구현
  });
  runApp(const MyApp());

  // 플랫폼 확인후 권한요청 및 Flutter Local Notification Plugin 설정
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  AndroidNotificationChannel? androidNotificationChannel;
  if (Platform.isIOS) {
    //await reqIOSPermission(fbMsg);
  } else if (Platform.isAndroid) {
    //Android 8 (API 26) 이상부터는 채널설정이 필수.
    androidNotificationChannel = const AndroidNotificationChannel(
      'important_channel', // id
      'Important_Notifications', // name
      '중요도가 높은 알림을 위한 채널.',
      // description
      importance: Importance.high,
    );

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(androidNotificationChannel);
  }
  //Background Handling 백그라운드 메세지 핸들링
  FirebaseMessaging.onBackgroundMessage(fbMsgBackgroundHandler);
  //Foreground Handling 포어그라운드 메세지 핸들링
  FirebaseMessaging.onMessage.listen((message) {
    fbMsgForegroundHandler(
        message, flutterLocalNotificationsPlugin, androidNotificationChannel);
  });
  //Message Click Event Implement
  await setupInteractedMessage(fbMsg);
}

//실행페이지
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: LoginScreen());
  }
}

/// iOS 권한을 요청하는 함수
Future reqIOSPermission(FirebaseMessaging fbMsg) async {
  NotificationSettings settings = await fbMsg.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );
}

/// Firebase Background Messaging 핸들러
Future<void> fbMsgBackgroundHandler(RemoteMessage message) async {
  print("[FCM - Background] MESSAGE : ${message.messageId}");
}

/// Firebase Foreground Messaging 핸들러
Future<void> fbMsgForegroundHandler(
    RemoteMessage message,
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
    AndroidNotificationChannel? channel) async {
  print('[FCM - Foreground] MESSAGE : ${message.data}');

  if (message.notification != null) {
    print('Message also contained a notification: ${message.notification}');
    flutterLocalNotificationsPlugin.show(
        message.hashCode,
        message.notification?.title,
        message.notification?.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel!.id,
            channel.name,
            channel.description,
            icon: '@mipmap/ic_launcher',
          ),
          // iOS: const DarwinNotificationDetails(
          //   badgeNumber: 1,
          //   subtitle: 'the subtitle',
          //   sound: 'slow_spring_board.aiff',
          // ),
        ));
  }
}

/// FCM 메시지 클릭 이벤트 정의
Future<void> setupInteractedMessage(FirebaseMessaging fbMsg) async {
  RemoteMessage? initialMessage = await fbMsg.getInitialMessage();
  // 종료상태에서 클릭한 푸시 알림 메세지 핸들링
  if (initialMessage != null) clickMessageEvent(initialMessage);
  // 앱이 백그라운드 상태에서 푸시 알림 클릭 하여 열릴 경우 메세지 스트림을 통해 처리
  FirebaseMessaging.onMessageOpenedApp.listen(clickMessageEvent);
}

void clickMessageEvent(RemoteMessage message) {
  
}

참고로 IOS쪽은 주석처리를 해두었습니다. 

 

이제 앱을 실행하면 콘솔에 토큰 값이 뜨는데 이 토큰을 복사해서

 

테스트 해보겠습니다.

새캠페인을 누르고

알림제목과 텍스트에 내용을 채우고

오른쪽의 테스트 메세지 전송을 누르면 다음과 같은 창이 뜨는데

FCM 등록 토큰 추가에 아까 복사해 두었던 토큰을 붙여넣기합니다.

 

테스트버튼을 누르면

푸시알람을 볼 수 있습니다.

 

아이폰은 실기기가 아니면 테스트가 안된다고 합니다.

 

 

Referece:

https://kanoos-stu.tistory.com/72

 

[Flutter] 매우 쉽게 Flutter 푸시 메세지(FCM) 사용하기

시작 전 프로젝트에 firebase 설정 [FlutterFire] 아주 쉽게 Flutter프로젝트 Firebase 설정 (with firebase CLI) Firebase CLI 설치 및 로그인 curl -sL https://firebase.tools | bash 위 명령어를 입력하고 password를 입력하면

kanoos-stu.tistory.com

https://velog.io/@leedool3003/Flutter-FCM-Firebase-Cloud-Messagin-%EC%97%B0%EB%8F%99

 

[Flutter] FCM, Firebase Cloud Messagin 연동

FCM 을 이용하여 Flutter 알림을 만들어보자.

velog.io

 

'Flutter' 카테고리의 다른 글

[Flutter + STOMP] Flutter에서 Stomp프로토콜 사용하기  (0) 2023.08.18
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함