Android系统的“程序异常退出”,给应用的用户体验造成不良影响。为了捕获应用运行时异常并给出友好提示,便可继承UncaughtExceptionHandler类来处理。通过Thread.setDefaultUncaughtExceptionHandler()方法将异常处理类设置到线程上即可。
1、异常处理类,代码如下:
-
public class CrashHandler implements UncaughtExceptionHandler {
-
public static final String TAG = "CrashHandler";
-
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) {
-
-
-
-
-
-
-
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();
-
}
-
-
-
-
-
-
-
-
private boolean handleException(Throwable ex) {
-
if (ex == null) {
-
return true;
-
}
-
-
-
-
-
-
-
-
-
-
return true;
-
}
-
}
2、线程绑定异常处理类
-
public class CrashHandlerActivity extends Activity {
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
CrashHandler crashHandler = CrashHandler.getInstance();
-
crashHandler.init(this);
-
-
throw new NullPointerException();
-
}
-
}
Demo下载地址:http://code.google.com/p/android-custom-view/downloads/list
转载地址: http://orgcent.com/android-uncaughtexceptionhandler-exception/
| 萝卜白菜的博客
Android 捕获系统全局异常
原文:http://blog.csdn.net/jecons/article/details/39290859