i’m trying to implement headless js in my react-native mobile application.
I have followed the official headless js docs.
In the [myAppName]androidappsrcmainjavacomanonymous[myAppName] i have defined MyTaskService.kt file as follows:
package com.anonymous.myAppName
import android.content.Intent
import com.facebook.react.HeadlessJsTaskService
import com.facebook.react.bridge.Arguments
import com.facebook.react.jstasks.HeadlessJsTaskConfig
class MyTaskService : HeadlessJsTaskService() {
override fun getTaskConfig(intent: Intent): HeadlessJsTaskConfig? {
return intent.extras?.let {
HeadlessJsTaskConfig(
"BackgroundFunctions",
Arguments.fromBundle(it),
5000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground.
// Default is false
)
}
}
}
Then, i have defined a BackgroundFunctions.js file in a different folder that contains the task that the app must perform in background:
module.exports = async (taskData) => {
// do stuff
console.log('Hello World!');
};
In the App.js file i have added the following lines of code:
import BackgroundFunctions from './scripts/background/BackgroundFunctions';
// *** app
import MainApp from './pages/Main/App';
AppRegistry.registerHeadlessTask('BackgroundFunctions',() => BackgroundFunctions);
export default function App() {
return <MainApp />
}
I have also added the service in my AndroidManifest.xml file (androidappsrcmainAndroidManifest.xml) as following:
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="true" android:theme="@style/AppTheme">
<service android:name="com.anonymous.myApp.MyTaskService" android:enabled="true" android:label="MyTaskService" />
</application>
I have the following issue:
when application starts after the build i’m expecting that the BackgroundFunctions task that i have defined starts immediately and prints on the terminal the console.log(‘Hello World!) inside the function.
I’m expecting that my code runs in foreground and background.
Are there any errors in my code?
Thanks in advance!
Jacopo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.