当前位置: 首页 > news >正文

Android抓取崩溃日志

崩溃日志抓取
感谢 “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>

相关文章:

  • AndroidStudio NDK开发(1)
  • win10更新后开始菜单无效的解决方案
  • Android.mk语法说明(android ndk开发)
  • RecyclerView的简单使用
  • 冒泡排序
  • 快速排序
  • HttpURLConnection官方文档翻译
  • android studio中xml文件代码提示问题
  • Android相机开发那些坑
  • ART、JIT、AOT、Dalvik之间有什么关系?
  • SharedPreference在使用过程中有什么注意点?
  • Android内存优化(使用SparseArray和ArrayMap代替HashMap)
  • Android中的观察者模式简单使用
  • Android内存泄漏总结
  • Android易混淆缩写笔记
  • Fastjson的基本使用方法大全
  • Invalidate和postInvalidate的区别
  • JS变量作用域
  • Making An Indicator With Pure CSS
  • Vue.js源码(2):初探List Rendering
  • vue自定义指令实现v-tap插件
  • 聚簇索引和非聚簇索引
  • 力扣(LeetCode)965
  • 使用权重正则化较少模型过拟合
  • 为视图添加丝滑的水波纹
  • 线上 python http server profile 实践
  • 写给高年级小学生看的《Bash 指南》
  • 移动端高清、多屏适配方案
  • ​3ds Max插件CG MAGIC图形板块为您提升线条效率!
  • (04)Hive的相关概念——order by 、sort by、distribute by 、cluster by
  • (C语言)逆序输出字符串
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (二) Windows 下 Sublime Text 3 安装离线插件 Anaconda
  • (紀錄)[ASP.NET MVC][jQuery]-2 純手工打造屬於自己的 jQuery GridView (含完整程式碼下載)...
  • (七)理解angular中的module和injector,即依赖注入
  • (数位dp) 算法竞赛入门到进阶 书本题集
  • (转)EXC_BREAKPOINT僵尸错误
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • .babyk勒索病毒解析:恶意更新如何威胁您的数据安全
  • .equal()和==的区别 怎样判断字符串为空问题: Illegal invoke-super to void nio.file.AccessDeniedException
  • .Net Core和.Net Standard直观理解
  • .Net Winform开发笔记(一)
  • .NET/C# 中你可以在代码中写多个 Main 函数,然后按需要随时切换
  • .net反混淆脱壳工具de4dot的使用
  • .Net各种迷惑命名解释
  • .NET下ASPX编程的几个小问题
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?
  • @value 静态变量_Python彻底搞懂:变量、对象、赋值、引用、拷贝
  • [ CTF ]【天格】战队WriteUp- 2022年第三届“网鼎杯”网络安全大赛(青龙组)
  • [bzoj 3124][sdoi 2013 省选] 直径
  • [C++]unordered系列关联式容器
  • [Codeforces] number theory (R1600) Part.11
  • [emuch.net]MatrixComputations(7-12)
  • [FUNC]判断窗口在哪一个屏幕上