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

android 捕获全局异常;

2016-03-21 00:00 495 查看
摘要: 有时候自己的app运行着运行着就崩掉了,然而却没有捕获到,尤其在上线以后,用户一定程度来说,是一个基数众多的“测试员”,而我们做的就是把用户测试的结果(崩掉的日志)log到自己的服务器并拿出相应的办法针对性地解决。以下就是进行全局异常的捕获。

自己定义一个用于捕获全局异常的类,继承自 Thread.UncaughtException:

给此类(CrashHandler)设计一个单例:

继承UncaughtException后实现 uncaughtException(Thread thread, Throwable ex) 方法

自定义抓取异常的处理操作: handleException(Throwable ex)

代码如下:

public class CrashHandler implements Thread.UncaughtExceptionHandler {

private static final String TAG = "CrashHandler";
private Thread.UncaughtExceptionHandler defaultHandler;
private Context context;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();

//创建CrashHandler实例(单例模式);
private static CrashHandler instance = new CrashHandler();

public static CrashHandler getInstance() {
return instance;
}

/**
* 私有化构造器保证只有一个对象
*/
private CrashHandler() {

}

/**
* 初始化
*
* @param context
*/
public void init(Context context) {

this.context = context;

//获取系统默认的uncaughtException处理器
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//设置crashhandler为程序默认的处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}

/**
* 当UncaughtException发生时会转入该函数来处理
*
* @param thread
* @param ex
*/
@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, "uncaughtException: error",e );
}

//退出程序
Process.killProcess(0);
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() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();

//手机设备参数信息;
collectDeviceInfo(context);

//保存日志文件:
saveCrashInfo2File(ex);
return true;
}

/**
* 保存错误信息到文件中
* @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);

String fileName = null;
try {
long timestamp = System.currentTimeMillis();
String time = dateFormat.format(new Date());
fileName = "crash-" + time + "-" + timestamp + ".loge";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = "/sdcard/crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (IOException e) {
Log.e(TAG, "saveCrashInfo2File: an error occured while writing file", e);
}

return null;
}

/**
* 手机设备参数信息
*
* @param context
*/
private void collectDeviceInfo(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
PackageManager.GET_ACTIVITIES);

if (packageInfo != null) {
String versinName = packageInfo.versionName == null ? "null" : packageInfo.versionName;
String versionCode = packageInfo.versionCode + "";
infos.put("versionName", versinName);
infos.put("versionCode", versionCode);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "an error occored when collect package info", e);
}

Field[] declaredFields = Build.class.getDeclaredFields();
for (Field field : declaredFields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + ":" + field.get(null));
} catch (IllegalAccessException e) {
Log.e(TAG, "collectDeviceInfo: an error occured when collect crash info", e);
}
}
}
}


当然不要忘了在Application里面初始化:

App Application {
onCreate() {
.onCreate();
CrashHandler crashHandler = CrashHandler.();
crashHandler.init(getApplicationContext());
}
}

记得在menifest.xml给App添加 name

文章转自 http://blog.csdn.net/jdsjlzx/article/details/7606423
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: