mochotomochotoロゴ

[Flutter]AndroidでPush通知を受信して処理する

広告Flutter
2024年03月31日

Firebase Cloud Messaging(以下 FCM)を利用して、Flutter の Android アプリでプッシュ通知を受け取った時に処理する方法のまとめです。

アプリの状態が Terminated・Background・Foreground ごとに通知を受信・通知をタップした場合をそれぞれまとめています。

  • Flutter 3.16.5
  • firebase_core: ^2.25.3
  • firebase_messaging: ^14.7.14
  • flutter_local_notifications: ^16.3.2
  • Android 実機で検証
  • Firebase Cloud Messaging(以下 FCM)の設定は完了している前提です。

プッシュ通知の設定はこちらの投稿を参照してください。

[Flutter]Android用のPush通知を実装する

Flutter Andoroidアプリのプッシュ通知を実装する手順です。mochot.commochot.com
[Flutter]Android用のPush通知を実装する

#Terminated の場合

#Terminated  通知受信時の処理

main 関数の前にハンドラを追加し、FirebaseMessaging.onBackgroundMessageでコールバックで呼び出します。

main.dart
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  debugPrint("TerminatedまたはBackgroundで通知受信: ${message.notification?.title}");
}
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

これで、アプリが Terminated 状態で通知を受信した際に_firebaseMessagingBackgroundHandlerの処理が実行されます。

#Terminated  通知タップ時の処理

Terminated 状態で通知をタップしてアプリを起動した場合は、getInitialMessage で通知内容を取得できます。

main.dart
void main() async {
 ・・・
  RemoteMessage? initialMessage =
      await FirebaseMessaging.instance.getInitialMessage();
  if (initialMessage != null) {
    debugPrint(
      "Terminatedで通知からアプリを開きました: ${initialMessage.notification?.title}")
    ;
  }

Terminated の動作確認方法はこちらの投稿を参照してください。

[Flutter]アプリが終了(Terminated)状態のデバッグをする

Flutterでアプリリンクやプッシュ通知のアプリがTerminated状態の場合をデバッグする方法をまとめました。mochot.commochot.com
[Flutter]アプリが終了(Terminated)状態のデバッグをする

#Background の場合

#Background  通知受信時の処理

Terminated と同様に、FirebaseMessaging.onBackgroundMessageで処理します。

main.dart
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  debugPrint("TerminatedまたはBackgroundで通知受信: ${message.notification?.title}");
}
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

#Background  通知タップ時の処理

Background 状態で通知をタップしてアプリを起動した場合は、FirebaseMessaging.onMessageOpenedApp.listenで処理します。

main.dart
void main() async {
  ・・・
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    debugPrint("Backgroundで通知からアプリを開きました: ${message.notification?.title}");
  });
}

#Foreground の場合

#Foreground  通知受信時の処理

アプリがフォアグラウンドで通知を受信した場合は、FirebaseMessaging.onMessage.listenで処理します。
Android は通知が表示されないため、flutter_local_notification パッケージを利用してローカル通知として表示しています。

flutter_local_notification の設定の詳細はこちらの投稿を参照してください。

[Flutter]Android用のPush通知を実装する

Flutter Andoroidアプリのプッシュ通知を実装する手順です。mochot.commochot.com
[Flutter]Android用のPush通知を実装する
main.dart
 
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
 
void main() async {
  ・・・
  FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
    debugPrint("Foregroundで通知受信 ${message.notification?.title}");
 
    final RemoteNotification? notification = message.notification;
    if (notification != null) {
      flutterLocalNotificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            'channel_id',
            'channel_name',
            importance: Importance.high,
            icon: '@mipmap/ic_launcher',
          ),
        ),
   
      );
    }
  });
}

#Foreground 通知タップ時の処理

Foreground 状態で表示されたローカル通知をタップした場合は、flutterLocalNotificationsPlugin.initializeonDidReceiveNotificationResponseで処理します。

main.dart
void main() async {
  ・・・
  flutterLocalNotificationsPlugin.initialize(
    const InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    ),
    onDidReceiveNotificationResponse: (NotificationResponse details) {
      debugPrint("Foregroundの通知をタップしました: ${details.payload}");
    },
  );
}

通知のデータを受けとるには、flutterLocalNotificationsPlugin.showpayloadに設定するとonDidReceiveNotificationResponseで取得できます。

main.dart
flutterLocalNotificationsPlugin.show(
  ・・・
  NotificationDetails(
    ・・・
  ),
  payload: notification.body,
);
main.dart
flutterLocalNotificationsPlugin.initialize(
  ・・・
  onDidReceiveNotificationResponse: (NotificationResponse details) {
    debugPrint("onMessageOpenedApp: ${details.payload}");
  },
);

#参考

Flutter アプリでメッセージを受信する  |  Firebase Cloud Messaging

Flutter アプリで Firebase Cloud Messaging からメッセージを受信して処理する方法について学びます。google.comgoogle.com

#まとめ

以上、Flutter の Android アプリでプッシュ通知を受信した際の処理方法のまとめでした。
どなたかの参考になれば幸いです。