How to keep an Activity running/active when the screen shuts off?
In the onCreate of your Activity, put the following lines:
Context mContext = getApplicationContext();
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PARTIAL_WAKE_LOCK,"motionDetection:keepAwake");
wakeLock.acquire();
//Place this where you no longer need to have the processor running
wakeLock.release();
After you press the power button, the activity should still run if that's where you closed it.
If you were like me, and you were collecting accelerometer data, be sure to remove the default sensorManager.unregisterListener(this);
from the onPause part of the app.
You will need to use a PARTIAL_WAKE_LOCK to ensure that your activity is kept active. android.permission.WAKE_LOCK
must be requested in your manifest. However, battery will drain faster, so do remember to release the wakelock as soon as possible.
Alternately, use a Service instead
There is also a good way. I found this some months ago and it save a little bit the battery life ;)
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With