如何为 flutter 应用程序添加 Android 通知通道 ID 以修复应用程序在后台运行时的通知

2024-01-18

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

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

onMessage 函数工作正常,问题是当应用程序处于后台时

我的猜测是它与 android 通知通道 id 有关,应将其添加到 android 清单中

当我将以下代码添加到 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"/>

您应该首先创建一个通知通道,插件:flutter_local_notifications https://pub.dev/packages/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,并将通道 ID 嵌入到 FCM 通知消息中,将每个通知发送到特定通道。为此,请添加channel_id标记到您的通知下notification标签,下android tag.

以下是来自 Firebase Functions 的示例通知消息,其中包含自定义通知通道 ID:

    'notification': {
        'title': your_title,
        'body': your_body,
    },
    'android': {
        'notification': {
            'channel_id': your_channel_id,
        },
    },
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 flutter 应用程序添加 Android 通知通道 ID 以修复应用程序在后台运行时的通知 的相关文章

随机推荐