I want my Android app to handle uncaught exceptions by sending the stacktrace to my backend application using a (POST) webservice. In order to do this, I set up an UncaughtExceptionHandler in my parent activity:
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this));
In my CustomExceptionHandler, I override the uncaughtException method:
@Override
public void uncaughtException(Thread thread, Throwable ex) {
HttpURLConnection connection = null;
try {
URL url = new URL("http://mywebserviceurl.com?message=justatest");
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
} catch (Exception e) {
//Handle crash
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
In order to test this I force my app to crash:
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
throw new RuntimeException("");
}
}, 2500);
but my webservice is not contacted. When I put a breakpoint on the second line of the try clause, it seems like the debugger very briefly arrives at the line, then the program and debugger simply quit. I also tried creating a new thread to handle the webservice call, I tried using AsyncTasks, but the behavior remains the same: my webservice is never contacted. What is going wrong?
Thanks.