registerAndroidPushNotificationHandlers function

Future<void> registerAndroidPushNotificationHandlers(
  1. AndroidSettings androidSettings
)

Implementation

Future<void> registerAndroidPushNotificationHandlers(
    AndroidSettings androidSettings) async {
  // Get the token each time the application loads
  fcmToken = await FirebaseMessaging.instance.getToken();
  print('📘 Firebase token: $fcmToken');

  // Update the token each time it refreshes
  FirebaseMessaging.instance.onTokenRefresh.listen(_onFCMTokenRefresh);

  await _flutterLocalNotificationsPlugin.initialize(
    InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    ),
    onDidReceiveNotificationResponse: _onSelectNotification,
  );

  _androidSettings = androidSettings;

  // Save push notification settings to shared preferences.
  final preferences = await SharedPreferences.getInstance();
  preferences.setString(ANDROID_SETTINGS, jsonEncode(_androidSettings));

  try {
    final activeNotifications = await _flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.getActiveNotifications();

    if (activeNotifications != null) {
      for (final displayedNotification in activeNotifications) {
        if (displayedNotification.payload != null) {
          final Map<String, dynamic> talkjsData =
              json.decode(displayedNotification.payload!);

          if ((talkjsData['conversation'] != null) &&
              (talkjsData['conversation']['id'] != null)) {
            print('📘 Existing notification: ${displayedNotification.payload}');
            final String notificationId = talkjsData['conversation']['id'];

            if (!_showIdFromNotificationId.containsKey(notificationId)) {
              _showIdFromNotificationId[notificationId] = _nextId;
              _nextId += 1;
            }

            if (_activeNotifications[notificationId] == null) {
              _activeNotifications[notificationId] = [
                displayedNotification.payload!
              ];
            } else {
              _activeNotifications[notificationId]!
                  .add(displayedNotification.payload!);
            }
          }
        }
      }
    }
  } on PlatformException {
    // PlatformException is raised on Android < 6.0
    // Simply ignoring this part
  }

  FirebaseMessaging.onBackgroundMessage(_onFCMBackgroundMessage);
}