当前位置:   article > 正文

Android 捕获全局异常,防止异常闪退,记录异常日志_android studio捕捉错误 不闪退

android studio捕捉错误 不闪退
  1. import android.content.Context;
  2. import android.content.pm.PackageInfo;
  3. import android.content.pm.PackageManager;
  4. import android.content.pm.PackageManager.NameNotFoundException;
  5. import android.os.Build;
  6. import android.os.Looper;
  7. import android.widget.Toast;
  8. import java.io.File;
  9. import java.io.FileNotFoundException;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.lang.Thread.UncaughtExceptionHandler;
  13. import java.lang.reflect.Field;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. /**
  17. * UncaughtException handler class
  18. *
  19. */
  20. public class CrashHandler implements UncaughtExceptionHandler {
  21. public static final String TAG = "CrashHandler";
  22. public static final String PROGRAM_BROKEN_ACTION = "com.teligen.wccp.PROGRAM_BROKEN";
  23. private UncaughtExceptionHandler mDefaultHandler;
  24. private static CrashHandler instance = new CrashHandler();
  25. private Context mContext;
  26. private Class<?> mainActivityClass;
  27. private Map<String, String> infos = new HashMap<String, String>();
  28. private CrashHandler() {
  29. }
  30. public static CrashHandler getInstance() {
  31. return instance;
  32. }
  33. public void init(Context context, Class<?> activityClass) {
  34. mContext = context;
  35. this.setMainActivityClass(activityClass);
  36. mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
  37. Thread.setDefaultUncaughtExceptionHandler(this);
  38. }
  39. @Override
  40. public void uncaughtException(Thread thread, Throwable ex) {
  41. if (!handleException(ex) && mDefaultHandler != null) {
  42. mDefaultHandler.uncaughtException(thread, ex);
  43. } else {
  44. System.out.println("uncaughtException--->" + ex.getMessage());
  45. // Log.e(TAG, ex.getMessage());
  46. logError(ex);
  47. try {
  48. Thread.sleep(3000);
  49. } catch (InterruptedException e) {
  50. // Log.e("debug", "error:", e);
  51. }
  52. exitApp();
  53. }
  54. }
  55. private boolean handleException(Throwable ex) {
  56. if (ex == null) {
  57. return false;
  58. }
  59. new Thread(new Runnable() {
  60. @Override
  61. public void run() {
  62. Looper.prepare();
  63. Toast.makeText(mContext.getApplicationContext(),
  64. "unknown exception and exiting...Please checking logs in sd card!", Toast.LENGTH_LONG).show();
  65. Looper.loop();
  66. }
  67. }).start();
  68. collectDeviceInfo(mContext.getApplicationContext());
  69. logError(ex);
  70. return true;
  71. }
  72. private void exitApp() {
  73. android.os.Process.killProcess(android.os.Process.myPid());
  74. System.exit(0);
  75. }
  76. public void collectDeviceInfo(Context ctx) {
  77. try {
  78. PackageManager pm = ctx.getPackageManager();
  79. PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
  80. PackageManager.GET_ACTIVITIES);
  81. if (pi != null) {
  82. String versionName = pi.versionName == null ? "null"
  83. : pi.versionName;
  84. String versionCode = pi.versionCode + "";
  85. infos.put("versionName", versionName);
  86. infos.put("versionCode", versionCode);
  87. }
  88. } catch (NameNotFoundException e) {
  89. e.printStackTrace();
  90. }
  91. Field[] fields = Build.class.getDeclaredFields();
  92. for (Field field : fields) {
  93. try {
  94. field.setAccessible(true);
  95. infos.put(field.getName(), field.get(null).toString());
  96. } catch (Exception e) {
  97. }
  98. }
  99. }
  100. private void logError(Throwable ex) {
  101. StringBuffer sb = new StringBuffer();
  102. for (Map.Entry<String, String> entry : infos.entrySet()) {
  103. String key = entry.getKey();
  104. String value = entry.getValue();
  105. sb.append(key + "=" + value + "\n");
  106. }
  107. int num = ex.getStackTrace().length;
  108. for (int i=0;i<num;i++){
  109. sb.append(ex.getStackTrace()[i].toString());
  110. sb.append("\n");
  111. }
  112. File file = new File(filePath+"/log.txt");
  113. FileOutputStream fos = null;
  114. try {
  115. fos = new FileOutputStream(file);
  116. fos.write((sb.toString()+"exception:"+ex.getLocalizedMessage()).getBytes());
  117. } catch (FileNotFoundException e) {
  118. e.printStackTrace();
  119. } catch (IOException e) {
  120. e.printStackTrace();
  121. }finally {
  122. try {
  123. fos.close();
  124. } catch (IOException e) {
  125. e.printStackTrace();
  126. }
  127. }
  128. }
  129. public Class<?> getMainActivityClass() {
  130. return mainActivityClass;
  131. }
  132. public void setMainActivityClass(Class<?> mainActivityClass) {
  133. this.mainActivityClass = mainActivityClass;
  134. }
  135. }

filePath是记录日志的路径

在Applicaton中初始化

@Override
public void onCreate() {
    super.onCreate();
    CrashHandler mCrashHandler = CrashHandler.getInstance();
    mCrashHandler.init(getApplicationContext(), getClass());
    initFile();
}

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/245451
推荐阅读
相关标签
  

闽ICP备14008679号