代码之家  ›  专栏  ›  技术社区  ›  Trevor

阻止Cordova Android在后台运行

  •  1
  • Trevor  · 技术社区  · 6 年前

    当Cordova应用程序移到后台时,是否有方法停止或暂停它?

    使用简单的测试代码

    var app = {
        // Application Constructor
        initialize: function() {
            document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        },
    
        // deviceready Event Handler
        //
        // Bind any cordova events here. Common events are:
        // 'pause', 'resume', etc.
        onDeviceReady: function() {
            this.receivedEvent('deviceready');
        },
    
        // Update DOM on a Received Event
        receivedEvent: function(id) {
            var parentElement = document.getElementById(id);
            var listeningElement = parentElement.querySelector('.listening');
            var receivedElement = parentElement.querySelector('.received');
    
            listeningElement.setAttribute('style', 'display:none;');
            receivedElement.setAttribute('style', 'display:block;');
    
            console.log('Received Event: ' + id);
            setInterval(function(){
                console.log("Stilling running at",new Date());
            },1);
        }
    };
    
    app.initialize();
    

    应用程序在手机上最小化后,间隔将继续运行。有没有什么方法可以像在旧版本的Android中那样暂停应用程序?

    这是一个使用pouchdb的大得多的应用程序的过度简化的例子,但在应用程序最小化或屏幕关闭后,javascript仍在继续运行时也存在同样的问题。

    1 回复  |  直到 6 年前
        1
  •  1
  •   BShaps    6 年前

    这取决于你所说的“暂停应用程序”。应用程序由手机的操作系统管理,其行为因设备和操作系统版本而异。你所能做的就是在应用程序被发送到后台和/或恢复到前台时运行代码。为此,您可以使用Cordova生成的暂停和恢复事件。

    您可以在此处找到活动文档: Cordova Events

    在应用程序发送到后台时运行代码

    document.addEventListener("pause", onPause, false);
    
    function onPause() {
      // Stop any intervals here along with any other code to "pause" the app
    }
    

    将应用程序还原到前台时运行代码

    document.addEventListener("resume", onResume, false);
    
    function onResume() {
      // Start up any intervals you want along with any other code to restore the app
    }