Development

How to use React Native Foreground Service v2@


Forground service that you can use to create an always on Background task in React Native. Foreground service is a kind of service in Android that has a notification that can not be removed until the foreground service is closed, and because of this, you can run a background task with the help of headless JS.

with th latest update of the v2 of React native foreground service, things are more easier and convinet now, React native foreground service now let you easily install and linked RN foreground service with your application with just 2 steps installation.

The purpose of this article is to show you how you can easily work Install foreground Service in your application and use it as per your requirement.

If you rather watch a video, below is the link for RN installation process and how you can easily install it and link it.

https://www.youtube.com/watch?v=t5LQdbvjufM

Check it out 👆

To Install the Library and attach it to your project, you can easily install with in 2 to 3 steps. Lets get to it.

Step 1

Installing the library with

npm i @supersami/rn-foreground-service

or

yarn add @supersami/rn-foreground-service

Step 2

Just run this command once and see the magic.

node node_modules/@supersami/rn-foreground-service/postinstall.js

In anycase, the above don't link your application correctly, you can try on manual linking of the application at Installation Documentation

Step 3

In your root, Index.js file. Paste the following code.

import ReactNativeForegroundService from "@supersami/rn-foreground-service";
ReactNativeForegroundService.register();

The above code will register a initial headless task, which will be a first layer, over which, you can add as many task as you desire and they all will execute seamlessly.

Create a task and add it the execution queue. anywhere in your application, you can create a task like this.

ReactNativeForegroundService.add_task(() => update(), {
  delay: 1000,
  onLoop: true,
  taskId: "taskid",
  onError: (e) => console.log(`Error logging:`, e),
});

Creating a foreground service, so that your headless task stays active.

ReactNativeForegroundService.start({
  id: 1244,
  title: "Foreground Service",
  message: "We are live World",
  icon: "ic_launcher",
  button: true,
  button2: true,
  buttonText: "Button",
  button2Text: "Anther Button",
  buttonOnPress: "cray",
  setOnlyAlertOnce: true,
  color: "#000000",
  progress: {
    max: 100,
    curr: 50,
  },
});
Author Image

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