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

Android teaches you how to interact with WebView and JS in five minutes

[[189497]] Background: Android API provides WebVi...

The self-redemption and helplessness of a sunset product

Every product has its life cycle. After going thr...

What is the black technology to save 16/32GB iPhone APFS?

There is hope for iPhone users with 16GB of stora...

How to create content that goes viral on WeChat Moments? Be logical!

You are interested in content operation , you can...

How to formulate e-commerce promotion and marketing strategies?

During shopping carnivals such as Double Eleven a...

Samsung Mobile Business President: To regain China's top customers are operators

According to the technology website ZDNet, after ...

2 pictures to help you understand Toutiao's recommendation system

The “predecessors” of recommendation systems In 2...

How to create a personal IP? 3800 words super detailed tutorial

I thought about a hundred or eighty projects, but...

Baoneng emerges as buyer of Pangda in crisis

Following Evergrande's 14.5 billion yuan inve...

Brand Spring Festival Marketing War

There are less than 3 weeks left until the 2022 S...