A
A
AlexBelan2021-08-13 02:39:17
Java
AlexBelan, 2021-08-13 02:39:17

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);


SomeTaskName.js:
module.exports = async (taskData) => {
    console.log('Beackgroud task')
    alert('test');
}


MyTaskService.java:
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;
  }
}


AndroidManifest.xml:
<service android:name="com.exaple.MyTaskService" />


MainActivity.java:
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();
    }


I did everything as in the documentation, but nothing works, what could be the matter?
Or at least tell me a library that will help implement this, I need the application to work in a closed state.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question