Flutter 本地通知操作按钮点击不起作用

问题描述 投票:0回答:2

我一直在尝试通过本地通知上的操作按钮来工作。但当单击它时,我无法在控制台上打印任何内容(应用程序在前台运行)。我正在使用 flutter_local_notifications:^14.1.1

所有项目设置均已根据设置说明完成。 我想指出大多数在线示例和教程都是从 main.dart 启动通知的。但就我而言,它的 Main.dart -> LoginPage -> HomePage(在 init 方法中调用的通知)

我尝试运行本地通知包的示例应用程序,它运行良好并触发操作按钮事件。我还将启动通知的部分函数复制到我的NotificationService 类中,但没有成功。我做了一些代码比较,在大多数情况下没有发现我的代码和示例应用程序之间有任何主要代码差异(但我可能会遗漏一些正在盯着我看的东西)

在HomePage init 方法中,我调用NotificationService 类,该类是根据文档设置的,如下所示:

NotificationService notifService = NotificationService();
    notifService.showNotificationWithActions(
      "Test Notification",
      "Your have changes that needs approval.",
      actions: <AndroidNotificationAction>[
        const AndroidNotificationAction(dismissNotifID, 'DISMISS',
            cancelNotification: true),
        const AndroidNotificationAction(approveChangesID, 'APPROVE',
            cancelNotification: false),
        const AndroidNotificationAction(viewChangesID, 'VIEW',
            cancelNotification: false),
      ],
    );

通知显示没有问题。但单击批准或查看不会打印我想要打印的内容。但是,控制台确实显示以下内容:

W/ActionBroadcastReceiver(26591):无法检索回调信息

随后按下的每个按钮都会重复此行

E/ActionBroadcastReceiver(26591):引擎已初始化

我似乎无法在按钮按下事件上打印任何其他内容。我在这里错过了什么或做错了什么。对此的任何帮助都是appriced。方向、代码帮助、建议..

通知服务类

class NotificationService {
  FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  Future<bool?> initializeService() async {
    _notificationsPlugin = FlutterLocalNotificationsPlugin();

    // Initialization setting for android
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings("ic_dol_notification");

    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: null,
    );

    return await _notificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse:
          (NotificationResponse notificationResponse) {
        print('onDidReceiveNotificationResponse');
        print('notification(${notificationResponse.id}) action tapped: '
            '${notificationResponse.actionId} with'
            ' payload: ${notificationResponse.payload}');
      },
      onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
    );
  }

  @pragma('vm:entry-point')
  void notificationTapBackground(NotificationResponse notificationResponse) {
    print('notificationTapBackground');
    print('notification(${notificationResponse.id}) action tapped: '
        '${notificationResponse.actionId} with'
        ' payload: ${notificationResponse.payload}');
  }

  final String highGroupKey = 'dolphin.high';
  final String maxGroupKey = 'dolphin.max';

  final String highGroupChannelId = 'HighImportanceNotifs';
  final String highGroupChannelDescription =
      'notification channel to show normal notifications including errors and normal msgs';
  final String maxGroupChannelId = 'MaxImportanceNotifs';
  final String maxGroupChannelDescription =
      'notification channel to show duty change alerts and other alerts that need immediate user attention';
  final String workingNotifChannelId = 'BackgroundWorkOnProgressNotifs';
  final String workingNotifChannelDescription =
      'Shows up when background work is currently ongoing';

  final String highGroupChannelName = 'Normal Notifications';
  final String maxGroupChannelName = 'Duty change Alerts';

  /* 
  this function was copied directly from example project
  hoping it would work. it yeilded same results as any other
  */
  int testid = 1;
  Future<void> showNotificationWithActions(String title, String msg,
      {List<AndroidNotificationAction>? actions}) async {
    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails('your channel id', 'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker',
            actions: actions);

    NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );
    await _notificationsPlugin.show(testid++, title, msg, notificationDetails,
        payload: 'item z');
  }

  /// Use this for errors and other msgs
  /// @params [title] title of the notification
  /// @params [msg] body of the notification
  void showHighNotification(String title, String msg,
      {List<AndroidNotificationAction>? actions}) async {
    AndroidNotificationDetails highNotificationAndroidSpecifics =
        AndroidNotificationDetails(
      highGroupChannelId,
      highGroupChannelName,
      channelDescription: highGroupChannelDescription,
      importance: Importance.high,
      priority: Priority.high,
      groupKey: highGroupKey,
      actions: actions,
    );

    NotificationDetails highNotificationPlatformSpecifics =
        NotificationDetails(android: highNotificationAndroidSpecifics);

    await _notificationsPlugin.show(
      612,
      title,
      msg,
      highNotificationPlatformSpecifics,
    );
  }

  /// Use this for Duty Changed notifications
  /// @params [title] title of the notification
  /// @params [msg] body of the notification
  void showMaxNotification(String title, String msg,
      {bool dismissable = true,
      List<AndroidNotificationAction>? actions}) async {
    AndroidNotificationDetails maxNotificationAndroidSpecifics =
        AndroidNotificationDetails(
      maxGroupChannelId,
      maxGroupChannelName,
      channelDescription: maxGroupChannelDescription,
      importance: Importance.max,
      priority: Priority.max,
      groupKey: maxGroupKey,
      playSound: true,
      enableVibration: true,
      showWhen: true,
      visibility: NotificationVisibility.public,
      category: AndroidNotificationCategory.reminder,
      actions: actions,
      ongoing: !dismissable,
    );

    NotificationDetails maxNotificationPlatformSpecifics =
        NotificationDetails(android: maxNotificationAndroidSpecifics);

    await _notificationsPlugin.show(
      832,
      title,
      msg,
      maxNotificationPlatformSpecifics,
    );
  }

  
}
android flutter dart android-notifications
2个回答
0
投票

我也面临着同样的问题,解决我的问题的是添加请求权限以在启动页面/主页上显示通知。

这是代码

Future<void> _requestPermissions() async {
if (Platform.isIOS || Platform.isMacOS) {
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          IOSFlutterLocalNotificationsPlugin>()
      ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          MacOSFlutterLocalNotificationsPlugin>()
      ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
} else if (Platform.isAndroid) {
  final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
      flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();

  final bool? granted = await androidImplementation?.requestPermission();
  setState(() {
    _notificationsEnabled = granted ?? false;
  });
}

希望它能解决您的问题


0
投票

W/ActionBroadcastReceiver(26591): 无法获取回调信息 已检索

我可以通过将通知设置(notificationsPlugin初始化和其他通知侦听器)放在主函数中的runApp函数之前来解决问题

© www.soinside.com 2019 - 2024. All rights reserved.