2

I have a react native application which is doing some task and sending the data to the backend. I want this task to keep running even if the app is closed, as in the app should keep running on the background of device.

NOTE: this app will only run in android

3

3 Answers 3

2

It's always good to use native functionality. If you want to execute JavaScript tasks in background. Then implement it using Headless JS https://reactnative.dev/docs/headless-js-android

0

You can make use of this library https://github.com/transistorsoft/react-native-background-fetch. There's good documentation about how to set it up & what you have to do in order to ensure that the app will execute tasks even when in background/killed. This is a little bit of a grey area and background tasks are usually not 100% reliable, but this library provides good solution.

0

I found a library which works well in Android 12 even while the screen is off:

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

Follow the installation and call the function like so:

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);
  }, []);

This also works in iOS but stops if you keep the app in the background for longer than two minutes. I have no idea why.

(Also I tried https://github.com/Rapsssito/react-native-background-actions library, but this also has same problem in iOS, and it doesn't work in Android).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.