1.0.18 • Published 2 years ago

react-native-foreground-service-android v1.0.18

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

react-native-foreground-service-android

A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a notification. Foreground services continue running even when the user isn't interacting with the app.

See the Android official documentation for details on the concept.

This app is a library created by forking @voximplant/react-native-foreground-service.

Getting started

$ npm install react-native-foreground-service-android --save

OR

$ yarn add react-native-foreground-service-android

Automatic installation (Android only)

  • React Native 0.60+

    CLI autolink feature links the module while building the app.

    1. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:
      <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    2. Add LTForegroundService as a service to the application's AndroidManifest.xml:
      <service android:name="com.leetaehong.foregroundservice.LTForegroundService"
      android:exported="true" <- If you want it to be maintained even after the app is turned off, default : "false"
      />

android:exported

  • Indicates whether components of other applications can call or interact with the service. If a call or interaction is possible, it is "true", otherwise "false". If this value is "false", only applications with the same application component or the same user ID can start or bind to the service. The default value depends on whether the service contains an intent filter. If there is no filter, the service can be called only when the exact class name is specified. This suggests that the service is designed only for internal application purposes (because others do not know the class name). Therefore, in this case, the default value is "false", whereas if there is more than one filter, it implies that the service is designed for external purposes, so the default value is "true". In addition to this characteristic, there is a way to limit services from being exposed to other applications. You can also use permission to restrict external entities that can interact with the service (see permission attributes).

  • React Native <= 0.59

    $ react-native link @leetaehong/react-native-foreground-service

    1. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:
      <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    2. Add LTForegroundService as a service to the application's AndroidManifest.xml:
      <service android:name="com.leetaehong.foregroundservice.LTForegroundService"> </service>
    3. If you want to use the background service, you add LTForegroundTask as a service to the application's AndroidManifest.xml:
      <service android:name="com.leetaehong.foregroundservice.LTForegroundTask"/>

Manual installation (Android only, React Native <= 0.59)

  1. Open up android/app/src/main/java/[...]/MainActivity.java
    • Add import com.leetaehong.foregroundservice.LTForegroundServicePackage; to the imports at the top of the file
    • Add new LTForegroundServicePackage() to the list returned by the getPackages() method
  2. Append the following lines to android/settings.gradle:
    include ':@leetaehong_react-native-foreground-service'
    project(':@leetaehong_react-native-foreground-service').projectDir = new File(rootProject.projectDir, '../node_modules/@leetaehong/react-native-foreground-service/android')
  3. Insert the following lines inside the dependencies block in android/app/build.gradle:
    implementation project(':@leetaehong_react-native-foreground-service')
  4. Add the FOREGROUND_SERVICE permission to the application's AndroidManifest.xml:
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  5. Add LTForegroundService as a service to the application's AndroidManifest.xml:
    <service android:name="com.leetaehong.foregroundservice.LTForegroundService"> </service>
  6. If you want to use the background service, you add LTForegroundTask as a service to the application's AndroidManifest.xml:
    <service android:name="com.leetaehong.foregroundservice.LTForegroundTask"/>

Demo project

Demo application: none

Usage

Import module

import LTForegroundService, {
  IChannelConfig,
  INotificationConfig,
} from "react-native-foreground-service-android";

Create notification channel (Android 8+)

Since the foreground service must display a notification, for Android 8+ it is required to create a notification channel first:

const channelConfig: IChannelConfig = {
  id: "channelId",
  name: "Channel name",
  description: "Channel description",
  enableVibration: false,
};
LTForegroundService.createNotificationChannel(channelConfig);

Update foreground service

async startForegroundService() {
    const notificationConfig: INotificationConfig = {
        channelId: 'channelId', // you must same channelId and id
        id: 3456,
        title: 'Title',
        text: 'Some text',
        icon: 'ic_icon',
        ongoing: true // default false
    };
    try {
        await LTForegroundService.updateService(notificationConfig);
    } catch (e) {
        console.error(e);
    }
}

Start foreground service

async startForegroundService() {
    const notificationConfig = {
        channelId: 'channelId',
        id: 3456,
        title: 'Title',
        text: 'Some text',
        icon: 'ic_icon',
        ongoing: true // default false
    };
    try {
        await LTForegroundService.startService(notificationConfig);
    } catch (e) {
        console.error(e);
    }
}

Stop foreground service

LTForegroundService.stopService();

Start background foreground service

async backgroundStartService() {
    const backgroundConfig : IBackgroundConfig = {
        channelId: 'channelId',
        id: 3456,
        title: 'Title',
        text: 'Some text',
        icon: 'ic_icon',
        ongoing: true, // default false
        taskName: "BackgroundTask",
        delay: 1000
    };

    const exampleTask = async (taskDataArguments?: IBackgroundConfig) => {
        await new Promise(() => {
            while (ForegroundService.getIsBackgroundRunning()) {
                // you can do anything
                console.log("taskDataArguments")
            }
        });
    };

    try {
        await LTForegroundService.backgroundStartService(exampleTask,backgroundConfig);
    } catch (e) {
        console.error(e);
    }
}

Stop background foreground service

LTForegroundService.backgroundStopService();

Reference

Methods

static async startService(notificationConfig)

Starts the foreground service and displays a notification with the defined configuration


static async stopService()

Stops the foreground service


static async createNotificationChannel(channelConfig)

Creates a notification channel for the foreground service. For Android 8+ the notification channel should be created before starting the foreground service


static async updateService(notificationConfig)

It is used to update the foreground service.

  • NOTE : When using the update function, the channel ID must be the same.

static async backgroundStartService(backgroundConfig)

It is used when you want a notification to run a task in the background.

static async backgroundStopService()

This is used when you want to stop background task notifications.

Configs

NotificationChannelConfig;
Property nameDescriptionRequired
idUnique channel idyes
nameNotification channel nameyes
descriptionNotification channel descriptionno
importanceNotification channel importance. One of:1 – 'min' 2 – 'low' (by default)3 – 'default'4 – 'high'5 – 'max'no
enableVibrationSets whether notification posted to this channel should vibrate. False by default.no
NotificationConfig;
Property nameDescriptionRequired
channelIdNotification channel id to display the notificationyes (Android 8+ only)
idUnique notification idyes
titleNotification titleyes
textNotification textyes
iconIcon nameyes
priorityPriority of this notification. One of:  0 – PRIORITY_DEFAULT (by default)-1 – PRIORITY_LOW-2 – PRIORITY_MIN 1 – PRIORITY_HIGH 2 – PRIORITY_MAXno
ongoingTo keep the notification or prevent the user from erasing the notification even if the user shuts down the app,no
BackgroundConfig;
Property nameDescriptionRequired
channelIdNotification channel id to display the notificationyes (Android 8+ only)
idUnique notification idyes
titleNotification titleyes
textNotification textyes
iconIcon nameyes
priorityPriority of this notification. One of:  0 – PRIORITY_DEFAULT (by default)-1 – PRIORITY_LOW-2 – PRIORITY_MIN 1 – PRIORITY_HIGH 2 – PRIORITY_MAXno
ongoingTo keep the notification or prevent the user from erasing the notification even if the user shuts down the app,no
delaySet the time to run the task regularly.no
tasknamePlease enter the background task name.no