Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/01   »
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 31
Tags more
Archives
Today
Total
관리 메뉴

혼자서 앱 만드는 개발자 함께하는 AI 세상

플러터 AwesomeNotifications 알림 백그라운드 처리를 위해 삽질 본문

플러터 앱개발

플러터 AwesomeNotifications 알림 백그라운드 처리를 위해 삽질

혼앱사 2023. 12. 17. 18:08
반응형

 

우선 플러터에서 

https://firebase.google.com/docs/cloud-messaging/flutter/receive?hl=ko

 

Flutter 앱에서 메시지 수신  |  Firebase 클라우드 메시징

Google I/O 2023에서 Firebase의 주요 소식을 확인하세요. 자세히 알아보기 의견 보내기 Flutter 앱에서 메시지 수신 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

firebase.google.com

먼저 적용해야 할 부분

적용된 소소

import 'dart:io';

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_windowmanager/flutter_windowmanager.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import 'core/app_export.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'package:uni_links/uni_links.dart';

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
  AwesomeNotifications().createNotification(
      content: NotificationContent(
    id: 10,
    channelKey: 'basic_channel',
    actionType: ActionType.Default,
    title: 'Hello World!',
    body: 'This is my first notification!',
  ));
  print("Handling a background message: ${message.messageId}");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  uriLinkStream.listen((Uri? uri) {
    debugPrint("uri: $uri");
    debugPrint(uri!.query);
    debugPrint(uri.queryParameters.values.first);
  }, onError: (Object err) {
    debugPrint("err: $err");
  });

/*
  //./adb shell 'am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "tlogis://gongyuchat.seesaw"'
//  ./adb shell 'am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "http://inkj.cafe24.com"'
  //Admob.initialize();
 */
  //await Firebase.initializeApp();

  if (Platform.isAndroid) {
    await Firebase.initializeApp();
  } else if (Platform.isIOS) {}

  AwesomeNotifications().initialize(
      // set the icon to null if you want to use the default app icon
      'resource://drawable/res_app_icon',
      [
        NotificationChannel(
            channelGroupKey: 'basic_channel_group',
            channelKey: 'basic_channel',
            channelName: 'Basic notifications',
            channelDescription: 'Notification channel for basic tests',
            defaultColor: Color(0xFF9D50DD),
            ledColor: Colors.white)
      ],
      // Channel groups are only visual and are not required
      channelGroups: [
        NotificationChannelGroup(
            channelGroupKey: 'basic_channel_group',
            channelGroupName: 'Basic group')
      ],
      debug: true);

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]).then((value) {
    Logger.init(kReleaseMode ? LogMode.live : LogMode.debug);
    runApp(const MyApp());
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('ko', 'KR'),
        Locale('en', 'US'),
        // include country code too
      ],
      theme: theme,
      translations: AppLocalization(),
      locale: Get.deviceLocale, //for setting localization strings
      fallbackLocale: const Locale('ko', 'KR'),
      //fallbackLocale: const Locale('ko', 'KR'),

      title: 'SeeSaw',
      initialBinding: InitialBindings(),
      initialRoute: AppRoutes.initialRoute,
      getPages: AppRoutes.pages,
    );
  }
}

적용된 부분

 

하지만 저렇게 하면 메시지가 두번 울린다. 기본 fcm notification 이 뜨고 AwesomeNotifications 이 뜬다.

그래서 보내는 부분에서 notification을 삭제 한다.

{ "registration_ids" : [
    "fEOvQ1_VRHaxYGaCNl4gj3:APA91bHM4_PMhpk2AfobiSXEYsdPELvX7gAzJLeQUiKPRpBF2adUhkz4NOgLrjdffDsi4U6O8TmiR7QE7yAA92Qe0iEOKZLaOLUmj_T4j05eRNYn-Ks2HqbFxFQFHDaZr1rDbrY0x799"
  ],
    "priority": "high",
    "mutable_content": true,
     "notification": {
        "badge": 42,
        "title": "Huston! The eagle has landed!",
        "body": "A small step for a man, but a giant leap to Flutter's community!"
    },
    "data" : {
        "content": {
            "id": 1,
            "badge": 42,
            "channelKey": "basic_channel",
            "displayOnForeground": true,
            "notificationLayout": "BigPicture",
            "largeIcon": "https://br.web.img3.acsta.net/pictures/19/06/18/17/09/0834720.jpg",
            "bigPicture": "https://www.dw.com/image/49519617_303.jpg",
            "showWhen": true,
            "autoDismissible": true,
            "privacy": "Private",
            "payload": {
                "secret": "Awesome Notifications Rocks!"
            }
        },
        "actionButtons": [
            {
                "key": "REDIRECT",
                "label": "리다이렉트",
                "autoDismissible": true
            },
            {
                "key": "DISMISS",
                "label": "디스펜스",
                "actionType": "DismissAction",
                "isDangerousOption": true,
                "autoDismissible": true
            }
        ],
        "Android": {
            "content": {
                "title": "Android! The eagle has landed!",
                "payload": {
                    "android": "android custom content!"
                }
            }
        },
        "iOS": {
            "content": {
                "title": "Jobs! The eagle has landed!",
                "payload": {
                    "ios": "ios custom content!"
                }
            },
            "actionButtons": [
                {
                    "key": "REDIRECT",
                    "label": "Redirect message",
                    "autoDismissible": true
                },
                {
                    "key": "DISMISS",
                    "label": "Dismiss message",
                    "actionType": "DismissAction",
                    "isDangerousOption": true,
                    "autoDismissible": true
                }
            ]
        }
    }
}

 

그래서

awesome_notifications 를 활용해서 알림 클릭시 컨텐츠 처리 해볼예정이다.

https://pub.dev/packages/awesome_notifications

 

awesome_notifications | Flutter Package

A complete solution to create Local and Push Notifications, customizing buttons, images, sounds, emoticons and applying many different layouts for Flutter apps.

pub.dev

 

728x90
반응형
Comments