转自: https://blog.csdn.net/cf8833/article/details/92662279

遇到的坑:

  1. 这个东西只能保存崩溃的错误日志,有点局限性
  2. 文件权限申请,文件权限申请,文件权限申请,重要的事情讲三遍,
  3. 这个生成之后的文件,一定要用手机去看,千万不要用电脑,别问题为什么,因为电脑看的那个文件夹没刷新,不显示,还有我们存储路径的wangrusheg 这个东西是可变化的,是你的项目名称,千万不要傻愣愣的一直去找这个文件夹 这个是项目名称,项目名称,项目名称!!!!切记

先看效果图:

1.权限,文件的读写,在清单文件里面,注意,我这里为了方便,没做动态权限申请,你们使用的时候,记得把权限开起来,还有,我们的用到了application,记得在清单文件添加

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.administrator.testz">

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

        <application
            android:name=".App"
            android:allowBackup="true"
            android:icon="@mipmap/icona"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

        </application>

    </manifest>

2.创建App文件

    public class App extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }
    }

3.MainActivity ,只要是模拟一下报错,你们也可以模拟别的错误,界面我就不贴了,就一个button,自己添加

    package com.example.administrator.testz;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;

    import java.util.ArrayList;
    import java.util.List;

    public class MainActivity extends AppCompatActivity {
        private static final String TAG = "MainActivity";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            final Button button2 = (Button) findViewById(R.id.bug);

            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<String> list = new ArrayList<>();

                    String[] strings = CrashHandler.getCrashReportFiles(MainActivity.this);//获取异常文件路径
                    for (int i = 0; i < strings.length; i++) {
                        Log.e(TAG, "onCreate: " + strings[i]);
                    }

                    Log.e(TAG, "onCreate: " + list.get(1));//模拟数组越界
                }
            });

        }
    }

4.日志类

    package com.example.administrator.testz;

    import android.util.Log;

    /**
     * @author DeMon
     * @date 2018/8/14
     * @description
     */
    public class DLog {
        /*m默认不打印Log,如果要打印,置为true*/
        private static boolean enableLog = BuildConfig.DEBUG;

        public static void e(String tag, String msg) {
            if (enableLog)
                Log.e(tag, msg);

        }

        public static void d(String tag, String msg) {
            if (enableLog)
                Log.d(tag, msg);

        }

        public static void i(String tag, String msg) {
            if (enableLog)
                Log.i(tag, msg);

        }

        public static void v(String tag, String msg) {
            if (enableLog)
                Log.v(tag, msg);

        }

        public static void w(String tag, String msg) {
            if (enableLog)
                Log.w(tag, msg);

        }

    }

5.日志写入错误信息类

    package com.example.administrator.testz;

    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.os.Build;
    import android.os.Environment;
    import android.util.Log;

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.io.Writer;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    /**
     * @author DeMon
     * @date 2018/8/14
     * @description
     */
    public class CrashHandler implements Thread.UncaughtExceptionHandler {

        private static final String TAG = "CrashHandler";
        /**
         * 系统默认的UncaughtException处理类
         */
        private Thread.UncaughtExceptionHandler mDefaultHandler;
        /**
         * 程序的Context对象
         */
        private Context mContext;
        /**
         * 错误报告文件的扩展名
         */
        private static final String CRASH_REPORTER_EXTENSION = ".txt";

        /**
         * CrashHandler实例
         */
        private static CrashHandler INSTANCE;

        /**
         * 保证只有一个CrashHandler实例
         */
        private CrashHandler() {
        }

        /**
         * 获取CrashHandler实例 ,单例模式
         */
        public static CrashHandler getInstance() {
            if (INSTANCE == null) {
                synchronized (CrashHandler.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new CrashHandler();
                    }
                }
            }
            return INSTANCE;
        }

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

        /**
         * 当UncaughtException发生时会转入该函数来处理
         */
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            handleException(ex);
            if (mDefaultHandler != null) {
                //收集完信息后,交给系统自己处理崩溃
                mDefaultHandler.uncaughtException(thread, ex);
            }
        }

        /**
         * 自定义错误处理,收集错误信息
         * 发送错误报告等操作均在此完成.
         * 开发者可以根据自己的情况来自定义异常处理逻辑
         */
        private void handleException(Throwable ex) {
            if (ex == null) {
                Log.w(TAG, "handleException--- ex==null");
                return;
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null) {
                return;
            }
            //收集设备信息
            //保存错误报告文件
            saveCrashInfoToFile(ex);
        }

        /**
         * 获取错误报告文件路径
         *
         * @param ctx
         * @return
         */
        public static String[] getCrashReportFiles(Context ctx) {
            File filesDir = new File(getCrashFilePath(ctx));
            String[] fileNames = filesDir.list();
            int length = fileNames.length;
            String[] filePaths = new String[length];
            for (int i = 0; i < length; i++) {
                filePaths[i] = getCrashFilePath(ctx) + fileNames[i];
            }
            return filePaths;
        }

        /**
         * 保存错误信息到文件中
         *
         * @param ex
         * @return
         */
        private void saveCrashInfoToFile(Throwable ex) {
            Writer info = new StringWriter();
            PrintWriter printWriter = new PrintWriter(info);
            ex.printStackTrace(printWriter);
            Throwable cause = ex.getCause();
            while (cause != null) {
                cause.printStackTrace(printWriter);
                cause = cause.getCause();
            }
            String result = info.toString();
            printWriter.close();
            StringBuilder sb = new StringBuilder();
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            String now = sdf.format(new Date());
            sb.append("TIME:").append(now);//崩溃时间
            //程序信息
            sb.append("\nAPPLICATION_ID:").append(BuildConfig.APPLICATION_ID);//软件APPLICATION_ID
            sb.append("\nVERSION_CODE:").append(BuildConfig.VERSION_CODE);//软件版本号
            sb.append("\nVERSION_NAME:").append(BuildConfig.VERSION_NAME);//VERSION_NAME
            sb.append("\nBUILD_TYPE:").append(BuildConfig.BUILD_TYPE);//是否是DEBUG版本
            //设备信息
            sb.append("\nMODEL:").append(android.os.Build.MODEL);
            sb.append("\nRELEASE:").append(Build.VERSION.RELEASE);
            sb.append("\nSDK:").append(Build.VERSION.SDK_INT);
            sb.append("\nEXCEPTION:").append(ex.getLocalizedMessage());
            sb.append("\nSTACK_TRACE:").append(result);
            try {
                FileWriter writer = new FileWriter(getCrashFilePath(mContext) + now + CRASH_REPORTER_EXTENSION);
                writer.write(sb.toString());
                writer.flush();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 获取文件夹路径
         *
         * @param context
         * @return
         */
        private static String getCrashFilePath(Context context) {
            String path = null;
            try {
                path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/"
                        + context.getResources().getString(R.string.app_name) + "/Crash/";
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "getCrashFilePath: " + path);
            return path;
        }
    }

标签: application

添加新评论