您的位置:首页 > 移动开发 > Android开发

Android全局异常捕获

2016-04-22 16:54 441 查看
一、构建异常处理的消息Handler

/**
* 用于捕获系统未知异常,并将异常写入log文件,便于开发人员查看
*
* @author wangmf
*/
public class CrashHandler implements UncaughtExceptionHandler {
//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();

//用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

private static CrashHandler crashHandler;

private UncaughtExceptionHandler mExceptionHandler;

private Context context;

public static final int CRASH_START_SPLASH = 10000;

/**
* 私有的构造方法
*
* @param context
*/
private CrashHandler(Context context) {

this.context = context;

mExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}

//通过单列的方式来获取一个实例变量
public static CrashHandler getInstance(Context context) {
if (crashHandler == null) {
crashHandler = new CrashHandler(context);
}
return crashHandler;
}

/**
* 初始化
*
* @param context
*/
public void init(Context context) {
this.context = context;

// 获取系统默认的 UncaughtException 处理器
mExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

// 设置该 CrashHandler 为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}

/**
* 当一个未知异常发生时调用该方法
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {

Log.e("logTest", "(wangmf):捕获到未知异常--并打印异常(该异常信息已经写入文件目录:" +
context.getExternalFilesDir(null).getAbsolutePath() + "/crash");

ex.printStackTrace();

if (!handleException(ex) && mExceptionHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mExceptionHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e("logTest", "error : ", e);
}

//退出程序,直接退出程序   【注意点1】
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(1);

// 重新启动程序,注释上面的退出程序
Intent intent = new Intent();
intent.putExtra("type",CRASH_START_SPLASH);
intent.setClass(context, SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "很抱歉,程序出现异常,即将重启...", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
//收集设备参数信息   【注意点2】
collectDeviceInfo(context);
//保存日志文件
saveCrashInfo2File(ex);【注意点3】
return true;
}

/**
* 收集设备参数信息
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e("logTest", "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d("logTest", field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e("logTest", "an error occured when collect crash info", e);
}
}
}

/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称, 便于将文件传送到服务器
*/
private String saveCrashInfo2File(Throwable ex) {

StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}

Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                String path = "/sdcard/crash/";
//            	String path = AsyncImageLoader.imageCachePath+"/crash/";
//应用安装包目录,当应用被卸载的时候,会一同被删除
String path = context.getExternalFilesDir(null).getAbsolutePath() + "/crash";

File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(new File(path, fileName));
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e("logTest", "an error occured while writing file...", e);
}
return null;
}
}
注意点:

1,崩溃以后的处理可以实现关闭系统,也可以重新打开App。系统已经崩溃,所以内存变量的值全被销毁,注意相关联系变量的控制。

2,收集设备信息,收集崩溃信息,便于获取信息进而解决问题;

3,将崩溃信息写入本地文件。在服务器支持的条件下,可实现将此文件读取回传,从而实现崩溃信息收集。

二、使用

在Application类oncreate中获取对象并初始化

CrashHandler crashHandler = CrashHandler.getInstance(CONTEXT);
crashHandler.init(this);



三、添加数据埋点

在主要的网络请求点,增加数据回传,从而实现数据埋点,为研究客户行为有很好地帮助,也是大数据研究的数据基础。移动端在实现的时候,主要考虑在合适的地方买数据采集点,然后是优化网络请求,更有效的回传数据。

我不知道未来如何,每天对一点的付出,心中多一点的心安。每天过的舒服并不一定真舒服,每天过的不舒服并不一定真不舒服 ~_~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: