How to keep an Activity running while screen off?

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


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.


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/

Tags:

Android