Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep an Activity running while screen off?

Tags:

android

How to keep an Activity running/active when the screen shuts off?

like image 725
babysnow Avatar asked Aug 15 '12 23:08

babysnow


3 Answers

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.

like image 94
Patrick Meng Avatar answered Oct 29 '22 21:10

Patrick Meng


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

like image 32
Anirudh Ramanathan Avatar answered Oct 29 '22 19:10

Anirudh Ramanathan


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/

like image 26
Tom-Oliver Heidel Avatar answered Oct 29 '22 19:10

Tom-Oliver Heidel