Expo-notifications后台通知接收处理

Joh*_*rge 6 react-native expo expo-notifications

我在 React Native (expo) 中使用 expo-notifications 包来处理传入的通知。当应用程序位于后台和前台时,我可以正确收到通知 - 为了发送通知,我在后端使用“expo-server-sdk”包。我可以使用 expo-notification 包中的 addNotificationReceivedListener() 函数处理前台通知接收。用于处理 expo 文档中的后台通知接收(链接:- https://docs.expo.dev/versions/latest/sdk/notifications/#handling -incoming-notifications-when-the-app-is-1)他们说我们可以使用 expo-task-manager 库来处理它。下面给出了我参考博览会文档编写的代码。

...
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);
    }
})

Run Code Online (Sandbox Code Playgroud)
//This code is written in App.js root component
useEffect(() => {
        Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);

        return()=>{
               Notifications.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
        }
},[])
Run Code Online (Sandbox Code Playgroud)

也在世博会文档中。他们说这个后台任务不适用于 expo go 应用程序。所以 O 执行了 expo run:android 并将应用程序构建到我的物理 Android 设备中。即使完成所有这些操作后,当通知到达时,此任务也没有运行,并且我没有从代码的控制台日志中获得任何输出,也console.log('data-----',data);没有获得代码的输出console.log('error occurred');,这意味着通知时不会执行“BACKGROUND-NOTIFICATION-TASK”当应用程序处于后台时出现。谁能告诉我问题是什么?

Pro*_*eli 4

基本上,你犯的唯一错误就是打电话

通知.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK)

我猜测 useEffect 位于 React 组件内部,此代码必须在 React 组件外部编写,就像使用 TaskManager.defineTask 所做的那样...请查看这个简单的 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
  },
});
Run Code Online (Sandbox Code Playgroud)

不需要useEfect