我正在尝试使用 expo 后台获取在 react-native 中实现后台任务。我创建了测试功能,它在按下按钮后运行后台任务并将“测试”打印到控制台。但是,当我调用此任务时,没有任何反应。有什么办法可以解决这个问题吗?
根据要求,我将此添加到我的 app.json
文件中
{
"expo": {
...
"ios": {
...
"infoPlist": {
...
"UIBackgroundModes": [
"location",
"fetch"
]
}
}
}
}
示例代码:
import React, { useContext } from "react";
import { View, StyleSheet } from "react-native";
import { Text, Button } from "react-native-elements";
import { SafeAreaView } from "react-navigation";
import Spacer from "../components/Spacer";
import { Context as AuthContext } from "../context/AuthContext";
import { Context as TwoFactorContext } from "../context/TwoFactorContext";
import { FontAwesome } from "@expo/vector-icons";
import TwoFactorFalseForm from "../components/TwoFactorFalseForm";
import TwoFactorTrueForm from "../components/TwoFactorTrueForm";
import { NavigationEvents } from "react-navigation";
import { customStyle } from "../components/Styles";
import * as TaskManager from "expo-task-manager";
import * as BackgroundFetch from "expo-background-fetch";
const LOCATION_TASK_NAME = "background-location-task";
TaskManager.defineTask(LOCATION_TASK_NAME, () => {
console.log("Test");
});
const AccountScreen = () => {
const {
state: { username },
signout,
} = useContext(AuthContext);
const {
state: { isEnabled },
checkIsEnabled,
reset,
} = useContext(TwoFactorContext);
return (
<SafeAreaView style={customStyle.container} forceInset={{ top: "always" }}>
<NavigationEvents onWillFocus={() => checkIsEnabled({ username })} />
<Text style={customStyle.mainText}>Account</Text>
<Text style={customStyle.passwordTextLabel}>Username</Text>
<Text style={customStyle.passwordTextSmall}>{username}</Text>
{isEnabled == true ? (
<TwoFactorTrueForm />
) : isEnabled == false ? (
<TwoFactorFalseForm />
) : (
<Text>Error</Text>
)}
<Spacer>
<Button
title="Sign Out"
onPress={signout}
onPressIn={reset}
buttonStyle={customStyle.button}
titleStyle={customStyle.title}
/>
<Button
title="Register background task"
onPress={async () => {
await BackgroundFetch.registerTaskAsync(LOCATION_TASK_NAME, {
minimumInterval: parseInt(60),
stopOnTerminate: false,
startOnBoot: true,
});
}}
/>
</Spacer>
</SafeAreaView>
);
};
AccountScreen.navigationOptions = {
title: "Account",
tabBarIcon: <FontAwesome name="gear" size={20} />,
};
export default AccountScreen;