您的位置:首页 > 其它

Thread.UncaughtExceptionHandler捕获未知异常

2013-05-08 10:05 441 查看
在Android开发中,常常会出现uncheched Exception 导致程序的crash,为了提供良好的用户体验,并对出错的信息进行收集,以便对程序进行改进,提高程序的健壮性。因此,常使用Thread.UncaughtExceptionHandler来进行处理。

首先需要继承Thread.UncaughtExceptionHandler类

public class CrashHandler implements Thread.UncaughtExceptionHandler {
public static final String TAG = CrashHandler.class.getSimpleName();
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Thread.UncaughtExceptionHandler mDefaultHandler;

private CrashHandler() {
}

public static CrashHandler getInstance() {
return INSTANCE;
}

public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
// if (!handleException(ex) && mDefaultHandler != null) {
// mDefaultHandler.uncaughtException(thread, ex);
// } else {
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(10);
// }
System.out.println("uncaughtException");

new Thread() {
@Override
public void run() {
Looper.prepare();
new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false)
.setMessage("程序崩溃了...").setNeutralButton("我知道了", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
})
.create().show();
Looper.loop();
}
}.start();
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return true;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(mContext).setTitle("提示")
.setMessage("程序崩溃了...").setNeutralButton("我知道了", null)
.create().show();
}
});

return true;
}
}
然后在Application类中进行注册
public class MyApplication extends Application{

@Override
public void onCreate(){
super.onCreate();
initErrorHandler();
}

private void initErrorHandler(){
CrashHandler handler = CrashHandler.getInstance();
handler.init(this);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: