Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a wakelock is acquired and my app crashes, what should I do?

My application has a background service running at all times when a flag is set to true. If this is the case, even if app is down this background service still needs CPU time. If I acquire wakelock (not for "screen on" purposes but for this background service) and then application crashes or user FC it, then I am not able to release this wakelock.

What is the expected result?

Does Android know about this and releases the wakelock?

In what way should I manage this situation?

like image 497
cesarmax Avatar asked Aug 21 '12 15:08

cesarmax


1 Answers

This sort of issue can happen with other aspects of Android as well. As an example that I've personally encountered, if you don't ever release a camera object and your app crashes, the camera will be unavailable until the user reboots. You can handle these types of situation like so:

// Store the default uncaughtexceptionhandler in a variable.
private Thread.UncaughtExceptionHandler previousHandler = Thread.currentThread().getUncaughtExceptionHandler(originalExceptionHandler);


@Override
public void onCreate(Bundle bundle){
    Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            try{ 
               // release your wakelock here.
            }
            catch(Exception e){ 
               // log 
            }
            finally{
               thread.setUncaughtExceptionHandler(previousHandler);
               previousHandler.uncaughtException(thread, ex);
               thread.setUncaughtExceptionHandler(previousHandler);
            };
        }

    }); 
}

What you're doing here is overriding the normal crash behavior when an exception is encountered and giving yourself time to free up any problematic spots that really need to be cleaned up before the app fully crashes and you have no hope to recover.

like image 116
scriptocalypse Avatar answered Oct 13 '22 12:10

scriptocalypse