I created an application which uses camera and during the appplication execution the screen is always on.
In the onCreate() method I added the lock:
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();
And this is the overriden onStop() method:
@Override
protected void onStop() {
if(mWakeLock.isHeld())
{
mWakeLock.release();
}
super.onStop();
}
But after the application termination the screen remains on all the time and if I run the camera application it encounters an error which obviously appears because the camera resources are not released.
Does anyone know how to release all resources on application termination?
I would move the lock from OnCreate()
to OnResume()
. You want the lock during the visible lifetime of the Activity, not the entire lifetime of the Activity. You Activity could definetly still be running with another Activity running in front of it.
I would move the release to OnPause()
. OnPause()
is the earliest point your application should normally be killed by the OS.
Additionally, I wouldn't check to see if I have the lock before releasing. If you use OnResume()
to acquire the lock; isHeld
should always be true in OnPause()
.
It sounds as though your application is never calling release on the Wakelock
- is it possible that it's throwing an exception earlier in onStop
or onPause
? I'd include some logging where you're calling release to confirm it's being executed.
In any case, you'll definitely want to move the acquire
and release
methods into onResume
and onPause
respectively. The code you've got will only acquire the WakeLock the first time your application is started.
Thanks the Android's background processing your code has a potential imbalance. If the user presses the home key to switch applications the lock will be released. If they switch back to your app onCreate won't be called, so the lock will never be acquired.
Your best bet is to construct the WakeLock in onCreate (as you have), acquire the lock in onResume and release it in onPause (including the call to isHeld). This will guarantee that the lock will be held whenever your application is in the foreground.
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