Preventing application/screen timeout Android
Asked Answered
C

2

6

I have an Android (version 1.5) application which needs to be constantly running when a button is pressed. So, when a Button is pressed I would like the phone to remain on and not want the screen or CPU to time-out.

When another Button is pressed I would like the phone to be back to normal and time-out as per user settings.

Changeless answered 13/6, 2009 at 19:51 Comment(1)
possible duplicate of Force Screen OnLox
L
3

Update: As suggested by Steve Pomeroy, this might be a better way to do it.


You can use a WakeLock that requires the following permission:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Here is how you aquire and release a WakeLock:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
// wake locked...
wl.release();

Depending on your requirements you might be able to use a different type of WakeLock.

Ludvig answered 13/6, 2009 at 20:15 Comment(6)
I did think of that solution however I can only release the wake lock where it was locally created, not in the "Off" button which is where it needs to be released. Ideas?Changeless
Create a service. In the service's onCreate(), grab the WakeLock, held in a private data member. In the service's onDestroy(), release the WakeLock. In the activity, when you need the screen/CPU to stay on, call startService(). Sometime later, when you no longer need the screen/CPU to stay on, call stopService(). Now, the WakeLock will be held so long as the service is running, no matter what happens to your activity. Moreover, the service could also watch for battery events, to perhaps release the WakeLock anyway once battery life gets low.Digestant
I keep getting "wl can not be resolved" on the .release method: public class WakeLockService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } public void onCreate() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag"); wl.acquire(); } public void onDestroy() { wl.release(); } }Changeless
Oh man... Services are way more complicated than that. Check out the guide: developer.android.com/guide/developing/tools/aidl.htmlClevey
See my note below. Wakelocks can be dangerous and should only be used when really needed.Baffle
I think here you do need the wake lock though, as it's to be controlled when pressing a button within an Activity, rather than for an entire Activity's (foreground) lifespan.Marmalade
B
2

Instead of using a wakelock, you should consider the solution proposed here: Force Screen On

It is much easier to use and doesn't have the potential of accidentally wasting the user's batteries.

Baffle answered 16/12, 2010 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.