Answer the question
In order to leave comments, you need to log in
How to run Headless JS on react native?
Hello everyone, I need to run background tasks on React native on Android smartphones, I decided to try to implement it on Headless JS, before that I tried the react-native-background-task library, but somehow it didn’t work out.
Now I'm working with Headless JS, but it doesn't work either, here's a sample code.
index.js:
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import SomeTaskName from './SomeTaskName'
AppRegistry.registerHeadlessTask("SomeTaskName", () =>
SomeTaskName
);
AppRegistry.registerComponent(appName, () => App);
module.exports = async (taskData) => {
console.log('Beackgroud task')
alert('test');
}
package com.exaple;
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;
import javax.annotation.Nullable;
public class MyTaskService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"SomeTaskName",
Arguments.fromBundle(extras),
5000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
return null;
}
}
<service android:name="com.exaple.MyTaskService" />
package com.exaple;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity2.class);
Intent service = new Intent(getApplicationContext(), MyTaskService.class);
getApplicationContext().startService(service);
startActivity(intent);
finish();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question