Android全局异常处理

自定义一个application

public class MyApplication extends Application {


    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        this.mContext = this;
        CrashHandler.getInstance().init(this);
    }

    public static Context getContext(){
        return mContext;
    }
}

写上CrashHandler类

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    /**
     * 系统默认UncaughtExceptionHandler
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    //日志文件夹
    private String LOG_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/shengxun/log/";
    private File logTxt;

    /**
     * context
     */
    private Context mContext;

    private static CrashHandler mInstance;

    private CrashHandler() {

    }

    /**
     * 获取CrashHandler实例
     */
    public static synchronized CrashHandler getInstance() {
        if (null == mInstance) {
            mInstance = new CrashHandler();
        }
        return mInstance;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * uncaughtException 回调函数
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //导出到SD卡
        dumpExceptonToSDCard(ex);

        //得到异常信息字符串
        String exceptionInfoStr = getExceptionInfoStr();

        //上传服务器
        uploadToServer(exceptionInfoStr);

        //如果系统提供的默认的异常处理器,让系统去处理
        if (null != mDefaultHandler) {
            mDefaultHandler.uncaughtException(thread, ex);
        }else {
            Process.killProcess(Process.myPid());
        }
    }


    /**
     * 上传信息到服务器
     * @param infoStr
     */
    private void uploadToServer(String infoStr) {

    }

    /**
     * 导出到sd卡,需要写入SD卡权限 如果无法写入。请查看APP设置是否有权限
     */
    private void dumpExceptonToSDCard(Throwable ex) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }

        File file = new File(LOG_DIR);
        if (!file.exists()) {
            if(!file.mkdirs()){
                return;
            }
        }

        long currentTimeMillis = System.currentTimeMillis();
        String format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").format(currentTimeMillis);
        logTxt = new File(LOG_DIR + format + ".txt");

        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(logTxt)));
            pw.println(format);
            phoneInfo(pw);
            pw.println();
            ex.printStackTrace(pw);
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //设备的信息
    private void phoneInfo(PrintWriter pw) throws PackageManager.NameNotFoundException {
        PackageManager pm = mContext.getPackageManager();

        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_RECEIVERS);
        pw.println("App Version:" + pi.versionName);
        pw.println("AppCode:" + pi.versionCode);
        pw.println("OS version :" + Build.VERSION.RELEASE + "_" + Build.VERSION.SDK_INT);
        pw.println("Vendor:" + Build.MANUFACTURER);
        pw.println("Model:" + Build.MODEL);
    }

    //返回异常信息字符串
    private String getExceptionInfoStr() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(logTxt));
            String str = "";
            StringBuilder sb = new StringBuilder();

            while ((str = bufferedReader.readLine()) != null) {
                sb.append("\n");
                sb.append(str);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "异常信息文件文件未找到";
    }

}

简单模拟异常

  public void  clickBtn(View view) throws Exception {
        throw  new Exception("模拟异常");
  }

你可能感兴趣的:(Android全局异常处理)