Android开发中获取crash信息

来源:互联网 发布:编程珠玑 第3版 pdf 编辑:程序博客网 时间:2024/06/05 06:20

我们知道不管程序怎么写都很难避免发生crash,Android应用程序亦是如此,如果能够收集Android应用程序发生crash信息的原因并在下一次新版本软件发布中修复相关问题的话,那么这将对产品的持续发展有很大的意义。下面将介绍Android开发中获取crash信息的实现。

查看java.lang.Thread类中的一个静态方法setDefaultUncaughtExceptionHandler的源码如下:

<span style="font-size:18px;">    /**     * Sets the default uncaught exception handler. This handler is invoked in     * case any Thread dies due to an unhandled exception.     *     * @param handler     *            The handler to set or null.     */    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {        Thread.defaultUncaughtHandler = handler;    }</span>

该方法是为线程设置异常处理器,静态变量Thread.defaultUncaughtHandler类型为UncaughtExceptionHandler,当crash发生时系统就会调用UncaughtExceptionHandler接口中的uncaughtException方法,在UncaughtExceptionHandler.uncaughtException方法中可以获取异常信息。因此我们可以重写UncaughtExceptionHandler.uncaughtException方法,在该方法中获取并处理异常信息,例如将异常信息存储到SD卡、在合适的时机将保存在手机本地异常信息通过网络上传到服务器,供开发者分析crash发生的场景从而在后续软件版本中修复该问题。

通过以上分析可知,我们可以定义UncaughtExceptionHandler接口的一个实现类,在该UncaughtExceptionHandler接口的实现类中首先实现一个UncaughtExceptionHandler对象,在它的uncaughtException方法中获取异常信息并将其存储在SD卡、上传到服务器上供开发人员分析;然后调用Thread.setDefaultUncaughtExceptionHandler方法将UncaughtExceptionHandler对象设置为线程默认的异常处理器。具体代码如下:

