I am trying to do the background action in react native. I already tested a lot of libraries and none is working.
Now I am trying to do background task using the Headless JS.
I am using React-Native-CLI
import React from 'react';
import {AppRegistry, Button} from 'react-native';
import { View } from 'react-native';
const bgTask = () => {
console.log('Working in background!')
}
const regBG = () => {
console.log('Pressed')
AppRegistry.registerHeadlessTask('Task', () => bgTask());
}
function App(){
return (
<View>
<Button title="Press" onPress={() => regBG()} />
</View>
);
}
export default App;
After the push on 'Press' button console showing the log message 'Pressed' and it's all.
Handless JS, React Native Background Task, React Native Background Action.
It seems like you are just registering the event, not calling it. You need some additional setup on the native side, which is where you will define the task
that will be called (which you registered as Task
, as well as the timeout
before it to be called. (Here are the docs).
Also, I would try exporting the method you want to call from another module, instead of calling a function from the same component you're registering the action in. (Check this example from the documentation).
Third, I'm not sure you will see that event log in the terminal, depending on how long the app's been in foreground
. In case you don't see that log after the additional setup mentioned in the documentation, try an API call
to a local server instead of a console.log
, so you can check from the server
log wether it's been called or not.
Last but not least, remember that this method is for Android only
, and there are other ways for doing this on iOS
, so make sure you're testing from an Android device/simulator.