ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Firebase 푸시 메시지(Android)
    Mobile/Flutter 2022. 4. 20. 22:21

    Flutter에서 푸시 메시지를 받기 위한 코드를 작성하는 예제이다.

     

    필요한 패키지는 아래 작성되어있다.

    flutter_local_notifications
    
    firebase_messaging
    
    firebase_core

     

    AndroidManifest.xml의  application아래 문장을 추가한다.

    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="high_importance_channel" />

    여기서 value에는 원하는 채널 명을 넣으면 된다.

     

    아래는 전체 코드이다.

    import 'dart:async';
    
    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_messaging/firebase_messaging.dart';
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_local_notifications/flutter_local_notifications.dart';
    
    late AndroidNotificationChannel channel;
    late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
    
    Future onBackgroundHandler(RemoteMessage message) async {
      print("onBackgroundMessage: ${message.data}");
      return Future.value();
    }
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging.onBackgroundMessage(onBackgroundHandler);
    
      if (!kIsWeb) {
        channel = const AndroidNotificationChannel(
          'high_importance_channel', // id
          'High Importance Notifications', // title
          importance: Importance.high,
        );
        flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    
    	await FirebaseMessaging.instance.requestPermission(
          alert: true,
          announcement: true,
          badge: true,
          carPlay: true,
          criticalAlert: true,
          provisional: true,
          sound: true,
        );
        
        // Notification Channel을 디바이스에 생성
        await flutterLocalNotificationsPlugin
            .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
            ?.createNotificationChannel(channel);
    
        await flutterLocalNotificationsPlugin.initialize(
            const InitializationSettings(
                android: AndroidInitializationSettings('@mipmap/ic_launcher'),
                iOS: IOSInitializationSettings()),
            onSelectNotification: (String? payload) async {
              // Background에서 수신했을 때 생성되는 heads up notification 클릭했을 때의 동작을 작성
            });
      }
    
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key}) : super(key: key);
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      late String token = '';
    
      @override
      void initState() {
        super.initState();
        FirebaseMessaging.instance
            .getInitialMessage()
            .then((RemoteMessage? message) {
        });
        _firebaseCloudMessagingListeners();
        tokenInit();
    
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: const Text("Firebase Test"),
            ),
            body: Center(
                child: Column(
              children: <Widget>[
                Text("토큰 값 : $token"),
              ],
            )));
      }
    
      Future<void> tokenInit() async {
        await FirebaseMessaging.instance.getToken().then((tokenData) {
          print(tokenData);
          setState(() {
            token = tokenData!;
          });
        });
      }
    
      void _firebaseCloudMessagingListeners() {
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;
          AppleNotification? ios = message.notification?.apple;
          if (notification != null && (android != null || ios != null) && !kIsWeb) {
            flutterLocalNotificationsPlugin.show(
              notification.hashCode,
              notification.title,
              notification.body,
              NotificationDetails(
                  android: AndroidNotificationDetails(
                      channel.id,
                      channel.name,
                      icon: 'ic_launcher'
                  ),
                  iOS: const IOSNotificationDetails()
              ),
            );
          }
        });
        FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
        	//Foreground 에서 수신했을 때 생성되는 heads up notification 클릭했을 때의 동작을 작성
        });
      }
    }

     

     

     

     

    channel = const AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      importance: Importance.high,
    );

    위 부분은 채널을 설정하는 부분이다.

    id 부분은 meta-data에 작성한 value로 작성하면 된다.

     

    await FirebaseMessaging.instance.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: true,
      criticalAlert: true,
      provisional: true,
      sound: true,
    );
    

    위 부분은 권한을 받는 부분이다.

     

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    위 부분은 채널을 생성하는 부분이다.

     

    await flutterLocalNotificationsPlugin.initialize(
        const InitializationSettings(
            android: AndroidInitializationSettings('@mipmap/ic_launcher'),
            iOS: IOSInitializationSettings()),
        onSelectNotification: (String? payload) async {
        
        });

    위 부분은 flutterLocalNotificationsPlugin을 초기화하는 부분이다.

     

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      AppleNotification? ios = message.notification?.apple;
      if (notification != null && (android != null || ios != null) && !kIsWeb) {
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
              android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                  icon: 'ic_launcher'
              ),
              iOS: const IOSNotificationDetails()
          ),
        );
      }
    });

    위 코드는 Foreground에서 메시지를 수신 받았을 때의 코드를 작성하는 부분이다.

    댓글

Designed by Tistory.