Updated 14 December 2016
Bye Bye ANR in Android.
It’s not a good practice to restart the application forcefully. We should try to catch exception wherever possible. However, android provide a way to perform certain intent whenever there is some exception occurred in the application that is not caught in the try-catch block.
The handler works the current thread on which it is being added. Â We can add the custom exception handler on a thread in the following manner:
| 1 2 |  Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,                 SplashScreenActivity.class)); | 
Here is an Exception handler class that implements java.lang.Thread.UncaughtExceptionHandler.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.webkul.mobikul.helper; import android.content.Context; import android.content.Intent; import android.os.Process; import java.io.PrintWriter; import java.io.StringWriter; 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) {         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();         //you can use this String to know what caused the exception and in which Activity         intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString());         intent.putExtra("stacktrace", s);         myContext.startActivity(intent);         //for restarting the Activity         Process.killProcess(Process.myPid());         System.exit(0);     } } | 
Stay updated !!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
1 comments