Search code examples
androidexceptionandroid-lifecycle

Executing method when app is killed on Android


I have built an Android application. If I terminate my application regularly trough the back button then onDestroy() is executed. But when I kill my application (using the recent apps button), onDestroy() is never executed. I have now added in the onCreate(Bundle savedInstanceState) method of my main Activity the following:

    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException (Thread thread, Throwable e)
        {
            handleUncaughtException (thread, e);
        }
    });

Later in the main Activity class I have added:

private boolean isUIThread(){
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

public void handleUncaughtException(Thread thread, Throwable e) {
    if(isUIThread()) {
        // exception occurred from UI thread

    } else {  //handle non UI thread throw uncaught exception
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                //handle non UI thread throw uncaught exception

            }
        });
    }
}

Unfortunately, the handleUncaughtException() method gets never called when I kill my application (it also gets not called when I regularly terminate my application through the back button).

What is wrong?

I'm using Android 5.1.


Solution

  • Unfortunately the handleUncaughtException() method gets never called when I kill my application (it also gets not called when I regularly terminate my application through the back button).

    Catching an exception (within dalvik) and killing an app (Linux) process are different things per se. The handleUncaughtException() method won't be called in this case, unless the app throws an uncaught exception.

    Executing method when app is killed on Android

    When removing an app from recents only Activity's onPause() is guaranteed to be called. But you might be "informed" by the Service's callbacks. Some extra info can be found here or here.