如何在 react native 中正确处理 redux saga 和后台事件?



我正在使用react-native,redux-saga,react-native-background-task。

首先,当我的应用程序从前台转到后台(在IOS和Android上)时,传奇仍在继续。我本来希望它会停止,但我想因为传奇在另一个线程上,它继续。这是否会导致电池管理出现问题或阻止IOS允许应用程序执行后台提取事件?

其次,当后台任务启动时,在 Android 应用程序上,我的主要传奇像往常一样开始(不是预期的行为,我会认为只有后台任务代码才能运行。在IOS上,只有后台任务代码按我的预期运行。为什么安卓应用会再次开启整个传奇?

第三,当我使用 xcode 来"模拟后台获取"时,它工作了一点,但现在它正在关闭任何其他打开的应用程序并且不运行任务代码。这是为什么呢?

以下是我定义后台任务的位置:

BackgroundTask.define(async () => {
const now = moment().format("HH:mm:ss");
console.log("Executing background task at: ", now);
console.log("Test Test Test!");
BackgroundTask.finish();
});

这是我计划后台任务并包含 redux 的地方:

import React from 'react';
import { SafeAreaView, View, StatusBar, Alert } from 'react-native';
import { Provider } from 'react-redux';
import { redux_store } from './redux/store';
import { AppContainer } from './helpers/navigation.js';
import { styles } from './styles/styles.js';
import ReduxRootConnection from './components/reduxRoot';
import { aws_configure } from './helpers/aws-configure';
import BackgroundTask from 'react-native-background-task'
aws_configure();
import { initPushNotifications } from './helpers/initPN';
export default class App extends React.Component {
componentDidMount() {
// TODO: add this back in
// initPushNotifications()
BackgroundTask.schedule();
this.check_background_task_status();
}
async check_background_task_status() {
const status = await BackgroundTask.statusAsync();
console.log("BackgroundTask Status: ", status);
}
render() {
return (
<Provider store={redux_store}>
<View style={{flex: 1}}>
<SafeAreaView style={styles.mainAppContainerStyle}>
<ReduxRootConnection>
<AppContainer/>
</ReduxRootConnection>
</SafeAreaView>
</View>
</Provider>
);
}
}

当 react 原生应用程序在 android 上后台运行时,并不意味着该活动一定会被销毁,因此您的 js 代码可能会继续运行不确定的时间。最终,如果用户不再次打开您的活动,您的活动可能会停止,但您无法确切知道何时。您可以使用 react native 的AppState(https://facebook.github.io/react-native/docs/appstate) 来取消您希望在应用程序进入后台时取消的传奇。

对于后台任务问题,Android 上的 BackgroundTask 实现使用 react native 的无头 js (https://facebook.github.io/react-native/docs/headless-js-android.html),它在后台启动整个应用程序。在ios上没有无头的js,所以实现是不同的。

最新更新