首页 文章

如何在React Native中运行后台任务?

提问于
浏览
60

我在React Native中构建了一个little iOS app来进行位置跟踪,定期将lat / lng发送到用户选择的服务器 . 但是,这仅在应用程序位于前台时才有效 . 当用户在其他应用程序中时,如何在后台运行此任务?

5 回答

  • 9

    这些库可以帮助您实现所需的功能:

    或者,您可以使用react-native中的Headless JS . 但它仅适用于Android .

  • 46

    目前,遗憾的是,不支持任何类型的后台任务 . 您指的功能将是后台计时器 . 这样的计时器是this product pain (a feature request)用于本机反应,您可以通过它来表示对此功能的需求增加 .

    EDIT 12/2016: 仍然没有真正的选择 . 自RN 0.33起你有Headless JS API,但它只适用于android . 如果它在前台运行,你的应用程序也会崩溃,所以你必须小心使用它 . 感谢@Feng指出这一点 .

  • 4

    现在有react-native-background-task这是Android和iOS的单一API .

  • 16

    在过去的几个月里,React Native生态系统一直在以惊人的速度发展,并且已经出现了一些插件来解决无法在后台运行代码的痛苦 .

    https://github.com/transistorsoft/react-native-background-fetch - 定期唤醒30秒以运行一些任意JS代码 . 不适合高分辨率地理定位,因为唤醒之间的时间将是15分钟或更长 .

    https://github.com/transistorsoft/react-native-background-geolocation - 更适合这种情况,专门针对背景中的地理位置 .

  • 4

    我用它,它似乎工作:https://github.com/ocetnik/react-native-background-timer

    定期发送事件(即使app在后台) . 您可以使用setInterval和setTimeout函数 . 此API与react-native相同,可用于使用后台计时器快速替换现有计时器 .

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

相关问题