How to Implement Background Task Functionality in React Native?

By Prajwal Haniya

Techletter #36 | June 29, 2023

What are background tasks?

Imagine your app makes use of user location. You are tracking location because you provide statistics of how much a user travelled in a single day or week or month or year. So, that is nothing but you have built an app for travel monitoring or management.

For this type of application, you will be tracking the user’s location always, until and unless the user will disable the permissions. So how do you track it? You need the help of background tasks or to be precise a foreground service.

In this blog, I will explain how you can implement background tasks in react native along with the expo. Using expo you can build and deploy mobile applications quickly. Believe me, with expo cli, you can save a lot of time.

There are 2 cases of background tasks:

Case 1: The tasks that run when you minimize the application

Case 2: The tasks that run even when you close the application completely.

Below is a simple react component, in which I will implement background tasks for both of the above cases.

When the application is minimized:

import * as BackgroundFetch from 'expo-background-fetch';

function App() {
    const LOCATION = 'location-in-background';

    TaskManager.defineTask(LOCATION, async () => {
        const now = Date.now();
        // Calls the below function for every minute when the app is minimized
        getLocation();
        return BackgroundFetch.BackgroundFetchResult.NewData;
    });

    (async function registerBackgroundFetchAsync() {
        return BackgroundFetch.registerTaskAsync(CALL_LOGS_IN_BACKGROUND, {
          minimumInterval: 60 * 10, 
          stopOnTerminate: false,
          startOnBoot: true,
        });
      })();

      return (
        <>
            {
                // Your component logic
            }
        </>
      )
}
export default App;

Link to official docs: https://docs.expo.dev/versions/latest/sdk/background-fetch/

When the application is closed:

For this, we will be using react-native-background-actions

Inside AndroidManifest.xml file

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">
    <service android:name="com.asterinet.react.bgactions.RNBackgroundActionsTask"/>
</application>

Note: I could run the background tasks successfully only after adding the above permissions to AndroidManifest.xml

import BackgroundService from 'react-native-background-actions';

function App() {
    useEffect(() => {
        startBackgroundTask();
    }, []);

    const veryIntensiveTask = async (taskDataArguments) => {
        const { delay } = taskDataArguments;
        await new Promise( async (resolve) => {
            for (let i = 0; BackgroundService.isRunning(); i++) {
                console.log("CALLING API IN BACKGROUND")
                // CALL FUNCTION OR DO ANYTHING THAT YOU WANT TO DO IN THE BACKGROUND
                await sleep(delay);
            }
        });
    };

    const startBackgroundTask = async () => {
    try {
        // This is for the notification for the user
      const options = {
        taskName: 'Location',
        taskTitle: 'Tracking Management',
        taskDesc: 'Tracking management application',
        taskIcon: {
            name: 'ic_launcher',
            type: 'mipmap',
        },
        linkingURI: 'your package name',
        parameters: {
            delay: 600000,
        },
      };
      
      await BackgroundService.start(veryIntensiveTask, options);
      await BackgroundService.updateNotification({taskDesc: 'Application started in background'});
    } catch (error) {
         console.log('Error while running background task', error);
    }
  }
} 

export default App;

Link to the official docs: https://github.com/Rapsssito/react-native-background-actions