Skip to content Skip to sidebar Skip to footer

Android UncaughtExceptionHandler To Finish App

I want to close the app after logging an unhandled exception. After searching here i made the following: public class MyApplication extends Application { //uncaught exceptions

Solution 1:

At last i resolved this making a class implementing the Thread.UncaughtExceptionHandler interface:

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private BaseActivity activity;
    private Thread.UncaughtExceptionHandler defaultUEH;

    public MyUncaughtExceptionHandler(BaseActivity activity) {
        this.activity = activity;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void setActivity(BaseActivity activity) {
        this.activity = activity;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        //LOGGING CODE
        //........

        defaultUEH.uncaughtException(thread, ex);

    }
}

In the BaseActivity i added the following code:

//exception handling
private static MyUncaughtExceptionHandler _unCaughtExceptionHandler;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    if(_unCaughtExceptionHandler == null)
        _unCaughtExceptionHandler = new MyUncaughtExceptionHandler(this);
    else
        _unCaughtExceptionHandler.setActivity(this);

    if(Thread.getDefaultUncaughtExceptionHandler() != _unCaughtExceptionHandler)
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}

I know its the same code i have in the question, but somehow its working now. When i have more free time i will look this deeply to find the root cause and post it


Post a Comment for "Android UncaughtExceptionHandler To Finish App"