【发布时间】:2014-06-08 20:41:31
【问题描述】:
我想在没有任何第三方库的情况下处理我的应用中未处理的异常。
所以我写了一个代码。
活动:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
throw new NullPointerException();
}
我的崩溃处理程序:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.widget.Toast;
/**
* Created by S-Shustikov on 08.06.14.
*/
public class ReportHelper implements Thread.UncaughtExceptionHandler {
private final AlertDialog dialog;
private Context context;
public ReportHelper(Context context) {
this.context = context;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
showToastInThread("OOPS!");
}
public void showToastInThread(final String str){
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
}
当我启动应用程序时,如您所见我抛出了 NullPointerException。显示了我的处理逻辑中的Toast,也显示了对话框。但!对话框点击处理不正确。我的意思是onClick 方法中的逻辑不起作用。什么问题以及如何解决?
【问题讨论】:
-
定义什么是不正确的?发生了什么以及您的 onClick 行为中的预期行为是什么?
-
你期待什么,你看到了什么?即为什么你说'它不起作用'?
-
@ben75 我希望对话框将关闭,应用程序将在按下“退出”按钮时完成。
-
@MartinKonecny 预期行为我在之前对 ben75 的回答中描述。对话框刚刚显示,但点击未处理。
-
@SergeyShustikov 我也有这个问题。你找到解决办法了吗?