views:

1308

answers:

1

Hello

I have an Android (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.

Thanks

+3  A: 

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.

Josef
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?
Tom
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.
CommonsWare
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(); }}
Tom
Oh man... Services are way more complicated than that. Check out the guide: http://developer.android.com/guide/developing/tools/aidl.html
fiXedd