Implement a callback to avoid force close, while reporting crash and showing a support screen

85 Views Asked by At

Instead of the force close dialog I would like to show an Activity with support information to the user and at the same time send error information to bugsnag. I followed this advice (https://trivedihardik.wordpress.com/2011/08/20/how-to-avoid-force-close-error-in-android/) to set up a handler for uncaught exceptions. Reporting to bugsnag with bugsnag.notify obviously takes some time, so I thought I need an AsyncTask to show the "Support Activity" and send the notification. The process shall be killed only after this has been completed. AFAIK, the problem with AsyncTask is that is not capable to update the UI thread when put into a helper class. So how can I can make sure the error is reported to busgnag, the Support Activity is shown and the process is killed afterwards?

Code within MainActivity.java

Bugsnag.init(this);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

ExceptionHandler.java

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import com.bugsnag.android.Bugsnag;

public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
    private final Activity myContext;

    public ExceptionHandler(Activity context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        new ReportCrashTask().execute();
    }

    private class ReportCrashTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            Intent intent = new Intent(myContext, CrashActivity.class);
            myContext.startActivity(intent);

            Bugsnag.notify(new RuntimeException("Test error"));
            return "done";
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        }
    }
}
0

There are 0 best solutions below