【Android】崩潰日志

用戶使用應(yīng)用出現(xiàn)異常后,會由默認(rèn)的異常處理器來處理異常。
這導(dǎo)致難以定位問題,我們要做的就是把這個任務(wù)接管過來,自己處理異常,包括收集日志,保存到本地,然后上傳到服務(wù)器。為了方便,使用第三方:bugly

下面是自己處理異常的方法,自定義類實(shí)現(xiàn)接口Thread.UncaughtExceptionHandler

在Application引用
CrashHandler.getInstance().init(this);

日志收集方法,記得申請寫入權(quán)限,上傳至服務(wù)器需自行處理。

/**
 * 描述:崩潰日志采集類
 */
@SuppressLint("SimpleDateFormat")
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";

    private static final String crashPath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "Crash" + File.separator;

    private static CrashHandler instance;

    private Thread.UncaughtExceptionHandler mDefaultHandler;    //系統(tǒng)默認(rèn)UncaughtExceptionHandler

    private Context mContext;

    private Map<String, String> infos = new HashMap<>();    //用于存儲設(shè)備信息與異常信息

    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    private CrashHandler() { }

    public static CrashHandler getInstance() {
        if(instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }

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

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if(!handleException(throwable) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, throwable);
            Log.e(TAG,"程序崩潰,走mDefaultHandler.uncaughtException(##-if-##):",throwable);
        } else {

//            AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
//
//            Intent intent = new Intent(mContext, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.putExtra("crash", true);
//            PendingIntent restartIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒鐘后重啟應(yīng)用
//
//            android.os.Process.killProcess(android.os.Process.myPid());
            Log.e(TAG,"程序崩潰,走system.exit(##-else-##):",throwable);
            System.exit(0);
            System.gc();

        }
    }

    /* 自定義錯誤處理,錯誤信息采集,日志文件保存,如果處理了返回True,否則返回False */
    private boolean handleException(Throwable throwable) {
        if(throwable == null) return false;
        try {
            new Thread(){
                @Override
                public void run() {
                    Looper.prepare();
                    Toast.makeText(mContext,"程序出現(xiàn)異常,即將關(guān)閉.", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }.start();
            getDeviceInfo(mContext);
            saveCrashInfoToFile(throwable);
            SystemClock.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /* 把錯誤信息寫入到文件中,返回文件名稱 */
    private String saveCrashInfoToFile(Throwable throwable) throws Exception {
        StringBuilder sb = new StringBuilder();
        try {
            //拼接時間
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sDateFormat.format(new java.util.Date());
            sb.append("\r\n").append(date).append("\n");
            //拼接版本信息與設(shè)備信息
            for (Map.Entry<String, String> entry : infos.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key).append("=").append(value).append("\n");
            }
            //獲取崩潰日志信息
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            throwable.printStackTrace(printWriter);
            printWriter.flush();
            printWriter.close();
            String result = writer.toString();
            //拼接日志奔潰信息
            sb.append(result);
            //寫入到文件中
            return writeFile(sb.toString());

        } catch (Exception e) {
            //異常處理
            Log.e(TAG, "an error occured while writing file...", e);
            sb.append("an error occured while writing file...\r\n");
            writeFile(sb.toString());
        }
        return null;
    }

    /* 獲取Crash文件夾的存儲路徑 */
//    private static String getGlobalPath() {
//        return Environment.getExternalStorageDirectory().getAbsolutePath()
//                + File.separator + "Crash" + File.separator;
//    }

    /* 將字符串寫入日志文件,返回文件名 */
    private String writeFile(String sb) throws Exception {
        String time = formatter.format(new Date());
        //文件名
        String fileName = "crash-" + time + ".logo";
        //判斷存儲卡是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            String path = getGlobalPath();
            File dir = new File(crashPath);
            //判斷crash目錄是否存在
            if (!dir.exists()) dir.mkdirs();
            //流寫入
            FileOutputStream fos = new FileOutputStream(crashPath + fileName, true);
            fos.write(sb.getBytes());
            fos.flush();
            fos.close();
        }
        return fileName;
    }

    /* 采集應(yīng)用版本與設(shè)備信息 */
    private void getDeviceInfo(Context context) {
        //獲取APP版本
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            if(info != null) {
                infos.put("VersionName",info.versionName);
                infos.put("VersionCode",info.versionCode + "");
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info");
        }
        //獲取系統(tǒng)設(shè)備相關(guān)信息
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field: fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect package info");
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容