How to use React Native Foreground Service

A Foreground Service for React Native apps, with multiple headless tasks
Why can you need such a kind of service?
A common use case will be when an app is tracking a userโs location. So with the help of the Headless.js and foreground service, you can keep track of the userโs location even he has killed his app from the recent tasks, of course, if permission is given.
How to Configure a foreground service within your app?
Do these steps carefully. ๐
1. You will need to add the permission in your manifest files to keep your app running in the background service
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
2. Now we need to define the name of the service, its description, and the color it is going to use, as well as we need to define the service and the headless task here
So before the closing tag of applications, append this. ๐
<meta-data android:name="com.supersami.foregroundservice.notification_channel_name" android:value="SuperService"/>
<meta-data android:name="com.supersami.foregroundservice.notification_channel_description" android:value="SuperService is running"/>
<meta-data android:name="com.supersami.foregroundservice.notification_color" android:resource="@color/orange"/>
<service android:name="com.supersami.foregroundservice.ForegroundService"></service>
<service android:name="com.supersami.foregroundservice.ForegroundServiceTask"></service>
3. In the above snippet, we define the color; we need to add the color orange manually in the resources.
So, Go to your android โ> app โ> src โ> main โres looks for the values-color.xml, If not exist Create one and then add this ๐, otherwise, add the orange color and integer array.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="orange" type="color">#FF4500
</item>
<integer-array name="androidcolors">
<item>@color/orange</item>
</integer-array>
</resources>
4. Step 4 includes receiving interaction of the notification on your JS Task.
Navigate to main Activity and declare a variable ๐
public boolean isOnNewIntent = false;
So to receive the interaction, you will need to override two of the methods, because the interaction will send pending intent data to the main activity, we will be receiving the interaction here, but we should be receiving it on our js thread instead, so to send the desired info, we override the methods.
Make sure to declare them one after another in order, like OnNewIntent first then below it OnStart. It is important. Otherwise, the interaction will be going to get overwritten by the onstart method.
First On New Intent:
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
isOnNewIntent = true;
ForegroundEmitter();
}
And then on OnStart:
@Override
protected void onStart() {
super.onStart();
if(isOnNewIntent == true){}else {
ForegroundEmitter();
}
}
Furthermore, in the last, we declare the function
This function basically being called by onNewIntent and onStart Method and forward info that it receives from the intent
public void ForegroundEmitter(){
// this method is to send back data from java to javascript so one can easily
// know which button from notification or the notification button is clicked
String main = getIntent().getStringExtra("mainOnPress");
String btn = getIntent().getStringExtra("buttonOnPress");
WritableMap map = Arguments.createMap();
if (main != null) {
map.putString("main", main);
}
if (btn != null) {
map.putString("button", btn);
}
try {
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("notificationClickHandle", map);
} catch (Exception e) {
Log.e("SuperLog", "Caught Exception: " + e.getMessage());
}
}
5. And the last step is to Register a headless Task
import ReactNativeForegroundService from '@supersami/rn-foreground-service';
ReactNativeForegroundService.register();
AppRegistry.registerComponent(appName, () => App);
Usage
To run a headless task, you need to declare a task; first, the task can be as many as you want. And then you need to start the foreground service.
Add a Task
A Task can be any JavaScript function that is not UI thread related because the background thread and UI thread are two different Javascript threads.
ReactNativeForegroundService.add_task(
() => console.log('I am Being Tested'),
{
delay: 100,
onLoop: true,
taskId: 'taskid',
onError: (e) => console.log(`Error logging:`, e),
},
)
Update a Task
You can update your existing task by passing a task
ReactNativeForegroundService.update(
() => console.log('I am Being Updated'),
{
delay: 100,
onLoop: true,
taskId: 'taskid', // this must be same
onError: (e) => console.log(`Error logging:`, e),
},
)
Remove Task
Remove task by providing taskid
remove_task('taskid')
Start Foreground Notification
Start an unremovable notification because of which you can run a background task.
ReactNativeForegroundService.start({
id: 144,
title: 'Foreground Service',
message: 'you are online!',
});
Update Foreground Notification
Updating the notification without removing it.
ReactNativeForegroundService.update({
id: 144,
title: 'Foreground Service',
message: 'you are online!',
});
Stop Foreground Service
Stoping the foreground service.
ReactNativeForegroundService.stop();
- Here is an example of a ๐ foreground service.
- ๐Github โ Foreground Service
- ๐NPM โ Foreground Service
You can always hire me to set it up for you via my Fiverr from the link https://www.fiverr.com/s2/05571a47b9
[Youtube Video] : https://www.youtube.com/embed/9wVpWr1ChVo

Raja Osama
I Describe Myself as a Polyglot ~ Tech Agnostic ~ Rockstar Software Engineer. I Specialise in Javascript-based tech stack to create fascinating applications.
I am also open for freelance work, and in-case you want to hire me, you can contact me at rajaosama.me@gmail.com or contact@rajaosama.me