import BackgroundTimer from 'react-native-background-timer';
// Start a timer that runs continuous after X milliseconds
const intervalId = BackgroundTimer.setInterval(() => {
// this will be executed every 200 ms
// even when app is the the background
console.log('tic');
}, 200);
// Cancel the timer when you are done with it
BackgroundTimer.clearInterval(intervalId);
// Start a timer that runs once after X milliseconds
const timeoutId = BackgroundTimer.setTimeout(() => {
// this will be executed once after 10 seconds
// even when app is the the background
console.log('tac');
}, 10000);
// Cancel the timeout if necessary
BackgroundTimer.clearTimeout(timeoutId);
5 回答
这些库可以帮助您实现所需的功能:
react-native-background-job
react-native-background-task
react-native-background-fetch
或者,您可以使用react-native中的Headless JS . 但它仅适用于Android .
目前,遗憾的是,不支持任何类型的后台任务 . 您指的功能将是后台计时器 . 这样的计时器是this product pain (a feature request)用于本机反应,您可以通过它来表示对此功能的需求增加 .
EDIT 12/2016: 仍然没有真正的选择 . 自RN 0.33起你有Headless JS API,但它只适用于android . 如果它在前台运行,你的应用程序也会崩溃,所以你必须小心使用它 . 感谢@Feng指出这一点 .
现在有react-native-background-task这是Android和iOS的单一API .
在过去的几个月里,React Native生态系统一直在以惊人的速度发展,并且已经出现了一些插件来解决无法在后台运行代码的痛苦 .
https://github.com/transistorsoft/react-native-background-fetch - 定期唤醒30秒以运行一些任意JS代码 . 不适合高分辨率地理定位,因为唤醒之间的时间将是15分钟或更长 .
https://github.com/transistorsoft/react-native-background-geolocation - 更适合这种情况,专门针对背景中的地理位置 .
我用它,它似乎工作:https://github.com/ocetnik/react-native-background-timer