有没有办法在react-native上创建一个后台服务,在Android上实现?我需要一个定时器,每小时唤醒一次并启动一个简单的JavaScript任务。
有没有办法在react-native上创建一个后台服务,在Android上实现?我需要一个定时器,每小时唤醒一次并启动一个简单的JavaScript任务。
是的,这是可以实现的。
React Native在本地桥接(Java/Objc)和JS之间运行,其中涉及“本地”和JS模块的概念(模块可以具有您可以从桥的“另一侧”调用的方法)。所有UI都是在桥的基础上构建的(处理生成视图的主要“本地”模块称为“UIManager”)。可以直接使用桥,唯一的限制是通信必须是异步的。
您可以从JAVA代码中调用JavaScript函数。参见此链接以获取文档。
当然可以。实际上,现在完全可以使用JS(无需编写原生代码)通过React Native Queue和React Native Background Task在跨平台上实现这个功能。
但是有一些限制。后台任务最小时间间隔大约为15分钟(如果甚至触发了定时任务,其定时不保证准确 - iOS/Android调度程序是一个黑匣子,它考虑电池寿命、当前CPU负载等因素来确定何时触发已安排的任务)。此外,任务的执行时间限制为30秒。
如果您在安装和运行中遇到任何困难,请告诉我。
发布v0.36版本,目前仅支持无界面JavaScript执行(Headless-JS)在安卓平台上。
https://facebook.github.io/react-native/docs/headless-js-android.html
react-native-background-job
库来运行后台服务。即使杀掉应用程序,它也可以正常工作。
https://github.com/vikeri/react-native-background-job
import BackgroundJob from "react-native-background-job";
const regularJobKey = "regularJobKey";
BackgroundJob.register({
jobKey: regularJobKey,
job: () => {
console.log('Background Service Call!');
}
});
<TouchableHighlight
onPress={() => {
BackgroundJob.schedule({
jobKey: regularJobKey,
period: 2000
});
}}
>
<Text>Schedule regular job</Text>
</TouchableHighlight>
尝试使用react-native-background-actions,它是一个非常棒的服务,即使对于iOS也是如此,并且他们还提供了ProgressBar功能。
yarn add react-native-background-actions
or npm:
npm install --save react-native-background-actions
import BackgroundService from 'react-native-background-actions';
// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
// Example of an infinite loop task
const { delay } = taskDataArguments;
await new Promise((resolve) => {
for (let i = 0; BackgroundService.isRunning(); i++) {
console.log(i);
await sleep(delay);
}
});
};
const options = {
taskName: 'Example',
taskTitle: 'ExampleTask title',
taskDesc: 'ExampleTask description',
taskIcon: {
name: 'ic_launcher',
type: 'mipmap',
},
color: '#ff00ff',
linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
parameters: {
delay: 1000,
},
};
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();