Android Uncaughtexceptionhandler, capturing errors

Source: Internet
Author: User
Tags throwable

Recently, in a project, you need to do something when the program crash and errors cause the program to run, and find a way

Thread.setdefaultuncaughtexceptionhandler (new Uncaughtexceptionhandler () {//  Set a handlerpublic                        voidfinal  Throwable ex) for the main thread to handle runtime exceptions {                                Ex.printstacktrace ();                                 // when the program appears crash, it will enter here, you can do some operations here, and then put System.exit (0); //                         }                });

Checked the JDK, as explained below.
public static void Setdefaultuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh) sets when a thread terminates abruptly because of an uncaught exception. And there is no default handler that is called when other handlers are defined for the thread.
Uncaught exception handling is first controlled by the thread, then controlled by the thread's Threadgroup object, and finally by the uncaught default exception handler. If the thread does not set an explicit uncaught exception handler, and the thread Group of the thread (including the parent thread group) does not specifically specify its Uncaughtexception method, the default handler's Uncaughtexception method is called.

By setting the default exception handlers that are not caught, the application can change the uncaught exception handling (such as logging to a specific device or file) for threads that have accepted any "default" behavior provided by the system.

Note that the default exception handler that is not caught should generally not conform to the thread's Threadgroup object, because this can lead to infinite recursion.


Parameters:
Eh-the object that is used as the default exception handler that is not caught. If NULL, there is no default handler.

On the internet to find a more detailed use of this use, the following content is reproduced

The most frustrating thing for programmers is bug and Debug. This debug lasted 20 days, and I was exhausted. Tired, because of Android compatibility, different phones will have different bugs come out, and it is difficult to reproduce, so on the internet to find a similar save error log to the file and then uploaded to the server, now the source is also shared. The code I uploaded to the server was not added. I believe we all have ready-made code.

The first principle, like the Java EE Custom exception capture, throws the error up, and then the top-level uniform processing. Here you can get the exception Message, save the operation

The exception capture classes are as follows:

/** * @authorStay * Uniform catch exception in application, save to file upload next time you open*/ Public classCrashhandlerImplementsUncaughtexceptionhandler {/**whether to turn on the log output, open in the debug state, * Turn off in the release state to prompt for program performance **/       Public Static Final BooleanDEBUG =true; /**system default Uncaughtexception processing class*/      PrivateThread.uncaughtexceptionhandler Mdefaulthandler; /**Crashhandler Instances*/      Private StaticCrashhandler INSTANCE; /**context object for the program*/  //private Context Mcontext;     /**guaranteed only one Crashhandler instance*/      PrivateCrashhandler () {}/**get Crashhandler instances, Singleton mode*/       Public StaticCrashhandler getinstance () {if(INSTANCE = =NULL) {INSTANCE=NewCrashhandler (); }           returnINSTANCE; }           /*** Initialize, register the context object, * Get the system default Uncaughtexception processor, * Set the Crashhandler as the default processor for the program * *@paramCTX*/       Public voidInit (Context ctx) {//mcontext = CTX; Mdefaulthandler =Thread.getdefaultuncaughtexceptionhandler (); Thread.setdefaultuncaughtexceptionhandler ( This); }           /*** When uncaughtexception occurs, it is transferred to the function to handle*/@Override Public voiduncaughtexception (thread thread, Throwable ex) {if(!handleexception (ex) && Mdefaulthandler! =NULL) {               //let the system default exception handler handle if the user does not handlemdefaulthandler.uncaughtexception (thread, ex); } Else{//If you handle the exception yourself, the error dialog box will not pop up and you will 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 messages * Sending error reports, etc. are done here. * Developers can customize exception handling logic according to their own situation *@return* True means handling the exception, no longer throwing an exception, * false means not handling the exception (the log information can be stored) and then to the upper layer (here to the system of exception handling) to deal with, * Simple is true does not pop up the error box , false will pop up*/      Private BooleanHandleException (FinalThrowable ex) {           if(ex = =NULL) {               return false; }   //final String msg = Ex.getlocalizedmessage ();         Finalstacktraceelement[] Stack =Ex.getstacktrace (); FinalString message =Ex.getmessage (); //use Toast to display exception information        NewThread () {@Override Public voidrun () {looper.prepare (); //Toast.maketext (mcontext, "program error:" + message, Toast.length_long). Show (); //You can create only one file, and then send it all to the inside append, so there will be duplicate information, personally not recommendedString fileName = "crash-" + system.currenttimemillis () + ". Log"; File File=NewFile (Environment.getexternalstoragedirectory (), fileName); Try{FileOutputStream fos=NewFileOutputStream (file,true);                     Fos.write (Message.getbytes ());  for(inti = 0; i < stack.length; i++) {fos.write (Stack.tostring (). GetBytes ());                     } fos.flush ();                 Fos.close (); } Catch(Exception e) {} looper.loop ();           }}.start (); return false; }           //TODO uses HTTP Post to send error reports to the server don't repeat it here .//private void Postreport (file file) {//when uploading, you can also send the version of the app, the model of the phone and other information sent by the server,//Android compatibility is well known, so it may be wrong not every phone will error, or targeted to debug better//    }   The copy code is registered Exceptionhandler at Application OnCreate, and is then captured as long as the program throws an exception.  Public classAppextendsapplication{@Override Public voidonCreate () {Super. OnCreate (); Crashhandler Crashhandler=crashhandler.getinstance (); //Register CrashhandlerCrashhandler.init (Getapplicationcontext ()); }   }  Public classLogactivityextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);         Setcontentview (R.layout.main); Try{//Manufacturing BugsFile File =NewFile (Environment.getexternalstoragestate (), "Crash.bin"); FileInputStream FIS=Newfileinputstream (file); byte[] buffer =New byte[1024];         Fis.read (buffer); } Catch(Exception e) {//You can no longer throw an exception, if you want to save the log information, throw runtime exception,//allow custom handler to capture, save files and upload them in unity            Throw NewRuntimeException (e); }     } }

Note that if the catch is not thrown after it is handled by default, Exceptionhandler will not catch the exception.

To share a log wrapper class, just set the debug value here to let the console print out the log

 Public classDebugutil { Public Static FinalString TAG = "ICON";  Public Static Final BooleanDEBUG =true;  Public Static voidToast (Context context,string content) {Toast.maketext (context, content, Toast.length_short). Show (); }            Public Static voidDebug (String tag,string msg) {if(DEBUG) {LOG.D (tag, msg); }     }            Public Static voidDebug (String msg) {if(DEBUG) {log.d (TAG, msg); }     }            Public Static voidError (String tag,string error) {LOG.E (tag, error); }            Public Static voiderror (String error) {LOG.E (TAG, error); } }

This article transferred from: http://www.apkbus.com/android-128270-1-1.html

Android Uncaughtexceptionhandler, capturing errors

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.