Safe exiting an Application from a ExceptionHandler subclass?

488 views Asked by At

I'm new to Android as well as java, i'll try my best to be as specific as possibe.

I have an app with one activity and several fragments and classes along with an ExceptionHandler subclass which implements default UncaughtExceptionHandler. I was able to successfully use :-

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

to exit an application in case of unhandled exceptions without displaying the "ForceClose" pop-up. I use System.exit(0) . I'm recording logs throughtout the application. I'm able to record the exception from ExceptionHandler subclass into the log.

Now, my issue is that the application exits without undergoing onPause(),onStop() or onDestroy() in case of an uncaught exception, but i need it to pass through all these lifecycles for my MainActivity.

How can i do this while exiting the application using the ExceptionHandler subclass?

1

There are 1 answers

0
N29 On BEST ANSWER

i finally got it, if the error is thrown in the first activity(MainActivity) which is launched then nothing can be done.

If it is thrown in anyother activity, then in the ExceptionHandler class we can pass the intent to start the MainActivity and then exit the app. gracefully :P

public class ExceptionHandler implements UncaughtExceptionHandler{

private Activity myContext;
public ExceptionHandler(Activity context) {
    this.myContext = context;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
    // TODO Auto-generated method stub
    StringWriter stackTrace = new StringWriter();
    ex.printStackTrace(new PrintWriter(stackTrace));
    String report = stackTrace.toString();

    if(myContext instanceof MainActivity){

        System.gc();
        android.os.Process.killProcess(android.os.Process.myPid());

    }else{

        Intent intent = new Intent(myContext, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        myContext.startActivity(intent);
        System.gc();
        android.os.Process.killProcess(android.os.Process.myPid());

    }
}

}