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?
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')
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With