Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to release resources when the application terminates?

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?

like image 316
Niko Gamulin Avatar asked Jul 01 '09 09:07

Niko Gamulin


2 Answers

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().

like image 149
Will Avatar answered Sep 23 '22 07:09

Will


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.

like image 28
Reto Meier Avatar answered Sep 23 '22 07:09

Reto Meier