hive 当应用程序在flutter中关闭时,我如何将firebase推送通知保存到本地设备?

cdmah0mi  于 2023-01-25  发布在  Hive
关注(0)|答案(1)|浏览(203)

我使用配置单元flutter和flutter本地通知:^13.0.0。我没有任何关于应用程序关闭时在设备本地保存通知的想法。您能帮助我吗?谢谢您的关心。

int badgesCount = 0;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
FirebaseMessaging messaging = FirebaseMessaging.instance;

class PushNotificationsService {
  Future initialise() async {
    iOSPermission();
    messaging.getToken().then((token) async {
      print('token is $token');
    });

    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@drawable/ic_stat_name');
    DarwinInitializationSettings initializationSettingsIOS =
        DarwinInitializationSettings(
            onDidReceiveLocalNotification: onDidReceiveIos);

    InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: (payload) async {
        if (payload != "") {
          log(payload.toString());
        }
      },
    );

    FirebaseMessaging.onMessage.listen(
      (RemoteMessage message) async {
        if (message.notification != null) {
          badgeCount += 1;

          final remoteModel = RemoteMessageModel.fromJson(message.toMap());
          await StorageHiveHelper().save(remoteModel);

          var data = message.notification;
          var title = data?.title.toString();
          var body = data?.body.toString();
          var image = message.data['image'] ?? '';
          var type = message.data['type'] ?? '';
          var id = '';
          id = message.data['type_id'] ?? '';
          if (Platform.isIOS) return;
          if (image != null && image != 'null' && image != '') {
            return await generateImageNotication(
                title ?? "", body ?? "", image, type, id);
          }
        }
      },
    );

    messaging.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        log("Initial Message: " + (message.data.toString()));
        pushToNavigate(message);
      }
    });

    FirebaseMessaging.onMessageOpenedApp
        .listen((RemoteMessage message) => pushToNavigate(message));

    FirebaseMessaging.onBackgroundMessage(getBackGroundMessage);
  }

  pushToNavigate(RemoteMessage? message) async {
    var type = await message?.data['type'] ?? '';
    log("OnDidReceiveIOS: " + (message?.data.toString() ?? "null ios payload"));
    log(type);

    if (type == 'products') {
      navService.pushNamed("product/detail", args: 631509);
    }
  }

  void iOSPermission() async {
    await messaging.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  void onDidReceiveIos(
      int id, String? title, String? body, String? payload) async {
    log("OnDidReceiveIOS: " + (payload?.toLowerCase() ?? "null ios payload"));
    try {
      var iosDetail = const DarwinNotificationDetails(
          presentBadge: true,
          presentAlert: false,
          presentSound: true,
          sound: "cash.caf");

      var platformChannelSpecifics = NotificationDetails(iOS: iosDetail);

      await flutterLocalNotificationsPlugin.show(
          id, title, title, platformChannelSpecifics,
          payload: jsonEncode(payload ?? {}));
    } on Exception catch (e) {
      debugPrint(e.toString());
    }
  }

我尝试在此处将消息保存到配置单元。当应用程序打开时它工作,但当应用程序完全关闭时它不工作

Future<void> getBackGroundMessage(RemoteMessage message) async {
    badgeCount += 1;
    await FlutterAppBadger.updateBadgeCount(badgeCount);
   final remoteModel = RemoteMessageModel.fromJson(message.toMap());

    await StorageHiveHelper().save(remoteModel);
  }
}

const String _sound = "notification_sound";

void display(
  RemoteMessage message,
  NotificationDetails notificationDetails,
) async {
  try {
    await flutterLocalNotificationsPlugin.show(
      message.hashCode,
      message.notification?.title,
      message.notification?.body,
      notificationDetails,
      payload: jsonEncode(message.data),
    );
  } on Exception catch (e) {
    debugPrint(e.toString());
  }
}

Future<void> generateSimpleNotication(
    String title, String msg, String type, String id, RemoteMessage pay) async {
  try {
    if (Platform.isIOS) return;
    log("Payload" + (pay.toMap().toString()));
    final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;

    var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
      'high_importance_channels',
      'High Importance Notifications',
      playSound: true,

      sound: RawResourceAndroidNotificationSound(_sound),
      largeIcon: DrawableResourceAndroidBitmap('@drawable/ic_stat_name'),
      importance: Importance.max,
      priority: Priority.max,  );
    var iosDetail = const DarwinNotificationDetails(
        presentAlert: true, presentSound: true, sound: "cash.caf");

    var platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iosDetail);
    await flutterLocalNotificationsPlugin.show(
        id, title, msg, platformChannelSpecifics,
        payload: jsonEncode(pay.data));
  } on Exception catch (e) {
    debugPrint(e.toString());
  }
}
8cdiaqws

8cdiaqws1#

我不明白主要的问题。你只是想在应用程序关闭或在后台显示通知?还是你真的需要将它们保存到本地数据库?无论如何,尝试使用这个类

import 'dart:async';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class PushNotificationService {
  static FirebaseMessaging messaging = FirebaseMessaging.instance;
  static final FlutterLocalNotificationsPlugin notificationPlugin =
      FlutterLocalNotificationsPlugin();
  static const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
    description:
        'This channel is used for important notifications.', // description
    importance: Importance.high,
  );
  static String? idPush;
  static StreamController<RemoteMessage> _messageStream =
      StreamController.broadcast();
  static Stream<RemoteMessage> get messagesStream => _messageStream.stream;

  static Future _backgroundHandler(RemoteMessage message) async {
    _messageStream.add(message);
    // implement your actions here
  }

  static Future _onMessageHandler(RemoteMessage message) async {
    _messageStream.add(message);
    // implement your actions here, if you want to use flutter_local_notifications, use the display() method.
  }

  static Future _onMessageOpenApp(RemoteMessage message) async {
    _messageStream.add(message);
    // implement your actions here
  }

  // iniciar firebase i notificacions locals
  static Future initializeApp() async {
    //Push notifications
    await Firebase.initializeApp();
    idPush = await FirebaseMessaging.instance.getToken();
    print('idPush: $idPush');
    //Handler
    FirebaseMessaging.onBackgroundMessage(_backgroundHandler);
    FirebaseMessaging.onMessage.listen(_onMessageHandler);
    FirebaseMessaging.onMessageOpenedApp.listen(_onMessageOpenApp);

    //local notifications initialization
    const InitializationSettings initializationSettings =
        InitializationSettings(
      iOS: DarwinInitializationSettings(),
      android: AndroidInitializationSettings("@mipmap/ic_notification"),
    );
    notificationPlugin.initialize(initializationSettings);
  }

  // mètode per obrir una notificació local (només amb l'app oberta)
  static void display(RemoteMessage message) async {
    try {
      await notificationPlugin.show(
        message.notification!.hashCode,
        message.notification!.title,
        message.notification!.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel.id,
            channel.name,
            channelDescription: channel.description,
            color: Colors.blue,
            icon: '@mipmap/ic_notification',
          ),
          iOS: const DarwinNotificationDetails(
              presentAlert: true, presentBadge: true, presentSound: true),
        ),
      );
    } on Exception catch (e) {
      print(e);
    }
  }

  // demanar permisos
  Future<void> requestPermission() async {
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }
  }

  static closeStreams() {
    _messageStream.close();
  }
}

此类将在应用程序关闭或处于后台时显示通知。如果您需要在应用程序打开时显示通知,您可以通过display方法。如果您希望将通知保存到配置单元,只需在处理程序中实现该部分。最后在主目录中初始化该类:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PushNotificationService.initializeApp();
  runApp(const MyApp());
}

相关问题