Android应用源码之捕获全局异常
创始人
2025-01-10 05:20:57
0

源码简介

本项目就是一个简单的全局异常捕捉例子,捕捉到异常以后可以把异常信息写入文件以供后来分析或者用友好的方式进行提示后再退出程序。
源码运行截图

源码片段:

  1. public class UncaughtException implements UncaughtExceptionHandler { 
  2.     private final static String TAG = "UncaughtException"; 
  3.     private static UncaughtException mUncaughtException; 
  4.     private Context context; 
  5.     private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");  
  6.     // 用来存储设备信息和异常信息  
  7.     private Map infos = new HashMap();  
  8.     public Context getContext() { 
  9.         return context; 
  10.     } 
  11.   
  12.     public void setContext(Context context) { 
  13.         this.context = context; 
  14.     } 
  15.   
  16.     private UncaughtException() { 
  17.         // TODO Auto-generated constructor stub 
  18.     } 
  19.   
  20.     /** 
  21.      * 同步方法,以免单例多线程环境下出现异常 
  22.      * 
  23.      * @return 
  24.      */ 
  25.     public synchronized static UncaughtException getInstance() { 
  26.         if (mUncaughtException == null) { 
  27.             mUncaughtException = new UncaughtException(); 
  28.         } 
  29.         return mUncaughtException; 
  30.     } 
  31.   
  32.     /** 
  33.      * 初始化,把当前对象设置成UncaughtExceptionHandler处理器 
  34.      */ 
  35.     public void init() { 
  36.         Thread.setDefaultUncaughtExceptionHandler(mUncaughtException); 
  37.     } 
  38.   
  39.     @Override 
  40.     public void uncaughtException(Thread thread, Throwable ex) { 
  41.         // TODO Auto-generated method stub 
  42.         //处理异常,我们还可以把异常信息写入文件,以供后来分析。 
  43.        saveCrashInfo2File(ex); 
  44.         Log.e(TAG, "uncaughtException thread : " + thread + "||name=" + thread.getName() + "||id=" + thread.getId() + "||exception=" + ex); 
  45.    /*   Looper.prepare(); 
  46.         Toast.makeText(context, "程序异常,立即退出", 1).show(); 
  47.       System.exit(0); 
  48.         Looper.loop();*/ 
  49.           
  50.          showDialog() ; 
  51.     } 
  52.   
  53.     private void showDialog() { 
  54.         new Thread() { 
  55.             @Override 
  56.             public void run() { 
  57.                 Looper.prepare(); 
  58.                 new AlertDialog.Builder(context).setTitle("泪奔提示").setCancelable(false).setMessage("大爷我崩溃了...") 
  59.                         .setNeutralButton("我知道了", new OnClickListener() { 
  60.                             @Override 
  61.                             public void onClick(DialogInterface dialog, int which) { 
  62.                                 System.exit(0); 
  63.                                   
  64.                             } 
  65.                         }).create().show(); 
  66.                 Looper.loop(); 
  67.             } 
  68.         }.start(); 
  69.     } 
  70.       
  71.     /** 
  72.      * 保存错误信息到文件中 
  73.     * 
  74.      * @param ex 
  75.      * @return  返回文件名称,便于将文件传送到服务器 
  76.      */  
  77.     private String saveCrashInfo2File(Throwable ex) {  
  78.         StringBuffer sb = new StringBuffer(); 
  79.          
  80.         long timestamp = System.currentTimeMillis();  
  81.         String time = formatter.format(new Date()); 
  82.         sb.append("\n"+time+"----"); 
  83.         for (Map.Entry entry : infos.entrySet()) {  
  84.             String key = entry.getKey();  
  85.             String value = entry.getValue();  
  86.             sb.append(key + "=" + value + "\n");  
  87.         }  
  88.     
  89.         Writer writer = new StringWriter();  
  90.         PrintWriter printWriter = new PrintWriter(writer);  
  91.         ex.printStackTrace(printWriter);  
  92.         Throwable cause = ex.getCause();  
  93.         while (cause != null) {  
  94.             cause.printStackTrace(printWriter);  
  95.             cause = cause.getCause();  
  96.         }  
  97.         printWriter.close();  
  98.     
  99.         String result = writer.toString();  
  100.         sb.append(result);  
  101.         try {  
  102.                
  103.             String fileName = "exception.log";  
  104.                 
  105.             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
  106.                 String path = "/sdcard/crash/";  
  107.                 File dir = new File(path);  
  108.                 if (!dir.exists()) {  
  109.                     dir.mkdirs();  
  110.                 }  
  111.                 FileOutputStream fos = new FileOutputStream(path + fileName,true);  
  112.                 fos.write(sb.toString().getBytes());  
  113.                 fos.close();  
  114.             }  
  115.     
  116.             return fileName;  
  117.         } catch (Exception e) {  
  118.             Log.e(TAG, "an error occured while writing file...", e);  
  119.         }  
  120.     
  121.         return null;  
  122.     }  

源码链接:http://down.51cto.com/data/1980812

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
粉嫩如何诠释霸道 东芝M805... “霸道粉”是个什么玩意东芝M805拿过来的时候,笔者扑哧笑了,不是笑这款笔记本,而是笑这款产品的颜色...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
全面诠释网络负载均衡 负载均衡的出现大大缓解了服务器的压力,更是有效的利用了资源,提高了效率。那么我们现在来说一下网络负载...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
30分钟搞定iOS自定义相机 最近公司的项目中用到了相机,由于不用系统的相机,UI给的相机切图,必须自定义才可以。就花时间简单研究...
Intel将Moblin社区控... 本周二,非营利机构Linux基金会宣布,他们将担负起Moblin社区的管理工作,而这之前,Mobli...