首页 > 技术文章 > Android application捕获崩溃异常

jeffen 2017-06-09 10:45 原文

Java代码
  1. 个人笔记:  
  2. 通用 application  
  3. 1、收集所有 avtivity 用于彻底退出应用  
  4. 2、捕获崩溃异常,保存错误日志,并重启应用  
  5.   
  6.   
  7. public class HKBaseApplication extends Application {  
  8.     // activity对象列表,用于activity统一管理  
  9.     private List<Activity> activityList;  
  10.     // 异常捕获  
  11.     protected boolean isNeedCaughtExeption = true;// 是否捕获未知异常  
  12.     private PendingIntent restartIntent;  
  13.     private MyUncaughtExceptionHandler uncaughtExceptionHandler;  
  14.     private String packgeName;  
  15.   
  16.     @Override  
  17.     public void onCreate() {  
  18.         super.onCreate();  
  19.   
  20.         activityList = new ArrayList<Activity>();  
  21.         packgeName = getPackageName();  
  22.   
  23.         if (isNeedCaughtExeption) {  
  24.             cauchException();  
  25.         }  
  26.     }  
  27.   
  28.     // -------------------异常捕获-----捕获异常后重启系统-----------------//  
  29.   
  30.     private void cauchException() {  
  31.         Intent intent = new Intent();  
  32.         // 参数1:包名,参数2:程序入口的activity  
  33.         intent.setClassName(packgeName, packgeName + ".LoginActivity");  
  34.         restartIntent = PendingIntent.getActivity(getApplicationContext(), -1, intent,  
  35.                 Intent.FLAG_ACTIVITY_NEW_TASK);  
  36.   
  37.         // 程序崩溃时触发线程  
  38.         uncaughtExceptionHandler = new MyUncaughtExceptionHandler();  
  39.         Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);  
  40.     }  
  41.   
  42.     // 创建服务用于捕获崩溃异常  
  43.     private class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {  
  44.         @Override  
  45.         public void uncaughtException(Thread thread, Throwable ex) {  
  46.             // 保存错误日志  
  47.             saveCatchInfo2File(ex);  
  48.   
  49.             // 1秒钟后重启应用  
  50.             AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);  
  51.             mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);  
  52.   
  53.             // 关闭当前应用  
  54.             finishAllActivity();  
  55.             finishProgram();  
  56.         }  
  57.     };  
  58.   
  59.     /** 
  60.      * 保存错误信息到文件中 
  61.      *  
  62.      * @return 返回文件名称 
  63.      */  
  64.     private String saveCatchInfo2File(Throwable ex) {  
  65.         Writer writer = new StringWriter();  
  66.         PrintWriter printWriter = new PrintWriter(writer);  
  67.         ex.printStackTrace(printWriter);  
  68.         Throwable cause = ex.getCause();  
  69.         while (cause != null) {  
  70.             cause.printStackTrace(printWriter);  
  71.             cause = cause.getCause();  
  72.         }  
  73.         printWriter.close();  
  74.         String sb = writer.toString();  
  75.         try {  
  76.             DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");  
  77.             String time = formatter.format(new Date());  
  78.             String fileName = time + ".txt";  
  79.             System.out.println("fileName:" + fileName);  
  80.             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
  81.                 String filePath = Environment.getExternalStorageDirectory() + "/HKDownload/" + packgeName  
  82.                         + "/crash/";  
  83.                 File dir = new File(filePath);  
  84.                 if (!dir.exists()) {  
  85.                     if (!dir.mkdirs()) {  
  86.                         // 创建目录失败: 一般是因为SD卡被拔出了  
  87.                         return "";  
  88.                     }  
  89.                 }  
  90.                 System.out.println("filePath + fileName:" + filePath + fileName);  
  91.                 FileOutputStream fos = new FileOutputStream(filePath + fileName);  
  92.                 fos.write(sb.getBytes());  
  93.                 fos.close();  
  94.                 //文件保存完了之后,在应用下次启动的时候去检查错误日志,发现新的错误日志,就发送给开发者  
  95.             }  
  96.             return fileName;  
  97.         } catch (Exception e) {  
  98.             System.out.println("an error occured while writing file..." + e.getMessage());  
  99.         }  
  100.         return null;  
  101.     }  
  102.   
  103.     // ------------------------------activity管理-----------------------//  
  104.   
  105.     // activity管理:从列表中移除activity  
  106.     public void removeActivity(Activity activity) {  
  107.         activityList.remove(activity);  
  108.     }  
  109.   
  110.     // activity管理:添加activity到列表  
  111.     public void addActivity(Activity activity) {  
  112.         activityList.add(activity);  
  113.     }  
  114.   
  115.     // activity管理:结束所有activity  
  116.     public void finishAllActivity() {  
  117.         for (Activity activity : activityList) {  
  118.             if (null != activity) {  
  119.                 activity.finish();  
  120.             }  
  121.         }  
  122.     }  
  123.   
  124.     // 结束线程,一般与finishAllActivity()一起使用  
  125.     // 例如: finishAllActivity;finishProgram();  
  126.     public void finishProgram() {  
  127.         android.os.Process.killProcess(android.os.Process.myPid());  
  128.     }  
  129. }  

来源: http://zheyiw.iteye.com/blog/1670990


来自为知笔记(Wiz)


推荐阅读