世博会通知后台通知接收处理



我在react native(expo(中使用expo通知包来处理传入通知。当应用程序在后台和前台时,我正确地收到了通知——为了发送通知,我在后台使用了"expo-server-sdk"包。我可以使用expo通知包中的addNotificationReceivedListener((函数处理前台通知接收。用于处理世博会文件中的后台通知接收(链接:-https://docs.expo.dev/versions/latest/sdk/notifications/#handling-incoming-notifications-when-the-app-is-1(他们说我们可以使用expo任务管理器库来处理它。下面是我参考expo文档编写的代码。

...
import * as Notifications from 'expo-notifications';
import * as TaskManager from 'expo-task-manager';
...
//This code is written in root file and outside any react component
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';

TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) =>{ 
if(error){
console.log('error occurred');
}
if(data){
console.log('data-----',data);
}
})
//This code is written in App.js root component
useEffect(() => {
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
return()=>{
Notifications.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
}
},[])

也在世博会文件中。他们表示,这个后台任务将不适用于expogo应用程序。所以O执行了expo-run:android,并将该应用程序构建到我的物理android设备中。即使在完成了所有这些之后,当通知到达时,该任务也没有运行,并且我在控制台日志中没有从代码console.log('data-----',data);获得任何输出,也没有获得代码console.log('error occurred');的输出,这意味着当应用程序处于后台时,当通知到来时,"BACKGROUND-notification-task"不会被执行。有人能告诉我问题出在哪里吗?

基本上,您犯的唯一错误就是调用

Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK(

内部useEffect,我猜它在react组件内部,此代码必须像使用TaskManager.defineTask一样在react部件外部编写。。。看看这个简单的App.js示例,以进一步了解

import { StyleSheet, View } from "react-native";
import * as Notifications from "expo-notifications";
import * as TaskManager from "expo-task-manager";
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) => {
if (error) {
console.log("error occurred");
}
if (data) {
console.log("data-----", data);
}
}
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
export default function App() {
return <View style={styles.container}></View>;
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});

无需使用有效

最新更新