Android: How to release resources when the application terminates?

android, resources

Solution

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

Problem

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?

Original source