如何保持应用程序在后台运行本机反应

问题描述 投票:0回答:3

我有一个反应本机应用程序,它正在执行一些任务并将数据发送到后端。我希望即使应用程序关闭,此任务也能继续运行,因为应用程序中应该继续在设备后台运行。

注意:此应用程序只能在 Android 中运行

android ios react-native background
3个回答
2
投票

使用本机功能总是好的。如果你想在后台执行 JavaScript 任务。然后使用 Headless JS 实现它https://reactnative.dev/docs/headless-js-android


0
投票

您可以使用这个库https://github.com/transistorsoft/react-native-background-fetch。有很好的文档介绍如何设置它以及您必须做什么才能确保应用程序即使在后台/被杀死时也能执行任务。这是一个灰色地带,后台任务通常不是 100% 可靠,但这个库提供了很好的解决方案。


0
投票

我发现了一个库,即使在屏幕关闭时也能在 Android 12 中正常运行:

https://github.com/ocetnik/react-native-background-timer

按照安装并调用该函数,如下所示:

import BackgroundTimer from "react-native-background-timer";

useEffect(() => {
    const timeoutId = BackgroundTimer.runBackgroundTimer(async () => {
      callYourFunction(); // Call your Function Here
    }, 10000);
    
   // 10000 is 10 Seconds

    return () => BackgroundTimer.clearInterval(timeoutId);
  }, []);

这也适用于 iOS,但如果您使应用程序在后台运行超过两分钟,则会停止。我不知道为什么。

(我也尝试了https://github.com/Rapsssito/react-native-background-actions库,但这在iOS中也有同样的问题,并且在Android中不起作用)。

© www.soinside.com 2019 - 2024. All rights reserved.