プッシュ通知を受信する

前提条件

事前に karte_core パッケージの導入を行う必要があります。

KARTE ではプッシュ通知の送信に、Firebase Cloud Messaging(以下FCM)を利用しています。
そのためFCM経由でプッシュ通知を送信するための各種設定を行う必要があります。

また受信側のアプリケーションでもFirebaseライブラリの導入などの対応が必要となります。

なお本ドキュメントでは、firebase_messaging パッケージ を利用する前提で説明します。
これ以外のライブラリを利用する場合は、読み替えた上で導入を行ってください。

導入手順

STEP1: firebase_messaging を導入する

  1. SDKを導入する
    導入に関しては、下記ドキュメントをご覧ください。
  1. Notification Composer で通知のテストを行う
    Firebase の Notification Composer から通知メッセージを送信し、メッセージが受信できるか確認してください。
    Send a notification message

STEP2: サービスアカウントの設定を行う

KARTEからFCMに対して通知の送信リクエストを行うために、KARTE側にサービスアカウントの設定を行う必要があります。
サービスアカウントを設定する

STEP3: karte_notification を導入する

共通

アプリケーションの pubspec.yaml の dependencies にパッケージを記入し、 pub get コマンドでインストールしてください。

dependencies:
  karte_notification: ^1.3.0
flutter pub get

STEP4: FCMトークンを送信する

KARTE からプッシュ通知を送信するためには、FCMトークンが必要となります。
そのためアプリケーションからKARTEにFCMトークンを送信する処理を実装します。

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:karte_notification/karte_notification.dart' as krt;

class _MyAppState extends State<MyApp> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.getToken().then((String? token) {
      if (token == null) return;
      // 取得したトークンをKARTEに送信
      krt.Notification.registerFCMToken(token);
    });
    _firebaseMessaging.onTokenRefresh.listen((String token) {
      // 更新されたトークンをKARTEに送信
      krt.Notification.registerFCMToken(token);
    });

    // ...
  }
}

STEP5: プラットフォーム毎の実装

KARTE Flutter SDKには通知受信・タップ時の処理用のメソッドが各プラットフォームごとに用意されています。
アプリのプラットフォームやステータスに応じて、firebase-messagingライブラリの各コールバックに対応するようにメソッドの呼び出しを行ってください。

アプリの状態イベントfirebase-messagingのメソッドKARTE SDKのメソッド処理内容
iOS / Foreground受信onMessage--
iOS / ForegroundタップonMessageOpenedApphandleForIOS通知タップによるdeeplink発火
iOS / Background受信onBackgroundMessage--
iOS / BackgroundタップonMessageOpenedApphandleForIOS通知タップによるdeeplink発火
iOS / Terminated受信onBackgroundMessage--
iOS / TerminatedタップgetInitialMessagehandleForIOS通知タップによるdeeplink発火
Android / Foreground受信onMessagehandleForAndroid通知の表示
Android / Foregroundタップ---
Android / Background,Terminated受信onBackgroundMessagehandleForAndroid通知の表示
Android / Background,Terminatedタップ---

それぞれのメソッド handleForIOS handleForAndroid は、対象外のプラットフォームでは何も処理を行いません。
そのため、基本的に下記のように呼び出せばそれぞれのSDKと同様の動作が期待されます。

  • onMessage: handleForAndroid
  • onMessageOpenedApp: handleForIOS
  • onBackgroundMessage: handleForAndroid
  • 起動後初回のgetInitialMessage: handleForIOS

次に具体的な実装例を示します。

iOSの場合のSTEP5実装例

受信したプッシュ通知をタップ(開封)した際、通知メッセージに含まれているリンクを開くためには下記の実装が必要となります。
参考: FCMのFlutter実装例

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:karte_notification/karte_notification.dart' as krt;

class _MyAppState extends State<MyApp> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  @override
  void initState() {
    super.initState();

    // アプリ未起動状態から通知が開かれた際の処理
    RemoteMessage? message =
        await FirebaseMessaging.instance.getInitialMessage();
    if (message != null) {
        var karteNotification = await krt.Notification.create(message);
        if (karteNotification != null) {
          karteNotification.handleForIOS();
        }
    }

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      // アプリ起動状態から通知が開かれた際の処理
      var karteNotification = await krt.Notification.create(message);
      if (karteNotification != null) {
        karteNotification.handleForIOS();
      }
    });

    // ...
  }
}

Androidの場合のSTEP5実装例

KARTEから送信されるメッセージはデータメッセージとして送信されます。
データメッセージのため、アプリの状態(foreground / background)によって実装する処理が異なります。
参考: FCMのFlutter実装例

foreground時に受信する場合の実装

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:karte_notification/karte_notification.dart' as krt;

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      // アプリがforeground時に受信する場合
      var karteNotification = await krt.Notification.create(message);
      if (karteNotification != null) {
        karteNotification.handleForAndroid();
      }
    });

    // ...
  }
}

background時に受信する場合の実装

flutter v1.12未満を使用する場合 Flutter v1.12未満(Flutter Android Embedding V1)の場合、backgroundで受信した際に `karte_notification` モジュールで処理を行うためには、 `firebase_messaging` パッケージが起動するbackgroundの `FlutterNativeView` に `karte_notification` を登録する必要があります。 `FlutterApplication` を実装したクラスに、`firebase_messaging` のServiceを登録するコードを追記したところに `karte_notification` を登録するコードも追加します。
class YourApplication : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {

    private val appKey = "YOUR_APP_KEY"
    override fun onCreate() {
        super.onCreate()

        FlutterFirebaseMessagingService.setPluginRegistrant(this)
        KarteApp.setup(this, appKey)
    }

    override fun registerWith(registry: PluginRegistry?) {
        if (registry?.hasPlugin("io.flutter.plugins.firebasemessaging") == false) {
            FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging"))
        }
        // KarteNotificationPluginをFirebaseMessagingServiceに登録する処理
        if (registry?.hasPlugin("io.karte.flutter.notifications") == false) {
            KarteNotificationPlugin.registerWith(registry.registrarFor("io.karte.flutter.notifications"))
        }
    }
}
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:karte_notification/karte_notification.dart' as krt;


Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) async {
  // アプリがbackground時に受信した場合
  var karteNotification = await krt.Notification.create(message);
  if (karteNotification != null) {
    karteNotification.handleForAndroid();
  }
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onBackgroundMessage(myBackgroundMessageHandler);
    // ...
  }
}

動作確認

最後に正しく導入が行われているか確認を行うためにテストメッセージを送信して確認を行います。

詳細については、下記ドキュメントをご覧ください。
テストメッセージを送信する