`

Android 错误信息捕获发送至服务器【整理】

阅读更多
android项目开发中的debug是很重要的,以下转载自前辈的文章,记录一下:

程序员最头疼的事情就是bug和debug。这次debug长达20天,搞的我心力交瘁。累,因为Android兼容性,不同手机会有不同的bug 出来,而且很难复现,所以就上网找了下类似保存错误log到文件再上传到服务器,现把源码也共享出来。上传至服务器的代码我没加。相信大家都有现成的代码了。

先讲下原理,跟JavaEE的自定义异常捕获一样,将错误一直向上抛,然后在最上层统一处理。这里就可以获得Exception Message,进行保存操作

异常捕获类如下:废话少说,代码附上。

import android.app.Application;

public class App extends Application {

	@Override
	public void onCreate() {
		super.onCreate();
		CrashHandler crashHandler = CrashHandler.getInstance();
		// 注册crashHandler
		crashHandler.init(getApplicationContext());
	}
}


AndroidManifest.xml中设置该App:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.yangguangfu.uncaught" android:versionCode="1"
	android:versionName="1.0">
	<application android:name="com.yangguangfu.uncaught.App"
		android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".ExceptionHandlerDome" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
</manifest>


CrashHandler类如下:
import java.io.File;
import java.io.FileOutputStream;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;

/**
 * @author 阿福 在Application中统一捕获异常,保存到文件中下次再打开时上传
 */
public class CrashHandler implements UncaughtExceptionHandler {
	/**
	 * 是否开启日志输出,在Debug状态下开启, 在Release状态下关闭以提示程序性能
	 * */
	public static final boolean DEBUG = true;
	/** 系统默认的UncaughtException处理类 */
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	/** CrashHandler实例 */
	private static final CrashHandler INSTANCE = new CrashHandler();

	/** 程序的Context对象 */
	// private Context mContext;
	/** 保证只有一个CrashHandler实例 */
	private CrashHandler() {
	}

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

	/**
	 * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
	 * 
	 * @param ctx
	 */
	public void init(Context ctx) {
		// mContext = ctx;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/**
	 * 当UncaughtException发生时会转入该函数来处理
	 */
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else { // 如果自己处理了异常,则不会弹出错误对话框,则需要手动退出app
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(10);
		}
	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
	 * 
	 * @return true代表处理该异常,不再向上抛异常,
	 *         false代表不处理该异常(可以将该log信息存储起来)然后交给上层(这里就到了系统的异常处理)去处理,
	 *         简单来说就是true不会弹出那个错误提示框,false就会弹出
	 */
	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return false;
		}
		// final String msg = ex.getLocalizedMessage();
		final StackTraceElement[] stack = ex.getStackTrace();
		final String message = ex.getMessage();
		// 使用Toast来显示异常信息
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				// Toast.makeText(mContext, "程序出错啦:" + message,
				// Toast.LENGTH_LONG).show();
				// 可以只创建一个文件,以后全部往里面append然后发送,这样就会有重复的信息,个人不推荐
				String fileName = "crash-" + System.currentTimeMillis()
						+ ".log";
				File file = new File(Environment.getExternalStorageDirectory(),
						fileName);
				try {
					FileOutputStream fos = new FileOutputStream(file, true);
					fos.write(message.getBytes());
					for (int i = 0; i < stack.length; i++) {
						fos.write(stack[i].toString().getBytes());
					}
					fos.flush();
					fos.close();
				} catch (Exception e) {
				}
				Looper.loop();
			}

		}.start();
		return false;
	}

	// TODO 使用HTTP Post 发送错误报告到服务器 这里不再赘述
	// private void postReport(File file) {
	// 在上传的时候还可以将该app的version,该手机的机型等信息一并发送的服务器,
	// Android的兼容性众所周知,所以可能错误不是每个手机都会报错,还是有针对性的去debug比较好
	// }
}


转自:http://yangguangfu.iteye.com/blog/1144769
分享到:
评论
1 楼 欧阳萧伦 2013-04-11  
前辈,如何将程序是哪行报错的信息也保存起来,方便解决问题

相关推荐

Global site tag (gtag.js) - Google Analytics