[Flutter]AndroidでPush通知を受信して処理する
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アプリのプッシュ通知を実装する手順です。#Terminated の場合
#Terminated 通知受信時の処理
main 関数の前にハンドラを追加し、FirebaseMessaging.onBackgroundMessageでコールバックで呼び出します。
@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 で通知内容を取得できます。
void main() async {
・・・
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
debugPrint(
"Terminatedで通知からアプリを開きました: ${initialMessage.notification?.title}")
;
}Terminated の動作確認方法はこちらの投稿を参照してください。
[Flutter]アプリが終了(Terminated)状態のデバッグをする
Flutterでアプリリンクやプッシュ通知のアプリがTerminated状態の場合をデバッグする方法をまとめました。#Background の場合
#Background 通知受信時の処理
Terminated と同様に、FirebaseMessaging.onBackgroundMessageで処理します。
@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で処理します。
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アプリのプッシュ通知を実装する手順です。
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.initializeのonDidReceiveNotificationResponseで処理します。
void main() async {
・・・
flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
),
onDidReceiveNotificationResponse: (NotificationResponse details) {
debugPrint("Foregroundの通知をタップしました: ${details.payload}");
},
);
}通知のデータを受けとるには、flutterLocalNotificationsPlugin.showのpayloadに設定するとonDidReceiveNotificationResponseで取得できます。
flutterLocalNotificationsPlugin.show(
・・・
NotificationDetails(
・・・
),
payload: notification.body,
);flutterLocalNotificationsPlugin.initialize(
・・・
onDidReceiveNotificationResponse: (NotificationResponse details) {
debugPrint("onMessageOpenedApp: ${details.payload}");
},
);#参考
Flutter アプリでメッセージを受信する | Firebase Cloud Messaging
Flutter アプリで Firebase Cloud Messaging からメッセージを受信して処理する方法について学びます。#まとめ
以上、Flutter の Android アプリでプッシュ通知を受信した際の処理方法のまとめでした。
どなたかの参考になれば幸いです。
