Android中的异常处理 CrashHandler

android中如果出现未捕获异常就会让应用程序crash掉,给用户的提示仅仅是该应用已崩溃,很不友好,自己定义一个UncaughtExceptionHanlder来捕获UI线程上的Exception,使用AlertDialog的方式展示出来,可以方便测试,也可以提升用户体验

package com.tcl.navigator.common;

import java.lang.Thread.UncaughtExceptionHandler;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Looper;
import android.util.Log;
/**
*
* @author peizc 2012-11-23
* 默认处理机制
*/

public class CrashHandler implements UncaughtExceptionHandler {

private static final String FLAG = "CrashHandler";
private Context mContext;

private static CrashHandler INSTANCE = new CrashHandler();
private Thread.UncaughtExceptionHandler mDefaultHandler;

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, final Throwable ex) {
// TODO Auto-generated method stub
Log.e(FLAG, ex.toString());
new Thread() {
public void run() {
Looper.prepare();
new AlertDialog.Builder(mContext).setTitle("提示")
.setCancelable(false).setMessage("Error...\n" + ex.toString())
.setNeutralButton("I know",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ex.printStackTrace();
System.exit(0);
}
}).create().show();
Looper.loop();
};

}.start();
}

}

你可能感兴趣的:(Android)