Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background/Foreground service in react native using Headless JS

I am using Headless JS in react native to create background service. My requirement is to create a service which will be invoked from MainActivity (For example on click of a button) and continue to execute even after the App goes to background. I could manage to create the service with Headless JS and invoke on button click. For simplicity I will explain with simple code

MyTask.js

module.exports = async () => {
    console.log("I am called from java service");
    for(var i=0; i<1000000;i++){
        console.log("I am called from for loop"+i);
    }
};

When using the above code, even after the app goes to background the for loop continues execution till i reaches 999999 also I am able to see the log message in console.

But my actual Task contains some async functions. For example when I use the following code in my task, it fails to print when the app goes to background

module.exports = async () => {
    console.log("I am called from java service");
    setInterval(() => {
        console.log("I am called from java service inside setInterval");
    }, 100);
}; 

The above code is supposed to print the log message continuously in 100 ms intervals. But the moment the app goes to background it stops printing. Again when the app resumes, it start printing again.

Can someone help on this?

like image 730
Vineesh Avatar asked Jan 29 '26 07:01

Vineesh


1 Answers

My guess is that your activity is paused once your async headless task is over (from the caller perspective), this is what RN documentation suggests :

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

Although it's unclear, as you might think that JS timers - like setInterval would keep your code running... They won't.

The solution implied by RN doc is to implement a native service - for example a native timer instead of a JS one - which is basically what react-native-background-timer does...

EDIT

Regarding foreground execution, by default, headlessJS tasks are not allowed in foreground and will raise an error.

like image 128
Vinzzz Avatar answered Jan 31 '26 20:01

Vinzzz