PhoneGap: Prevent an Android Device's Screen from Sleeping
I'm currently developing an Android application via PhoneGap. It took me two entire workdays to learn how to prevent this application's screen from dimming or sleeping (after 5 minutes of inactivity), so I want to document what I learned here for the sake of others who need to solve the same problem.
First, let's discuss a few strategies that will not work. Keep in mind that I'm working specifically in the PhoneGap environment (around the time of Cordova version 2), and that "Your Mileage May Vary" if you're working outside of PhoneGap.
What Did Not Work
I thought there might be a way to change this behavior in
that seems not to be the case. It seems that this functionality is planned for
a later release, however.
Some sources said that adding
AndroidManifest.xml would solve this problem. Simply put, it didn't work for
Using the PowerManagement PhoneGap plugin
This plugin seems to have been designed to do exactly what we want - however, it just doesn't work anymore. The problem seems to be that it was broken by changes in Cordova sometime beyond the 1.6 version, so if you're working with a version newer than that, don't waste your time.
Trying to simulate user interactions with jQuery Mobile
Out of desperation, I tried something cute: I created a link within my
href was simply
timer that would invoke a jQuery
.click() event on that link every 30
What Did Work
Ultimately, this answer on Stack Overflow pointed me in the right direction. In the case of PhoneGap, however (at least as of the time of this writing), it was missing an important detail: You must import some extra dependencies at the beginning of your application's main Java file:
import android.view.WindowManager; import android.view.Window;
(When I say your "application's main Java file", I mean the file that lives
approot/src/. For me, it was
As an example in-context, the following file worked for me:
I hope this saves you some time.