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.