<span style="font-size:18px;">package com.fxj.crashdemo;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.lang.Thread.UncaughtExceptionHandler;import java.text.SimpleDateFormat;import java.util.Date;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.Process;import android.util.Log;public class CrashHandler implements UncaughtExceptionHandler {private static final String tag="com.fxj.crashdemo.CrashHandler";/*crash记录信息文件夹路径*/private static final String path=Environment.getExternalStorageDirectory().getPath()+"/CrashDemo/log/";/**crash文件名*/private static final String FileName="crash";/**crash文件后缀*/private static final String FileNameSuffix=".txt";/**CrashHandler单例对象*/private static CrashHandler sInstance=new CrashHandler();private UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;/**上下文*/private Context mContext;public CrashHandler() {super();// TODO Auto-generated constructor stub}/**获取CrashHandler单例,单例模式*/public static CrashHandler getInstance(){Log.i(tag,"CrashHandler#getInstance");if(sInstance==null){sInstance=new CrashHandler();}return sInstance;}public void init(Context context){Log.i(tag,"CrashHandler#init");mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();/*给线程设置异常处理器*/Thread.setDefaultUncaughtExceptionHandler(this);mContext = context.getApplicationContext();}/** * 函数名称:uncaughtException(Thread thread, Throwable ex) * 函数说明:UncaughtExceptionHandler接口中未实现的uncaughtException *   的方法,当有未捕获异常发生时系统就会调用uncaughtException方法。 * 函数参数:thread---发生未捕获异常的线程,ex----未捕获异常 * */@Overridepublic void uncaughtException(Thread thread, Throwable ex) {Log.i(tag,"CrashHandler#uncaughtException");        /*将异常信息导出到SD卡中*/ dumpExceptionToSDCard(ex);/*将异常信息上传到服务器*/uploadExceptionToServer(ex);if(this.mDefaultUncaughtExceptionHandler!=null){this.mDefaultUncaughtExceptionHandler.uncaughtException(thread, ex);System.out.println(tag+",使用系统默认的异常处理器来处理异常!");Log.i(tag,"使用系统默认的异常处理器来处理异常!");}else{Process.killProcess(Process.myPid());System.out.println(tag+",当前进程自己结束当前进程!");Log.i(tag,"当前进程自己结束当前进程!");}}/**将异常信息导出到SD卡中*/private void dumpExceptionToSDCard(Throwable ex) {/*检查SD卡是否存在*/if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){Log.i(tag,"SD卡不存在");return;} Log.i(tag,"SD卡存在");File fileDir=new File(path);if(!fileDir.exists()){/*当指定路径的文件夹不存在时创建指定的文件夹*/fileDir.mkdirs();}long current=System.currentTimeMillis();String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));Log.i(tag,"异常发生时间:"+time);File file=new File(path+FileName+time+FileNameSuffix);        try {if(!file.exists()){file.createNewFile();}PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(file)));pw.write(time);dumpPhoneInfo(pw);pw.println();/*将异常的跟踪栈信息输出到指定的输出流*/ex.printStackTrace(pw);//System.out.println(ex);pw.close();} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();Log.i(tag,"dump crash infomation failed!");}}/**导出手机信息 * @throws NameNotFoundException */private void dumpPhoneInfo(PrintWriter pw) {PackageManager pm=mContext.getPackageManager();try {PackageInfo pi=pm.getPackageInfo(mContext.getPackageName(),PackageManager.GET_ACTIVITIES);pw.println();pw.println("APP Version:"+pi.versionName+"_"+pi.versionCode);pw.println("Android系统版本号OS Version:"+Build.VERSION.RELEASE+"_"+Build.VERSION.SDK_INT);pw.println("手机制造商Vendor:"+Build.MANUFACTURER);pw.println("手机型号Model:"+Build.MODEL);pw.println("CPU架构CPU ABI:"+Build.CPU_ABI);} catch (NameNotFoundException e) {// TODO Auto-generated catch blockLog.i(tag,"NameNotFoundException");e.printStackTrace();}}/**将异常信息上传到服务器*/private void uploadExceptionToServer(Throwable ex) {// TODO Auto-generated method stub}}</span>
在UncaughtExceptionHandler的实现类CrashHandler的init()方法中首先获取Thread.getDefaultUncaughtExceptionHandler然后给线程设置默认的异常处理器。在uncaughtException方法中通过文件读写的方式将异常信息存储到SD卡中。注意uncaughtException方法的两个参数分别为Thread类型和Throwable类型,在Java中任何异常都是继承自Throwable,Java异常分为Error和Exception

定义好UncaughtExceptionHandler的实现类CrashHandler后,我们可以选择在Application初始化的时候为线程设置CrashHandler,通常我们可以重写android.app.Application这个类,在这个类中的onCreate方法中为线程设置CrashHandler,具体代码如下:

<span style="font-size:18px;">package com.fxj.crashdemo;import android.app.Application;import android.util.Log;public class MyApplication extends Application {private static final String tag="MyApplication";private static MyApplication sInstance;@Overridepublic void onCreate() {super.onCreate();Log.i(tag,"onCreate");sInstance=this;CrashHandler crashHandler=CrashHandler.getInstance();crashHandler.init(this);}public MyApplication getMyApplicationInstance(){return sInstance;}}</span>

当然我们还需要在AndroidManifest.xml文件中指定当前Android应用的Application,由于我们自定义的MyApplication继承自android.app.Application,因此需要在AndroidManifest.xml文件<application>标签中指定当前Android应用的Application,如下所示:

<span style="font-size:18px;">    <application        android:name="com.fxj.crashdemo.MyApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme"         ></span>

最后为了测试能否获取异常,我们可以在Activity添加一个Button按钮,当点击Button时抛出一个异常,具体代码如下:

<span style="font-size:18px;">this.button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(tag,"按钮被点击!");throw new RuntimeException("抛出自定义异常!");}});</span>
测试例程源代码(github)


0 0
原创粉丝点击