Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native and Android Background Services

I am using Headless.js for running background services with React Native. We are facing quite a few issues with its usage. What are my options for running Android background services using React Native?

like image 571
Gunner Avatar asked Nov 24 '16 08:11

Gunner


Video Answer


2 Answers

add file name BackgroundAudio.java

import android.content.Intent;
import android.os.Bundle;

import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;

public class BackgroundAudio extends HeadlessJsTaskService {

    @Override
    protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            return new HeadlessJsTaskConfig(
                    "BackgroundAudio",
                    Arguments.fromBundle(extras),
                    5000);
        }
        return null;
    }
}

edit AndroidManifest.xml

<service android:name=".BackgroundAudio" android:enabled="true" android:label="BackgroundAudio" />

Then in my index.android.js :

import BackgroundAudio from './src/BackgroundAudio'
AppRegistry.registerHeadlessTask('BackgroundAudio', () => BackgroundAudio)

And lastly, BackgroundAudio.js file referenced in the index.android.js reads as such:

export async function BackgroundAudio (taskData) { 
    alert('BACKGROUND AUDIO')
}
like image 105
shodiqul muzaki Avatar answered Nov 07 '22 18:11

shodiqul muzaki


There's a couple of packages that have been created since you asked this question that could be helpful depending on your exact use case.

Specifically you can use react native queue with react native background task to easily schedule a background task to execute periodically (roughly every ~15 min your scheduled task will run for at most 30 seconds - use the queue to handle task timeout management) when your app is closed (this works cross platform for iOS and Android). However, if your intention is to have a service that is running constantly in the background, I'm not certain that is possible in the RN world (so far as the time of my post is concerned).

like image 28
billmalarky Avatar answered Nov 07 '22 17:11

billmalarky