首页 > 解决方案 > 如何为flutter应用添加android通知通道ID以在应用处于后台时修复通知

问题描述

在我的颤振应用程序中,onResume 和 onLunch 函数在 android 平台上不起作用,虽然它们在 IOS 上运行良好,但我在控制台上收到以下消息,而不是在这些函数中打印字符串:

“W/FirebaseMessaging(24847):AndroidManifest 中缺少默认通知通道元数据。将使用默认值。”

onMessage 功能工作正常,问题是当应用程序在后台时

我的猜测是它与应该添加到 android manifest 中的 android 通知通道 id 有关

当我通过将以下代码添加到 AndroidManifest 将其添加到清单时,消息更改为:(我在值中添加了一个 strings.xml 文件并在那里定义了“default_notification_channel_id”。)

“应用程序尚未创建 AndroidManifest.xml 中设置的通知通道。将使用默认值。”

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id"/>

在我的控制台中,我应该收到我打印的 onResume 和 onLunch 字符串,但我收到以下消息:

“W/FirebaseMessaging(24847):AndroidManifest 中缺少默认通知通道元数据。将使用默认值。”

“应用程序尚未创建 AndroidManifest.xml 中设置的通知通道。将使用默认值。”

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id"/>

标签: flutterfirebase-cloud-messagingandroid-notifications

解决方案


你应该先创建一个通知通道,插件:flutter_local_notifications可以创建和删除通知通道。

首先,初始化插件:

Future<void> initializeLocalNotifications() async {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();
  // app_icon needs to be a added as a drawable resource to the
  // Android head project
  var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
  var initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: onDidReceiveLocalNotification);
  var initializationSettings = InitializationSettings(
      initializationSettingsAndroid, initializationSettingsIOS);
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: selectNotification);
}

其次,使用此插件创建通知通道:

Future<void> _createNotificationChannel(String id, String name,
    String description) async {
  final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  var androidNotificationChannel = AndroidNotificationChannel(
    id,
    name,
    description,
  );
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(androidNotificationChannel);
}

现在你有两个选择:

  1. 使用您已在其中定义的默认 ID 创建一个频道AndroidManifest.xml

  2. 通过将频道 ID 嵌入到 FCM 通知消息中,选择您自己的频道 ID 并将每个通知发送到特定频道。为此,请在标签下的标签下将标签添加channel_id到您的通知中。notificationandroid

以下是来自 Firebase Functions 的带有自定义通知通道 ID 的示例通知消息:

    'notification': {
        'title': your_title,
        'body': your_body,
    },
    'android': {
        'notification': {
            'channel_id': your_channel_id,
        },
    },

推荐阅读