In this tutorial, we will learn about how to handle exceptions manually in android using UncaughtExceptionHandler and how to restart app after exceptions. Some of the cases App gets crashed or situations like force close. Thread.setDefaultUncaughtExceptionHandler will enter to the uncaughtException method and trace the exceptions occured. Below few lines of code will help you to read those exceptions and in which activity using logs/print.
public class MyExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final Class<?> myActivityClass;
public MyExceptionHandler(Context context, Class<?> c) {
myContext = context;
myActivityClass = c;
}
public void uncaughtException(Thread thread, Throwable exception) {
// To know what causes the exception and in which activity
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
System.err.println(stackTrace); // You can use LogCat too
Intent intent = new Intent(myContext, myActivityClass);
String s = stackTrace.toString();
intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString());
intent.putExtra("stacktrace", s);
// To clear the previous tasks from stack
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
myContext.startActivity(intent);
// myPid returns the identifier of this process for restarting the Activity
Process.killProcess(Process.myPid());
System.exit(0);
}
}
Now the only thing you need to do is call uncaughtException method by using Thread.setDefaultUncaughtExceptionHandler inside onCreate() method of launcher activity. The app will restart after crash or force close from launcher activity.
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this, LauncherActivity.class));
0 Comment(s)