Search code examples
androidreact-nativenode-modules

React Native Background Actions Not Starting


I am trying to use the react native background actions library for my app.

I have read the documentation and tried to implement it but it is not working.

clicking the start background job button does nothing, no notification and the line console.log("in intensive task"); never gets logged. What am I doing wrong?

import { Button } from '@react-native-material/core';
import { View } from 'react-native';
import BackgroundService from 'react-native-background-actions';

const sleep = (time:number) => new Promise<void>((resolve) => setTimeout(() => resolve(), time));

const veryIntensiveTask = async (taskDataArguments:any) => {
    console.log("in intensive task");
    const { delay } = taskDataArguments;
    await new Promise( async (resolve) => {
        for (let i = 0; BackgroundService.isRunning(); i++) {
            console.log(i);
            await sleep(delay);
        }
    });
};

const options = {
    taskName: 'Example',
    taskTitle: 'ExampleTask title',
    taskDesc: 'ExampleTask description',
    taskIcon: {
        name: 'ic_launcher',
        type: 'mipmap',
    },
    color: '#ff00ff',
    parameters: {
        delay: 1000,
    },
};

export default function Background(){
const startBackgoundJob=async ()=>{
    await BackgroundService.start(veryIntensiveTask, options);
    console.log("background service started");
};
const updateBackgroundJob=async ()=>{
    await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); 
    console.log("background service updated");
};
const stopBackgroundJob=async ()=>{
    await BackgroundService.stop();
    console.log("background service stopped");
};
return(
    <View style={{flex:1,display:"flex",justifyContent:"center",alignItems:"center"}}>
        <Button title="start background job" onPress={startBackgoundJob}/>
        <Button title="update background job" onPress={updateBackgroundJob}/>
        <Button title="stop background job" onPress={stopBackgroundJob}/>
    </View>
)
}

I have tried running this in the emulator with Android SDKs versions 30 and 33, and on physical device running SDK 33.
I have also made sure that the AndroidManifest.xml file contains

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

Thanks!


Solution

  • Adding

    <service android:name="com.asterinet.react.bgactions.RNBackgroundActionsTask" />
    

    to your AndroidManifest.xml file fixes the problem as suggested in the solution by Julius Cebreros