Ionic prevent phone sleeping only when app is running

4.4k views Asked by At

The Insomnia plugin promises to keep devices awake with window.plugins.insomnia.keepAwake(), until such time as window.plugins.insomnia.allowSleepAgain() is called.

But for some apps it only makes sense for the device to stay awake while the app is active. If the user pauses the app and forgets they have left it going in the background, it would be nice to allow sleep rather than decimate their battery level.

Typically actions required on app pause are handled through the pause event:

function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
}

function onPause() {
    window.plugins.insomnia.allowSleepAgain();
}

But according to Cordova docs, the Pause handler on iOS can't call anything native - which would include the Insomnia plugin.

How to achieve the desired functionality?

2

There are 2 answers

0
Paulw11 On

Looking at the source of that plugin, on iOS it calls setIdleTimerDisabled:true on the UIApplication instance. isIdleTimerDisabled is

A Boolean value that controls whether the idle timer is disabled for the app.

It doesn't disable the idle timer for the device as a whole, so if the user suspends your app then the idle timer will be enabled again.

0
Sebastien Horin On

You can use allowSleepAgain() with a $timeout and reinit the delay everytime you do something with keepAwakeforMinutes().

var keepAwakeforMinutes = function(minutes){
    // when an action is done,
    // cancel the last allowSleepAgain() $timeout if exists to create a new longer one
    if ($rootScope.sleeping){
        // alert("cancel previous timeout");
        $timeout.cancel( $rootScope.sleeping );
    }

    // be awake for the next minutes by creating a new timeout
    $window.plugins.insomnia.keepAwake();
    $rootScope.sleeping = $timeout(function() {
        // timeout ended
        $window.plugins.insomnia.allowSleepAgain();
    }, 60000*minutes); // awake for the next minutes
}