user icon

Androidでflutter_local_notificationsを使う

AndroidでFirebase Cloud Messagingの表示に、flutter_local_notificationsを使ってみます。
とりあえずフォアグラウンドだけ。

Flutterプロジェクト作成

前回同様 flutter createしたものを使います。
createからflutterfireで設定する所までは省略。

flutter_local_notifications 関連のパッケージを追加します。
flutter pub add firebase_core
flutter pub add firebase_messaging
flutter pub add flutter_local_notifications

ファイル編集

lib/main.dartを編集

importを以下のように追加します。
test202502は、flutter create時のプロジェクト名に変更します。
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:test202502/firebase_options.dart';
main()を編集。
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try{
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // Firebaseの初期化

    // get token
    final fcmToken = await FirebaseMessaging.instance.getToken(); // FCMトークンの取得
    print('FCM Token: $fcmToken');


    // local notificaitons
    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      description: 'This channel is used for important notifications.', // description
      importance: Importance.max,
    );
    // init
    final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    // request permission Android 13
    await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()?.requestNotificationsPermission();
    // create channel
    await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel);


    // show message
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Fore Message notification: ${message.notification?.title} / ${message.notification?.body}');
      print('Fore Message data: ${message.data}');
      //
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channelDescription: channel.description,
                //icon: android.smallIcon,
                icon: 'launch_background',
              ),
            ));
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { // バックグラウンド
      print('Back Message notification: ${message.notification?.title} / ${message.notification?.body}');
      print('Back Message data: ${message.data}');
    });
  }catch (e){
    print(e);
  }
  // run
  runApp(const MyApp());
}

android/app/build.gradle.kts を編集

flutter local notificationsのページに記載が有るのですがktsでない方式なので、そのままでは駄目でした。
android{}ブロック内の各ブロック内に追加・変更します。
isCoreLibraryDesugaringEnabled , multiDexEnabled は無いので追加、それ以外は変更になると思います。
// android{}内で追加・変更
   compileOptions {
       // For AGP 4.1+
       isCoreLibraryDesugaringEnabled = true
       // Sets Java compatibility to Java 8
       sourceCompatibility = JavaVersion.VERSION_1_8
       targetCompatibility = JavaVersion.VERSION_1_8
   }
   kotlinOptions {
       jvmTarget = "1.8"
   }
   defaultConfig {
       multiDexEnabled = true
   }
それから、dependencies{}ブロックは多分無いので追加します。
dependencies {
   // For AGP 7.4+
   coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.3")
}
後は、現バージョンでは、ndkVersionが古いよとWarningが出るので、出た最低バージョンに合わせて書き直します。
※sdkVersionも34以上が必要ですが、今は34以上になっているので変更不要なようです。
    ndkVersion = "27.0.12077973"

ビルド

VSCodeでターゲットをAndroidにしてmain,dartから▷を押してビルド&プレイ。
起動後にPush通知の許可選択のダイアログが出るので、Allow(許可)を選択します。
その後、VSCodeのコンソールに出ているFCM TokenをコピーしてPush通知を行うと、通知が画面上部に表示されました。
Facebooktwitterlinkedintumblrmail
名前
E-mail
URL
コメント

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)