Android采集应用崩溃日志

来源:互联网 发布:2016年 网络热门话题 编辑:程序博客网 时间:2024/06/15 17:29

使用CrashHandler来获取应用的crash信息

Android应用不可避免的会发生crash,也称之为崩溃。应用发生崩溃时,会强制停止掉正在执行的程序,就是出现闪退和提示用户程序已经停止运行,这样对用户来说是很不友好的。

当用户发生了crash时,开发者却无法得治程序为何crash。Android中提供了处理这类问题的方法setDefaultUncaughtExceptionHandler。

 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {        SecurityManager sm = System.getSecurityManager();        if (sm != null) {            sm.checkPermission(                new RuntimePermission("setDefaultUncaughtExceptionHandler")                    );        }         defaultUncaughtExceptionHandler = eh;     }

上面的setDefaultUncaughtExceptionHandler方法作用是设置系统默认异常处理器,这个方法就可以解决crash的问题。
当crash发生的时候,系统就会回调UncaughtExceptionHandler的uncaughtException方法,在uncaughtException方法中就可以获取到异常信息,然后将异常信息存储到SD卡中,然后再合适的时间通过网络将crash上传到服务器。

public class CrashHandler implements UncaughtExceptionHandler {    private static final String TAG = "CrashHandler";    private static final boolean DEBUG = true;    /**崩溃日志存储目录*/    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/CrashTest/log/";    private static final String FILE_NAME = "crash";    private static final String FILE_NAME_SUFFIX = ".trace";    private static CrashHandler sInstance = new CrashHandler();    private UncaughtExceptionHandler mDefaultCrashHandler;    private Context mContext;    private CrashHandler() {    }    public static CrashHandler getInstance() {        return sInstance;    }    public void init(Context context) {        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();        Thread.setDefaultUncaughtExceptionHandler(this);        mContext = context.getApplicationContext();    }    /**     * 这个是最关键的函数,当程序中有未被捕获的异常,系统将会自动调用#uncaughtException方法     * thread为出现未捕获异常的线程,ex为未捕获的异常,有了这个ex,我们就可以得到异常信息。     */    @Override    public void uncaughtException(Thread thread, Throwable ex) {        try {            //导出异常信息到SD卡中            String filePath= dumpExceptionToSDCard(ex);            uploadExceptionToServer(filePath);            //这里可以通过网络上传异常信息到服务器,便于开发人员分析日志从而解决bug        } catch (IOException e) {            e.printStackTrace();        }        ex.printStackTrace();        //如果系统提供了默认的异常处理器,则交给系统去结束我们的程序,否则就由我们自己结束自己        if (mDefaultCrashHandler != null) {            mDefaultCrashHandler.uncaughtException(thread, ex);        } else {            Process.killProcess(Process.myPid());        }    }    private String    dumpExceptionToSDCard(Throwable ex) throws IOException {        //如果SD卡不存在或无法使用,则无法把异常信息写入SD卡        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            if (DEBUG) {                Log.w(TAG, "sdcard unmounted,skip dump exception");                return null;            }        }        File dir = new File(PATH);        if (!dir.exists()) {            dir.mkdirs();        }        long current = System.currentTimeMillis();        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));        String path=PATH + FILE_NAME + time + FILE_NAME_SUFFIX;        File file = new File(path);        try {            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));            pw.println(time);            dumpPhoneInfo(pw);            pw.println();            ex.printStackTrace(pw);            pw.close();        } catch (Exception e) {            Log.e(TAG, "dump crash info failed");        }        return path;    }    /**获取程序崩溃的手机型号*/    private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {        PackageManager pm = mContext.getPackageManager();        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);        pw.print("App Version: ");        pw.print(pi.versionName);        pw.print('_');        pw.println(pi.versionCode);        //android版本号        pw.print("OS Version: ");        pw.print(Build.VERSION.RELEASE);        pw.print("_");        pw.println(Build.VERSION.SDK_INT);        //手机制造商        pw.print("Vendor: ");        pw.println(Build.MANUFACTURER);        //手机型号        pw.print("Model: ");        pw.println(Build.MODEL);        //cpu架构        pw.print("CPU ABI: ");        pw.println(Build.CPU_ABI);    }    /**通过次方法,上传崩溃日志到服务器*/    private void uploadExceptionToServer(String filePath) {        File file=new File(filePath);    }}

写好了CrashHandler,我们如何使用呢?

我们可以在Application初始化的时候为线程设置CrashHandler,如下:

CrashHandler.getInstance().init(this);
0 0
原创粉丝点击