The JS API
A task is a async function that you register on
AppRegistry, similar to registering React applications:
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).
The Java API
Yes, this does still require some native code, but it's pretty thin. You need to extend
HeadlessJsTaskService and override
Then add the service to your
Now, whenever you start your service, e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.
By default, the headless JS task will not perform any retries. In order to do so, you need to create a
HeadlessJsRetryPolicy and throw a specific
LinearCountingRetryPolicy is an implementation of
HeadlessJsRetryPolicy that allows you to specify a maximum number of retries with a fixed delay between each attempt. If that does not suit your needs then you can implement your own
HeadlessJsRetryPolicy. These policies can be passed as an extra argument to the
HeadlessJsTaskConfig constructor, e.g.
A retry attempt will only be made when a specific
Error is thrown. Inside a headless JS task, you can import the error and throw it when a retry attempt is required.
If you wish all errors to cause a retry attempt, you will need to catch them and throw the above error.
- The function passed to
setTimeoutdoes not always behave as expected. Instead the function is called only when the application is launched again. If you only need to wait, use the retry functionality.
- By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. You can pass a fourth
booleanargument to control this behaviour.
- If you start your service from a
BroadcastReceiver, make sure to call
HeadlessJsTaskService.acquireWakeLockNow()before returning from
Service can be started from Java API. First you need to decide when the service should be started and implement your solution accordingly. Here is an example that reacts to network connection change.
Following lines shows part of Android manifest file for registering broadcast receiver.
Broadcast receiver then handles intent that was broadcasted in onReceive function. This is a great place to check whether your app is on foreground or not. If app is not on foreground we can prepare our intent to be started, with no information or additional information bundled using
putExtra (keep in mind bundle can handle only parcelable values). In the end service is started and wakelock is acquired.