我想在Android上使用UncaughtExceptionHandler
。
如果粉碎应用程序,首先显示MainActivity
第二,在logcat
MainActivity
对话框
但没有显示活动,logcat对话框
所以我尝试使用吐司 它显示吐司,但没有显示活动 确切地说,显示了activity_main.xml并在activity_main上显示了logcat对话框
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler(this));
setContentView(R.layout.activity_main);
}
UnhandledExceptionHandler.java(吐司测试)
public class UnhandledExceptionHandler implements UncaughtExceptionHandler {
private static final String TAG = "UnUnHandler";
private final Activity activity;
public UnhandledExceptionHandler(final Activity activity) {
this.activity = activity;
}
public void uncaughtException(Thread unusedThread, final Throwable e) {
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(activity.getApplicationContext(), "occur errororor", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
UnhandledExceptionHandler.java(测试对话框)
public class UnhandledExceptionHandler implements UncaughtExceptionHandler {
private final Activity activity;
public UnhandledExceptionHandler(final Activity activity) {
this.activity = activity;
}
public void uncaughtException(Thread unusedThread, final Throwable e) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
String title = "Fatal error: ";
String msg = "fffff"
TextView errorView = new TextView(UnhandledExceptionHandler.this.activity);
errorView.setText(msg);
errorView.setTextSize(2, 8.0F);
ScrollView scrollingContainer = new ScrollView(UnhandledExceptionHandler.this.activity);
scrollingContainer.addView(errorView);
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
System.exit(1);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(UnhandledExceptionHandler.this.activity);
builder.setTitle(title)
.setView(scrollingContainer)
.setPositiveButton("Exit", listener).show();
}
});
}
}