You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为AndroidNotificationDetails中的通知按钮添加点击动作?

Flutter本地通知按钮点击事件处理

要给通知按钮添加点击动作,你需要通过监听通知动作回调来实现,具体操作如下:

  • 初始化flutterLocalNotificationsPlugin时,设置onDidReceiveNotificationResponse回调,捕获通知及按钮的点击事件
  • 在回调内根据动作ID(比如你定义的"stop")执行对应逻辑

修改后的完整代码示例:

// 初始化通知插件并设置点击回调
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

void initNotifications() async {
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('ic_bg_service_small');
  const InitializationSettings initializationSettings =
      InitializationSettings(android: initializationSettingsAndroid);
  
  // 绑定通知点击回调
  await flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onDidReceiveNotificationResponse: (NotificationResponse response) {
      // 判断点击的是哪个按钮
      if (response.actionId == "stop") {
        // 这里写入点击Stop按钮后要执行的逻辑,比如停止后台服务
        print("Stop按钮已点击");
        // 示例:执行服务停止操作等
      }
    },
  );
}

// 展示带按钮的通知
void showNotification() {
  const androidNotification = AndroidNotificationDetails(
      'Bla', 'Bla',
      icon: 'ic_bg_service_small',
      ongoing: true,
      actions: [AndroidNotificationAction("stop", "Stop")]);

  flutterLocalNotificationsPlugin.show(
    888,
    'MyService',
    'bla',
    const NotificationDetails(android: androidNotification),
  );
}

注意事项:

  • 确保项目已正确配置flutter_local_notifications依赖的相关权限(比如AndroidManifest.xml中的权限声明)
  • Android 13及以上版本,需额外申请POST_NOTIFICATIONS权限

内容的提问来源于stack exchange,提问作者blacky99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:50:24