Reputation: 2788
I have a Phonegap Android app that scans RFID chips. Apparently scanning RFID does not count as a user action, because the device will go to sleep after the interval set in Android Settings (which is a maximum of 10 minutes).
So despite constant scanning, my device will go to sleep. So I need a way to tell the OS that I'm active, programtically after each RFID scan.
Currently, I am doing something that I don't want, which is using
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to prevent sleep while the app is running, but I'd like to still be able to use the sleep interval if the device is actually inactive.
I had high hopes for using powerManager.userActivity(l, false)
but apparently this is only available for System apps, so I cannot set permission for it.
Any ideas how to keep the device active while not doing any touch screen interaction?
Upvotes: 1
Views: 5976
Reputation: 2788
A WakeLock is the answer, but the key is to use ON_AFTER_RELEASE
. With this flag, the user activity timer will be reset when the WakeLock is released.
So for the NFC plugin, under the onPause method I added:
MyMainActivity ma = (MyMainActivity) cordova.getActivity();
wl = ((PowerManager) ma.getSystemService(Context.POWER_SERVICE))
.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "wakeywakey");
wl.acquire();
And under the onResume method I added:
wl.release();
With this arrangement, when an RFID chip is scanned, the NFC plugin will create the WakeLock and then release it, which will reset the activity timer. Also, I used SCREEN_BRIGHT_WAKE_LOCK
even though it is deprecated, as this will brighten the screen if it has gone dim.
Upvotes: 0
Reputation: 3297
You can use this cordova plugin
To prevent sleeping you call:
window.plugins.insomnia.keepAwake();
and to allow sleeping again:
window.plugins.insomnia.allowSleepAgain();
Upvotes: 3
Reputation: 57309
You will need to play with JAVA a bit.
Add this code to your activity class:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
Here you will find more info.
Also dont forget to relese WakeLock at the end:
wl.release();
You also need to be sure you have the WAKE_LOCK permission set in your Manifest.
Upvotes: 0