Johan
Johan

Reputation: 35194

setDefaultUncaughtExceptionHandler makes app crash silently

CustomExceptionHandler

public class CustomExceptionHandler implements UncaughtExceptionHandler {

private Context ctx;
private ContentResolver cr;

public CustomExceptionHandler(Context ctx, ContentResolver cr) {
    this.ctx = ctx;
    this.cr = cr;
}

public void uncaughtException(Thread t, Throwable e) {

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();


    String deviceUuid = Utilities.DeviceUuid(ctx, cr);
    String bluetoothName = Utilities.LocalBluetoothName();

    AsyncTasks.ErrorLogTask logTask = new AsyncTasks.ErrorLogTask(e, bluetoothName, deviceUuid, stacktrace);
    logTask.execute();
}




}

Called from my main activity:

Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(getBaseContext(), getContentResolver()));

When an exception occurs now, i dont get the regular "unfortunately, has stopped" popup. Its just a black screen. If i remove my call from my main activity, in other words dont use the CustomExceptionHandler anymore, i get the default behaviour.

Is there any way to implement the default error behaviour in my class?

Thanks in advance!

Upvotes: 4

Views: 7128

Answers (1)

David Wasser
David Wasser

Reputation: 95578

You can add the following at the end of your exception handler to get the "unfortunately has stopped" dialog:

System.exit(1);

However, this will cause the process to terminate which means that your AsyncTask will not run to completion.

In any case, I would doubt that your code will run reliably anyway if you are in an uncaughtExceptionHandler, because you have no idea what the state of your application is. It might work, and it might not. What you could also try is to create a new Thread in your uncaughtExceptionHandler and have that thread sleep for a little while and then terminate the application using System.exit(). That may give your AsyncTask enough time to run to completion.

Upvotes: 3

Related Questions