手动使用Handler捕获异常或通过第三方腾讯bugly完成异常捕获(第三方可在bugly里的文档中心查看使用)

1.新建一个UnCatchHandler用于异常捕获

package com.bawei.uncatchhandler;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局捕获异常类,实现Thread.UncaughtExceptionHandler
 * @author hasee
 */
public class UnCatchHandler implements Thread.UncaughtExceptionHandler {
    private static UnCatchHandler mUnCatchHandler;
    private Context mContext;

    /**
     * 一定要写个单例
     * @return
     */
    public static UnCatchHandler getInstance(Context context) {
        if(mUnCatchHandler == null){
            synchronized (UnCatchHandler.class) {
                mUnCatchHandler = new UnCatchHandler(context);
            }
        }
        return mUnCatchHandler;
    }

    private UnCatchHandler(Context context) {
        init(context);
    }

    public void init(Context context) {
        //获取默认的系统异常捕获器
        //把当前的crash捕获器设置成默认的crash捕获器
        Thread.setDefaultUncaughtExceptionHandler(this);
        mContext = context.getApplicationContext();
    }

    /**
     * 保存我们抛出的异常至SD卡
     * @param t
     * @param e
     */
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        try {
            //如果不需要写到SD卡,则不需要打开以下注释
//            saveSD(e);

            //打印异常信息
            Log.i("1607C", e.getLocalizedMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

//    /**
//     * 存储sd卡
//     */
//    private void saveSD(Throwable throwable) throws Exception {
//        //判断SD卡状态
//        //MEDIA_MOUNTED 存储媒体已经挂载,并且挂载点可读/写
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            //彻底退出
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(0);
//            return;
//        }
//
//        //获取手机的一些信息
//        PackageManager pm = mContext.getPackageManager();
//        PackageInfo inFo = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
//
//        //获取版本信息
//        String versionName = inFo.versionName;
//        int versionCode = inFo.versionCode;
//
//        int version_code = Build.VERSION.SDK_INT;
//
//        //Android版本号
//        String release = Build.VERSION.RELEASE;
//        //手机型号
//        String mobile = Build.MODEL;
//
//        //手机制造商
//        String mobileName = Build.MANUFACTURER;
//
//        //存储至sdCard下
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
//
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
//        String time = simpleDateFormat.format(new Date());
//
//        //找到文件夹路径,创建exception文件夹
//        File f = new File(path, "exception");
//        f.mkdirs();
//
//        //找到文件夹路径,查找exception + time的txt文件夹
//        File file = new File(f.getAbsolutePath(), "exception" + time + ".txt");
//
//        //如果文件没有,则创建
//        if (!file.exists()) {
//            file.createNewFile();
//        }
//
//        String data = "\nMobile型号:" + mobile + "\nMobileName:" + mobileName + "\nSDK版本:" + version_code +
//                "\n版本名称:" + versionName + "\n版本号:" + versionCode + "\n异常信息:" + throwable.toString();
//
//        Log.i("dj", data);
//
//        //以下是写入文件
//        byte[] buffer = data.trim().getBytes();
//        FileOutputStream fileOutputStream = new FileOutputStream(file);
//        // 开始写入数据到这个文件。
//        fileOutputStream.write(buffer, 0, buffer.length);
//        fileOutputStream.flush();
//        fileOutputStream.close();
//
//       android.os.Process.killProcess(android.os.Process.myPid());
 //     System.exit(0);
  // }
}

2.建一个全局配置的Application(记住在清单文件注册)

package com.bawei.uncatchhandler;

import android.app.Application;

import com.tencent.bugly.crashreport.CrashReport;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        UnCatchHandler.getInstance(getApplicationContext()).init(getApplicationContext());
         //第三方通过腾讯bugly需要写的
//        CrashReport.initCrashReport(getApplicationContext(), "f9f67393ee", true);
    }
}

3.需要在清单文件注册的权限

//向SD卡写的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
//读取SD卡的权限
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    //读取手机型号的权限
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    //网络权限
    <uses-permission android:name="android.permission.INTERNET" />
    //网络类型的权限
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    //WIFI网络的权限
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    //读取日志的权限
    <uses-permission android:name="android.permission.READ_LOGS"
        tools:ignore="ProtectedPermissions" />

4.第三方通过腾讯bugly完成异常捕获需要的权限

implementation 'com.tencent.bugly:crashreport:latest.release'

猜你喜欢

转载自blog.csdn.net/guoxinyu1207/article/details/84861042