Android application source code captures global exceptions

Android application source code captures global exceptions

Source code introduction

This project is a simple example of global exception capture. After capturing the exception, the exception information can be written to a file for later analysis or prompted in a friendly manner before exiting the program.
Source code running screenshot

Source code snippet:

  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. // Used to store device information and exception information  
  7. private Map<string, string= "" > infos = new HashMap<string, string= "" >();
  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. * Synchronization method to avoid exceptions in a single-threaded environment
  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. * Initialize and set the current object to the UncaughtExceptionHandler processor
  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. //Handling exceptions, we can also write exception information to a file for later analysis.  
  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, "Program exception, exit immediately", 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( "Tears prompt" ).setCancelable( false ).setMessage( "My Lord, I am broken..." )
  59. .setNeutralButton( "I know" , 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. * Save error information to a file
  73. *
  74. * @param ex
  75. * @return Returns the file name to facilitate transferring the file to the server
  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<string, string= "" > 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 occurred while writing file..." , e);
  119. }
  120.     
  121. return   null ;
  122. }
  123. }</string,></string,></string,>

Source code link: http://download..com/data/1980812

<<:  How Cook Kills Android

>>:  Android multi-threaded breakpoint download

Recommend

There are fewer and fewer people who can write good copy

I must state in advance that this is just my pers...

9 practical methods behind the hot new media headlines!

It is said that a good title is half the battle o...

How to think about operations during the epidemic?

It has been 2 months since I stopped publishing, ...

Regarding "user growth", these may be things you don't know

Judging from the current situation, the domestic ...

How to use video marketing to let customers fully understand your products?

A marketing activity that uses video as the main ...

Quantum computers: a three-step leap from the laboratory to changing the world

Quantum computers have been one of the hottest st...

Tesla's solar glass for Model 3 can melt snow

Solar energy technology has been applied in vario...

Increase followers, promotion, IP building, and Weibo operation skills!

Weibo is a social networking platform with great ...

Can farmers pay social security? How should I pay? What are the payment methods?

Every year, many farmers have headaches because o...

Pitfalls you may encounter when using Android notifications

I've recently encountered some issues with An...