React-native background process(android) handling?

本小妞迷上赌 提交于 2019-12-12 02:08:07

问题


How to console.log() something periodically in the background process or when the app is terminated on android platform?


回答1:


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




回答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



来源:https://stackoverflow.com/questions/36691215/react-native-background-processandroid-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!