It\'s a general question, which raised from specific scenario, but I\'d like to get a general answer how to deal with the following situation:
Background:
All you need to do is Extend all the activities with BaseActivity. The app never crashes at any point
Code sniplet for BaseActivity :
public class BaseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Error"+Thread.currentThread().getStackTrace()[2],paramThrowable.getLocalizedMessage());
}
});
}
}
As mentioned above, Thread.setDefaultUncaughtExceptionHandler is the proper way to handle this. Create the class:
private class MyThreadUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e(TAG, "Received exception '" + ex.getMessage() + "' from thread " + thread.getName(), ex);
}
}
Then call setDefaultUncaughtExceptionHandler from your main thread:
Thread t = Thread.currentThread();
t.setDefaultUncaughtExceptionHandler(new MyThreadUncaughtExceptionHandler());