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
相关产品推荐
相关产品推荐

