1. 程式人生 > >關於如何獲取上線後的app異常資訊(bug)處理

關於如何獲取上線後的app異常資訊(bug)處理

  • 首先是在Application中實現介面
public class App extends Application {
//記得在清單檔案註冊App的name
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new MYExceptionHandler());
    }
    /**
     * 當app出現異常就會走下面的方法!!!
     * */
    class  MYExceptionHandler implements Thread.UncaughtExceptionHandler{

        @Override
public void uncaughtException(Thread thread, Throwable throwable) { if (throwable != null) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); throwable.printStackTrace(printWriter); String errorReport = result.toString(); Log.d("-<<<<>"
, errorReport); //這裡吧errorReport post到http去就行了!!! //... //或者儲存檔案到sd卡中 saveInFile(errorReport ); //最後殺死自己 android.os.Process.killProcess(android.os.Process.myPid()); } } } private
void saveInFile(String errorReport) { FileOutputStream out = null ; File file = new File(Environment.getExternalStorageDirectory() , "error-log.txt"); if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ try { out = new FileOutputStream(file); out.write(errorReport.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
  • 我這個專案是如果異常了,就再次啟動自己
//在這個方法裡啟動另一個activity
 public void uncaughtException(Thread thread, Throwable ex) {
        if (ex != null) {
            final Writer result = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(result);
            ex.printStackTrace(printWriter);
            String errorReport = result.toString();
            Log.d("-<<<<>" , errorReport); 

            //上傳http

            Intent intent = new Intent("com.dopool.devinstall.TwoActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(CATCH_EXCEPTION, errorReport);
            mContent.startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());