This would be the best way to handle an uncaught exception:
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); appInitialization(); } private void appInitialization() { defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler); } private UncaughtExceptionHandler defaultUEH;
The application is the base class for those who need to maintain the state of the global application. And therefore, there will be a better place to handle such exceptions.
EDIT: The above code will handle uncaught exceptions if they are thrown into the user interface thread. If an exception occurs in the workflow, you can handle it as follows:
private boolean isUIThread(){ return Looper.getMainLooper().getThread() == Thread.currentThread(); } // Setup handler for uncaught exceptions. Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException (Thread thread, Throwable e) { handleUncaughtException (thread, e); } }); public void handleUncaughtException(Thread thread, Throwable e) { e.printStackTrace(); // not all Android versions will print the stack trace automatically if (isUIThread()) { // exception occurred from UI thread invokeSomeActivity(); } else { //handle non UI thread throw uncaught exception new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { invokeSomeActivity(); } }); } }
source share