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

React Native中@supersami/rn-foreground-service通知点击事件处理问题

解决@supersami/rn-foreground-service通知点击事件无响应问题

你的代码核心问题在于事件监听方式错误,以及函数定义不完整,以下是修正后的实现方案:

修正后的完整代码

const start = async () => {
  ReactNativeForegroundService.add_task(() => regularFunct(), {
    delay: 1000,
    onLoop: true,
    taskId: "taskid",
    onError: (e) => console.log(`Error logging:`, e),
  });

  // 正确绑定指定事件名的监听回调
  ReactNativeForegroundService.eventListener("notificationClickHandle", async () => {
    await stop();
  });

  ReactNativeForegroundService.start({
    id: 1244,
    title: "Foreground Service",
    message: "We are live World",
    icon: "ic_launcher",
    button: true,
    buttonText: "停止服务",
    buttonOnPress: "notificationClickHandle",
    mainOnPress: "notificationClickHandle",
    setOnlyAlertOnce: true,
    color: "#000000",
    progress: {
      max: 100,
      curr: 50,
    },
  });
};

// 补全函数闭合,确保语法正确
const stop = async () => {
  await ReactNativeForegroundService.stop();
};

关键修改说明

  • 事件监听修正:ReactNativeForegroundService.eventListener需要传入两个参数,第一个是你在mainOnPress/buttonOnPress中配置的事件名("notificationClickHandle"),第二个是触发事件时执行的回调函数,这里直接调用停止服务的逻辑。
  • 函数语法补全:原代码中stop函数缺少闭合的},会导致语法错误,直接影响代码执行,现已补全。
  • 操作文本优化:将按钮文本改为"停止服务",让用户清晰知晓点击后的操作效果。

修改完成后,点击通知主区域或通知按钮,都会触发事件回调并关闭前台服务,无需用户进入应用操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:56:08