How to console.log() something periodically in the background process or when the app is terminated on android platform?
Asked
Active
Viewed 1,035 times
2 Answers
2
you need to create custom Java module which will run in the background. For example:
@ReactMethod
public void startTimeTasks(Integer delay1, Integer delay2) {
if (timer != null) {
timer.cancel();
timer.purge();
}
timer = new Timer();
timer.schedule(new TimeTask(), delay1);
timer.schedule(new TimeTask(), delay2);
}
@ReactMethod
public void cancelTimeTasks() {
if (timer != null) {
timer.cancel();
}
}
@Override
public String getName() {
return "MyCustomModule";
}
class TimeTask extends TimerTask {
public void run() {
//do something
}
}
Then call in JS:
//run background task after 300000 and 240000 milliseconds
NativeModules.MyCustomModule.startTimeTasks(300000, 240000);
//stop this background task
NativeModules.MyCustomModule.cancelTimeTasks();
it is my case but based on it can do anything

Дмитрий
- 21
- 4
-2
You can use setInterval in JS to run something periodically.
//run our function every 1000 MS
setInterval(() => {console.log('something'); }, 1000);
But there's not really a concept of "background" in JS. I'm not sure if you can hook into the applications lifecycle events from JS, you certainly can in Native code though. https://facebook.github.io/react-native/docs/embedded-app-android.html

rooftop
- 3,031
- 1
- 22
- 33