代码改变世界

android异常捕获处理

2016-01-31 19:24  百度乜搜不到  阅读(234)  评论(0编辑  收藏  举报

继承UncaughtExceptionHandler 接口,重写方法,进行处理

package com.example.exp;

import java.lang.Thread.UncaughtExceptionHandler;

import com.example.threadtest.MainActivity;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;

public class CrashHandler implements UncaughtExceptionHandler {

public static final String TAG = "CrashHandler";
private static CrashHandler INSTANCE = new CrashHandler();
private Application mContext;
private Thread.UncaughtExceptionHandler mDefaultHandler;

private CrashHandler() {
}

public static CrashHandler getInstance() {
return INSTANCE;
}

public void init(Application 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);
// }
if (!handleException(ex) && mDefaultHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
// 重新启动程序,注释上面的退出程序
Intent intent = new Intent();
intent.setClass(mContext,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}

}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return true;
}
//TODO

return true;
}
}