I need implement Headless JS in my React Native Android Application, but I got following issue :
Here is My Code :
index.android.js :
import React, { Component } from 'react';
import {AppRegistry} from 'react-native';
import SomeTaskName from './SomeTaskName'
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
SomeTaskName.js
module.exports = async (taskData) => {
alert('test');
}
MyTaskService.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 MyTaskService extends HeadlessJsTaskService {
@Override
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"MyTaskService",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
and add service in AndroidManifest.xml
<service android:name=".MyTaskService" android:enabled="true" android:label="MyTaskService" />
Please , Anyone help to fix this issue.
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
Supports Cross-Platform Application Development: By using React JS, you can make applications for a variety of platforms, including iOS and Android platforms. Therefore, you no longer have to learn different languages, like C++ and Java.
You can use the setInterval and setTimeout functions. This API is identical to that of react-native and can be used to quickly replace existing timers with background timers.
React Native background service library for running background tasks forever in Android & iOS. Schedule a background job that will run your JavaScript when your app is in the background or foreground.
You have to register a headless task. So replace the following code:
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
with:
AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTaskName);
And you need to call the task from your service, so replace:
if (extras != null) {
return new HeadlessJsTaskConfig(
"MyTaskService",
Arguments.fromBundle(extras),
5000);
}
return null;
with:
// Following line just to be sure it does not silently fail
WritableMap data = extras != null ? Arguments.fromBundle(extras) : null;
return new HeadlessJsTaskConfig(
"SomeTaskName", // Use the registered headless Task here
data,
5000);
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