0

I have an application with global excpetion handler like this:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

    }
}

I want to avoid display force close to user and show user a friendly toast like "Something went wrong...". Here is the exception handler class:

public class ExceptionHandler implements
        Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final String LINE_SEPARATOR = "\n";


    public ExceptionHandler(Context context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        StringBuilder errorReport = new StringBuilder();
        errorReport.append("************ CAUSE OF ERROR ************\n\n");
        errorReport.append(stackTrace.toString());
        Log.e("ERROR_TAG", errorReport.toString());
        Utils.showShortToast(R.string.something_went_wrong, myContext);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                   android.os.Process.killProcess(android.os.Process.myPid());
                   System.exit(10);
            }
        },1000);
    }
}

The problem is when it comes to display toast, application freezes and wait till system.exit() is called and then application exits. And as it noticed in refercend questions below, calling exit() right after displaying toast lead to process kill and does not displays toast.

P.S. I've read this, this and this but none of them lead to a solution.

Community
  • 1
  • 1
VSB
  • 9,825
  • 16
  • 72
  • 145
  • 2
    Why You are exiting app on problem. handling exeptions should handle it not kill app, create some ErrorActivty and go there in catch. You are doing the same as standard android exception - killing app, i don't undersand purpose of such thinking. – Maciej Sikora Aug 10 '16 at 13:05
  • @MaciejSikora Even trying to handle all exceptions, there may happen that some of them are not caught because of different reasons (developer mistake, developer lack of knowledge, wide variation of different OS and platforms). So I just want to avoid display user the famouse "Force Close.." window and save the error log to pinpoint problem and handle that uncaught exception in future. This is the reason! :) – VSB Aug 10 '16 at 13:10
  • App errors are not pokemons, solve them not catch them :). Change way of thinking. – Maciej Sikora Aug 10 '16 at 14:42
  • @MaciejSikora This method is a part of a crash report which is usual in many apps. Displaying toast is just for sake of informing user. – VSB Aug 10 '16 at 14:45

1 Answers1

-1

Make the toast in onDestroy(). I think it's good way :)

Best regar

Rettiwer
  • 9
  • 3