setDefaultUncaughtExceptionHandler makes app crash silently

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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!

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!