Crash의 수집

첫걸음
충돌 전 시스템에서 API 제공
UncaughtExceptionHandler
 
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler(); //                  Thread.setDefaultUncaughtExceptionHandler(this);

 
 
 
 

 
사용자 정의 프로세서를 사용할 수 있기 때문에, 우리는 이 종류를 계승하여 프로세서를 다시 쓸 수 있다
 
 
 
package com.example.cuizehui.estore.uitls;

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 java.lang.Thread.UncaughtExceptionHandler;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by cuizehui on 17-10-11.
 */
public class CrashHandler implements UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final boolean DEBUG = true;

    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/ryg_test/log/";
    private static final String FILE_NAME = "crash";

    //log      
    private static final String FILE_NAME_SUFFIX = ".trace";

    private static CrashHandler sInstance = new CrashHandler();

    //         (     ,            )
    private UncaughtExceptionHandler mDefaultCrashHandler;

    private Context mContext;

    //      ,          ,       
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return sInstance;
    }

    //           
    public void init(Context context) {
        //            
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        //                 
        Thread.setDefaultUncaughtExceptionHandler(this);
        //  Context,      
        mContext = context.getApplicationContext();
    }

    /**
     *          ,            ,        #uncaughtException  
     * thread           ,ex       ,    ex,           。
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            //       SD  
            dumpExceptionToSDCard(ex);
            //                  ,              bug
            uploadExceptionToServer();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //          
        ex.printStackTrace();

        //               ,             ,            
        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        } else {
            //    
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }

    }

    private void dumpExceptionToSDCard(Throwable ex) throws IOException {
        //  SD         ,          SD 
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.w(TAG, "sdcard unmounted,skip dump exception");
                return;
            }
        }

        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        //       log  
        File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);

        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            //         
            pw.println(time);

            //      
            dumpPhoneInfo(pw);

            pw.println();
            //          
            ex.printStackTrace(pw);

            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump crash info failed");
        }
    }

    private void dumpPhoneInfo(PrintWriter pw) throws PackageManager.NameNotFoundException {
        //           
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App Version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);

        //android   
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        //     
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        //    
        pw.print("Model: ");
        pw.println(Build.MODEL);

        //cpu  
        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

    private void uploadExceptionToServer() {
        //TODO Upload Exception Message To Your Web Server
    }

}

 
이 중 흐름으로 이상 정보를 txt 파일로 출력하거나 서버에 업로드합니다
두 번째 단계
Application에서 초기화하려면 다음과 같이 하십시오.
 
     //              ,                 
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(this);

 
전체 솔루션:
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = CrashHandler.class.getSimpleName();
    private static final boolean DEBUG = true;

    private static final String FILE_NAME = "crash";
    private static final String FILE_NAME_SUFFIX = ".txt";

    private Thread.UncaughtExceptionHandler mDefaultCrashHandler;
    private Context mContext;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return CrashHandlerHolder.INSTANCE;
    }

    public void initialize(Context context) {
        mContext = context.getApplicationContext();
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            dumpExceptionToSDCard(ex);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ex.printStackTrace();

        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        } else {
            android.os.Process.killProcess(Process.myPid());
        }
    }

    private void dumpExceptionToSDCard(Throwable ex) throws FileNotFoundException {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.d(TAG, "sdcard unmounted, skip dump exception");
            }
            return;
        }
        String rootPath = getAppDir(mContext);

        String realPath = rootPath + "/crash/";
        File dir = new File(realPath);
        boolean dirCreated = true;
        if (!dir.exists()) {
            dirCreated = dir.mkdirs();
        }
        if (!dirCreated && DEBUG) {
            Log.e(TAG, "crash dir create failed");
            return;
        }

        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date(current));

        File file = new File(realPath + FILE_NAME + time + FILE_NAME_SUFFIX);

        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            pw.println(time);

            dumpPhoneInfo(pw);

            pw.println();
            ex.printStackTrace(pw);
            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump exception info failed");
        }
    }

    private void dumpPhoneInfo(PrintWriter pw) throws PackageManager.NameNotFoundException {
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App version: ");
        pw.print(pi.versionName);
        pw.print("_");
        pw.println(pi.versionCode);

        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        pw.print("Model: ");
        pw.println(Build.MODEL);

        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

    private static String getAppDir(Context context) {
        File fileDir = context.getExternalCacheDir();
        String dir;
        if (fileDir != null) {
            dir = fileDir.getAbsolutePath();
        } else {
            dir = context.getCacheDir().getAbsolutePath();
        }
        fileDir = new File(dir);
        if (fileDir.exists()) return dir;
        boolean result = fileDir.mkdirs();
        return result ? dir : null;
    }

    private static class CrashHandlerHolder {
        private static final CrashHandler INSTANCE = new CrashHandler();
    }
}public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = CrashHandler.class.getSimpleName();
    private static final boolean DEBUG = true;

    private static final String FILE_NAME = "crash";
    private static final String FILE_NAME_SUFFIX = ".txt";

    private Thread.UncaughtExceptionHandler mDefaultCrashHandler;
    private Context mContext;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return CrashHandlerHolder.INSTANCE;
    }

    public void initialize(Context context) {
        mContext = context.getApplicationContext();
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            dumpExceptionToSDCard(ex);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ex.printStackTrace();

        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        } else {
            android.os.Process.killProcess(Process.myPid());
        }
    }

    private void dumpExceptionToSDCard(Throwable ex) throws FileNotFoundException {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.d(TAG, "sdcard unmounted, skip dump exception");
            }
            return;
        }
        String rootPath = getAppDir(mContext);

        String realPath = rootPath + "/crash/";
        File dir = new File(realPath);
        boolean dirCreated = true;
        if (!dir.exists()) {
            dirCreated = dir.mkdirs();
        }
        if (!dirCreated && DEBUG) {
            Log.e(TAG, "crash dir create failed");
            return;
        }

        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date(current));

        File file = new File(realPath + FILE_NAME + time + FILE_NAME_SUFFIX);

        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            pw.println(time);

            dumpPhoneInfo(pw);

            pw.println();
            ex.printStackTrace(pw);
            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump exception info failed");
        }
    }

    private void dumpPhoneInfo(PrintWriter pw) throws PackageManager.NameNotFoundException {
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App version: ");
        pw.print(pi.versionName);
        pw.print("_");
        pw.println(pi.versionCode);

        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        pw.print("Model: ");
        pw.println(Build.MODEL);

        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

    private static String getAppDir(Context context) {
        File fileDir = context.getExternalCacheDir();
        String dir;
        if (fileDir != null) {
            dir = fileDir.getAbsolutePath();
        } else {
            dir = context.getCacheDir().getAbsolutePath();
        }
        fileDir = new File(dir);
        if (fileDir.exists()) return dir;
        boolean result = fileDir.mkdirs();
        return result ? dir : null;
    }

    private static class CrashHandlerHolder {
        private static final CrashHandler INSTANCE = new CrashHandler();
    }
}

 
 
 
요약:
현재 시장에서는 3자 플랫폼 관리crash log./아니면 로컬을 완벽하게 하고 LOG를 분류하고 무게를 제외하고
텐센트의 Bugly 동맹 플랫폼 등
 
이 클래스는 붕괴 전에 사용자 매개 변수 정보를 보존하는 데도 사용할 수 있습니다.

좋은 웹페이지 즐겨찾기