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

Android抓取崩溃日志

2016-01-13 10:04 666 查看
崩溃日志抓取

感谢 “liuhe688” 大神的无私分享

这里是博客地址:http://blog.csdn.net/liuhe688/article/details/6584143#

在Android里如果运行时出现异常,而开发者又没有手动去catch的话,程序就会崩溃;



在IDE上进行调试的时候,错误信息会第一时间显示在logcat里,可以很方便的查看崩溃信息,找出错误;

但是如果程序在非调试阶段崩溃的话,logcat就没法为我们显示崩溃日志了。

所以当程序出现未捕获的异常导致崩溃时,我们可以将崩溃日志写到sd卡中,方便排查。

原文大家可以看 “liuhe688” 大神的博客,http://blog.csdn.net/liuhe688/article/details/6584143# 讲解的很清楚;

这里简单讲解一下步骤:

1.自定义类实现UncaughtExceptionHandler接口

2.重写uncaughtException方法

3.在初始化时使用自定义的CrashCatchHandler替换掉系统默认的UncaughtException处理器

4.在uncaughtException方法中获得错误信息,并将它存储到sd卡中

5.自定义Application继承Application,在onCreate方法中初始化自定义的CrashCatchHandler

6.更改AndroidManifest中Application的name字段为自定义的Application


注:这里其实不是必须重写Application,在任何时候我们都可以设置默认的UncaughtException处理器;但是为了能够将整个应用程序的崩溃日志都截取下来,最好是在Application中就更改好。

自己改造过的demo在github上的地址:https://github.com/BadWaka/CrashCatchDemo

预览

提示信息:



sd卡中的crash文件:



使用NotePad++打开.log文件:



下面直接贴出代码:

权限:

<!--读写sd卡权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


CrashCatchHandler自定义UncaughtException处理器

package com.waka.workspace.crashcatchdemo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
* 崩溃日志抓取
* <p>
* UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告
* <p>
* 感谢 liuhe688 大神的无私分享
* <p>
* 这里是博客地址:http://blog.csdn.net/liuhe688/article/details/6584143#
*
* @author liuhe688
* @一些改动 waka
*/
public class CrashCatchHandler implements UncaughtExceptionHandler {

public static final String TAG = "CrashHandler";

private static final CrashCatchHandler INSTANCE = new CrashCatchHandler();// 单例模式
private Context context;
private UncaughtExceptionHandler defaultHandler;// 系统默认的UncaughtException处理类
private Map<String, String> infosMap = new HashMap<String, String>(); // 用来存储设备信息和异常信息

/**
* 私有构造方法,保证只有一个CrashHandler实例
*/
private CrashCatchHandler() {

}

/**
* 获取CrashHandler,单例模式
*
* @return
*/
public static CrashCatchHandler getInstance() {
return INSTANCE;
}

/**
* 初始化
*
* @param context
*/
public void init(Context context) {
this.context = context;
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 获取系统默认的UncaughtException处理器
Thread.setDefaultUncaughtExceptionHandler(this);// 设置当前CrashHandler为程序的默认处理器
}

/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && defaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
defaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "exception : ", e);
e.printStackTrace();
}
// 杀死进程
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return 如果处理了该异常信息, 返回true;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
// 使用Toast显示异常信息
new Thread() {
public void run() {
Looper.prepare();
Toast.makeText(context, "程序出现未捕获的异常,即将退出!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();

collectDeviceInfo(context);// 收集设备参数信息
saveCrashInfoToFile(ex);// 保存日志文件

return true;
}

/**
* 收集设备信息
*
* @param context
*/
public void collectDeviceInfo(Context context) {
// 使用包管理器获取信息
PackageManager pm = context.getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
// TODO 在这里得到包的信息
String versionName = pi.versionName == null ? "" : pi.versionName;// 版本名;若versionName==null,则="null";否则=versionName
String versionCode = pi.versionCode + "";// 版本号
infosMap.put("versionName", versionName);
infosMap.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an NameNotFoundException occured when collect package info");
e.printStackTrace();
}

// 使用反射获取获取系统的硬件信息
Field[] fields = Build.class.getDeclaredFields();// 获得某个类的所有申明的字段,即包括public、private和proteced,
for (Field field : fields) {
field.setAccessible(true);// 暴力反射 ,获取私有的信息;类中的成员变量为private,故必须进行此操作
try {
infosMap.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (IllegalArgumentException e) {
Log.e(TAG, "an IllegalArgumentException occured when collect reflect field info", e);
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e(TAG, "an IllegalAccessException occured when collect reflect field info", e);
e.printStackTrace();
}
}
}

/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称
*/
@SuppressLint("CommitPrefEdits")
private String saveCrashInfoToFile(Throwable ex) {
// 字符串流
StringBuffer stringBuffer = new StringBuffer();

// 获得设备信息
for (Map.Entry<String, String> entry : infosMap.entrySet()) {// 遍历map中的值
String key = entry.getKey();
String value = entry.getValue();
stringBuffer.append(key + "=" + value + "\n");
}

// 获得错误信息
Writer writer = new StringWriter();// 这个writer下面还会用到,所以需要它的实例
PrintWriter printWriter = new PrintWriter(writer);// 输出错误栈信息需要用到PrintWriter
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {// 循环,把所有的cause都输出到printWriter中
cause.printStackTrace(printWriter);
cause = ex.getCause();
}
printWriter.close();
String result = writer.toString();
stringBuffer.append(result);

// 写入文件
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String crashFileName = rootPath + "/crash_" + simpleDateFormat.format(new Date()) + ".log";

/*//因为是sd卡根目录,所以就需要创建父文件夹了
File file = new File(rootPath);
if (!file.exists()) {
file.mkdirs();// 如果不存在,则创建所有的父文件夹
}*/

try {
FileOutputStream fos = new FileOutputStream(crashFileName);
fos.write(stringBuffer.toString().getBytes());
fos.close();

//TODO 在这里可以将文件名写入sharedPreferences中,方便下一次打开程序时对错误日志进行操作
/*SharedPreferences.Editor editor = mContext
.getSharedPreferences("waka").edit();
editor.putString("lastCrashFileName", crashFileName);
editor.commit();*/

return crashFileName;
} catch (FileNotFoundException e) {
Log.e(TAG, "an FileNotFoundException occured when write crashfile to sdcard", e);
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "an IOException occured when write crashfile to sdcard", e);
e.printStackTrace();
}
return null;
}

}


自定义Application:

public class CrashCatchApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
CrashCatchHandler crashCatchHandler = CrashCatchHandler.getInstance();//获得单例
crashCatchHandler.init(getApplicationContext());//初始化,传入context
}
}


更改AndroidManifest.xml

<!--使用自定义的Application-->
<application
android:name=".CrashCatchApplication"
</application>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: