Android 全局捕捉异常Crash日志

实现自己的崩溃日志管理,捕捉全局异常,方便检查错误发生地。

先附上申请权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

6.0 以上自行动态申请权限。

用到的库:

android 工具类

依赖:

  implementation 'com.blankj:utilcode:1.19.0'

收集收集信息:

 /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                mInfo.put("versionName", versionName);
                mInfo.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mInfo.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

这里mInfo :

  /**
     * 采集信息
     */
    private Map<String ,String> mInfo = new HashMap<>();

保存信息:

/**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称,便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : mInfo.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);
        try {
            String time = dateFormat.format(new Date());
            String fileName = time + ".txt";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = Environment.getExternalStorageDirectory().toString()+"/crash_demo";
                        //AppSettings.CrashLogPath;
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //FileWriter fileWriter = new FileWriter(path + fileName);
                FileOutputStream fos = new FileOutputStream(path +"/"+ fileName);
                //fileWriter.write(sb.toString());
                fos.write(sb.toString().getBytes("UTF-8"));
                fos.close();
                //fileWriter.close();
            }
            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
        return null;
    }

CrashHandler全部代码:

public class CrashHandler implements Thread.UncaughtExceptionHandler {


    private static final String TAG = "CrashHandler";
    
    private static CrashHandler crashHandler ;
    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler ;

    private Context mContext ;

    /**
     * 采集信息
     */
    private Map<String ,String> mInfo = new HashMap<>();

    /**
     * 文件日期
     */
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 单例
     */
    private CrashHandler()
    {

    }

    /**
     * 懒汉式单例
     * @return
     */
    public static CrashHandler getCrashHandler()
    {
        if(crashHandler == null)
        {
            synchronized (CrashHandler.class)
            {
                if(crashHandler == null)
                {
                    crashHandler = new CrashHandler();
                }
            }
        }

        return crashHandler ;
    }


    /**
     * 初始化
     * @param context
     */
    public void init(Context context)
    {
        mContext = context ;
        uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {

        if(!handlerException(throwable))
        {
            if(uncaughtExceptionHandler != null)
            {
                uncaughtExceptionHandler.uncaughtException(thread,throwable);
            }
        }else
        {

            try {
                Thread.sleep(1000);
                // 退出程序
                ActivityUtils.finishAllActivities();
                Process.killProcess(Process.myPid());
                System.exit(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean handlerException(Throwable throwable)
    {
        if(throwable == null)
        {
            return false ;
        }
        new Thread()
        {
            @Override
            public void run() {

                Looper.prepare();
                Toast.makeText(mContext,"异常",Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        collectDeviceInfo(mContext);
        saveCrashInfo2File(throwable);
        return true ;
    }
}

Application 配置:

public class CrashApplication extends Application {

    private CrashHandler crashHandler ;
    @Override
    public void onCreate() {
        super.onCreate();
        crashHandler = CrashHandler.getCrashHandler();
        crashHandler.init(this);
        Utils.init(this);
    }
}

当异常出现的时候就可以到/crash_demo 文件夹下找相应的txt 文件,查找log。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值