Android error messages are captured and sent to the server [original]

Source: Internet
Author: User

ProgramThe biggest headache for Members is Bug and debug. This debug lasted 20 days, and I made a failover. Tired, because of Android compatibility, different mobile phones may have different bugs, and it is difficult to reproduce, So I went online and found a similar error log to save it to the file and then upload it to the server, the source code is also shared. TheCodeI did not add. I believe everyone has ready-made code.

First, let's talk about the principle. Like the custom exception capture of javaee, the error is always thrown up and then processed at the top. The exception message can be obtained and saved.

The exception capture class is as follows:

/*** @ Author stay * uniformly captures exceptions in the application and stores them in the file for the next time and then uploads the file */public class crashhandler implements uncaughtexceptionhandler {/** whether to enable log output, enable in debug state, * disable in release state to prompt program performance **/public static final Boolean DEBUG = true; /** default uncaughtexception class */private thread. uncaughtexceptionhandler mdefaulthandler;/** crashhandler instance */Private Static crashhandler instance;/** context object of the Program * // Private con Text mcontext;/** ensure that there is only one crashhandler instance */private crashhandler () {}/ ** to obtain the crashhandler instance. Singleton mode */public static crashhandler getinstance () {If (instance = NULL) {instance = new crashhandler ();} return instance;}/*** initialize, register the context object, and * obtain the default uncaughtexception processor of the system, * set the crashhandler as the default processor of the program ** @ Param CTX */Public void Init (context CTX) {// mcontext = CTX; mdefaulthandler = thread. getdefau Ltuncaughtexceptionhandler (); thread. setdefaultuncaughtexceptionhandler (this);}/*** when uncaughtexception occurs, it will be transferred to this function for processing */@ override public void uncaughtexception (thread, throwable ex) {If (! Handleexception (Ex) & mdefaulthandler! = NULL) {// if the user does not process the mdefaulthandler, the system's default exception processor is used to process the mdefaulthandler. uncaughtexception (thread, ex);} else {// if you have handled the exception yourself, the error dialog box does not pop up. You need to manually exit the app try {thread. sleep (3000);} catch (interruptedexception e) {} android. OS. process. killprocess (Android. OS. process. mypid (); system. exit (10) ;}/ *** custom error handling, collecting error information * Sending error reports and other operations are completed here. * developers can customize the exception handling logic based on their own situations * @ return * true indicates that the exception is handled and no exception is thrown up, * false indicates that the exception is not handled (the log information can be stored) and then handed over to the upper layer (here the Exception Processing of the system is implemented) for processing, * Simply put, "true" does not bring up the error prompt box, and "false" will pop up */private Boolean handleexception (final throwable ex) {If (EX = NULL) {return false ;} // final string MSG = ex. getlocalizedmessage (); Final stacktraceelement [] stack = ex. getstacktrace (); final string message = ex. getmessage (); // use toast to display the exception information new thread () {@ override public void run () {loid. prepare (); // toast. maketext (mcontext, "program error:" + message, toast. length_long ). show (); // only one file can be created, and all files will be appended and sent to the file later. In this way, duplicate information will be generated. We do not recommend string filename = "crash-" + system. currenttimemillis () + ". log "; file = new file (environment. getexternalstoragedirectory (), filename); try {fileoutputstream Fos = new fileoutputstream (file, true); FOS. write (message. getbytes (); For (INT I = 0; I <stack. length; I ++) {FOS. write (stack [I]. tostring (). getbytes ();} FOS. flush (); FOS. close ();} catch (exception e) {} logoff. loop ();}}. start (); Return false;} // todo uses http post to send an error report to the server. This will not be detailed here // Private void postreport (File file) {// when uploading, you can also send the version of the app, the model of the mobile phone, and other information to the server. // Android compatibility is well known, therefore, the error may not be reported on every mobile phone, but it is better to debug it //}}

Register exceptionhandler in application oncreate, which can be captured after the program throws an exception.

 
Public class app extends application {@ override public void oncreate () {super. oncreate (); crashhandler = crashhandler. getinstance (); // register crashhandler. init (getapplicationcontext ());}}
 
Public class logactivity extends activity {@ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); try {// create bugfile file = new file (environment. getexternalstoragestate (), "Crash. bin "); fileinputstream FCM = new fileinputstream (File); byte [] buffer = new byte [1024]; FCM. read (buffer);} catch (exception e) {// no exception can be thrown up here. If you want to save the log information, a runtime exception is thrown, // capture the Custom Handler and save the file in a unified manner. Upload throw new runtimeexception (e );}}}

NOTE: If no throw is triggered after a catch operation, it is handled by yourself by default. exceptionhandler will not catch exceptions.

To share a log encapsulation class, you only need to set the debug value here so that the console can print the log

 
Public class debugutil {public static final string tag = "icon"; public static final Boolean DEBUG = true; public static void toast (context, string content) {toast. maketext (context, content, toast. length_short ). show ();} public static void debug (string tag, string MSG) {If (Debug) {log. D (TAG, MSG) ;}} public static void debug (string MSG) {If (Debug) {log. D (TAG, MSG) ;}} public static void error (string tag, string error) {log. E (TAG, error);} public static void error (string error) {log. E (TAG, error );}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.