Baz Baz - 3 years ago 121
Javascript Question

Stop my app from sleeping (Cordova/Android)

I have an Android App which I create from a node.js webpack project.

When I install my app on my phone I notice that it sleeps when the phone sleeps. So for example, I have a javascript timer which stops getting called:


for the pingInterval. How do I stop my app from sleeping? Eventually, I will want my app to go to sleep but for now stopping the phone from sleeping is my best option.


I followed the instructions as described here:

but with no luck.

Answer Source

The best option for you to use is the WakeLock api

Add the permission in the manifest file for the wakeLock

<uses-permission android:name="android.permission.WAKE_LOCK" />

then you can add the following according to your modifications like as suggested in the MDN behaviour

function forPingTimer(){
 var lock =  window.navigator.requestWakeLock('screen');
 //set timeout or until the timer expires

and release the lock using the lock.unlock(); function.


For the cordova app you can also use the plugin insomniaThe changes to be made in the config file are as mentioned in the docs and it can be simply used in the following way as

function forPingTimer(){
//as long as the app runs or set the timeout here or wrap it in a promise
//Simply calling window.plugins.insomnia.keepAwake() to keep awake
//window.plugins.insomnia.allowSleepAgain() to sleep again until the timer after the timer is fulfilled
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download