【问题标题】:React-native background process(android) handling?反应原生后台进程(android)处理?
【发布时间】:2016-04-18 10:20:52
【问题描述】:

如何在后台进程或应用程序在android平台上终止时定期console.log()?

【问题讨论】:

    标签: android react-native background-process


    【解决方案1】:

    您需要创建将在后台运行的自定义 Java 模块。例如:

    @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
        }
    }
    

    然后在JS中调用:

    //run background task after 300000 and 240000 milliseconds
    NativeModules.MyCustomModule.startTimeTasks(300000, 240000);
    //stop this background task
    NativeModules.MyCustomModule.cancelTimeTasks();
    

    这是我的情况,但基于它可以做任何事情

    【讨论】:

      【解决方案2】:

      你可以在 JS 中使用 setInterval 来定期运行一些东西。

      //run our function every 1000 MS    
      setInterval(() => {console.log('something'); }, 1000);
      

      但是 JS 中并没有真正的“背景”概念。我不确定您是否可以从 JS 挂钩到应用程序生命周期事件,但您当然可以在本机代码中。 https://facebook.github.io/react-native/docs/embedded-app-android.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        • 2020-05-13
        • 2018-03-21
        • 2020-01-22
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        相关资源
        最近更新 更多