Use Uncaughtexceptionhandler to handle uncaught exceptions in Android

Source: Internet
Author: User
Tags throwable

The original text on the sparkyuan.me, reprint annotated Source: http://sparkyuan.github.io/2016/03/28/use Uncaughtexceptionhandler to handle uncaught exceptions/

All apps will take place crash, this article explains how to collect crash information for follow-up development to deal with this kind of problem.

Basic ideas

When the crash occurs, the system calls the Uncaughtexceptionhandler Uncaughtexception method, we can capture the exception information in this method, the exception information stored in the SD card, The crash information is transmitted back to the server at the appropriate time through the network, so that it can analyze the crash cause and resolve it in subsequent releases.
Let's take a look at one of the methods in the thread class, Setdefaultuncaughtexceptionhandler

publicstaticvoidsetDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {    Thread.defaultUncaughtHandler = handler;}

Defaultuncaughthandler is a static member variable of the thread class, so if we set the custom Uncaughtexceptionhandler to thread, Then all threads in the current process can use this uncaughtexceptionhandler to handle the exception.

Crashhandler
 Public  class Crashhandler implements Uncaughtexceptionhandler {    Private Static FinalString TAG ="Crashhandler";Private Static Final BooleanDEBUG =true;Private Static FinalString PATH = Environment.getexternalstoragedirectory (). GetPath () +"/crashtest/log/";Private Static FinalString file_name ="Crash";Private Static FinalString File_name_suffix =". Trace";Private StaticCrashhandler sinstance =NewCrashhandler ();PrivateUncaughtexceptionhandler Mdefaultcrashhandler;PrivateContext Mcontext;Private Crashhandler() {    } Public StaticCrashhandlergetinstance() {returnSinstance; }//A singleton that needs to be initialized     Public void Init(Context context)        {Mdefaultcrashhandler = Thread.getdefaultuncaughtexceptionhandler (); Thread.setdefaultuncaughtexceptionhandler ( This);    Mcontext = Context.getapplicationcontext (); }/** * This is the most critical function, when there is an uncaught exception in the program, the system will automatically call the #uncaughtexception method * thread for an uncaught exception, ex is an uncaught exception, and with this ex we can get the exception information. */    @Override     Public void uncaughtexception(thread thread, throwable ex) {Try{//Export exception information to SD cardDumpexceptiontosdcard (ex); Uploadexceptiontoserver ();//Here you can upload the exception information to the server through the network, so as to facilitate the developer to analyze the log to resolve the bug}Catch(IOException e)        {E.printstacktrace (); } ex.printstacktrace ();//If the system provides a default exception handler, give it to the system to end our program, or we will end ourselves        if(Mdefaultcrashhandler! =NULL) {mdefaultcrashhandler.uncaughtexception (thread, ex); }Else{process.killprocess (Process.mypid ()); }    }Private void Dumpexceptiontosdcard(Throwable ex)throwsIOException {//If the SD card is not present or unusable, the exception information cannot be written to the SD card        if(! Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {if(DEBUG) {LOG.W (TAG,"SDcard unmounted,skip dump Exception");return; }} File dir =NewFile (PATH);if(!dir.exists ())        {Dir.mkdirs (); }LongCurrent = System.currenttimemillis (); String time =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (NewDate (current)); File File =NewFile (PATH + file_name + time + file_name_suffix);Try{PrintWriter PW =NewPrintWriter (NewBufferedWriter (NewFileWriter (file));            Pw.println (time);            Dumpphoneinfo (PW);            Pw.println ();            Ex.printstacktrace (PW);        Pw.close (); }Catch(Exception e) {LOG.E (TAG,"Dump crash info failed"); }    }Private void Dumpphoneinfo(PrintWriter PW)throwsnamenotfoundexception {Packagemanager pm = Mcontext.getpackagemanager ();        PackageInfo pi = pm.getpackageinfo (Mcontext.getpackagename (), packagemanager.get_activities); Pw.print ("App Version:");        Pw.print (Pi.versionname); Pw.print (' _ '); Pw.println (Pi.versioncode);//android Version numberPw.print ("OS Version:");        Pw.print (Build.VERSION.RELEASE); Pw.print ("_"); Pw.println (Build.VERSION.SDK_INT);//Handset manufacturerPw.print ("Vendor:"); Pw.println (Build.manufacturer);//Phone modelPw.print ("Model:"); Pw.println (Build.model);//CPU ArchitecturePw.print ("CPU ABI:");    Pw.println (Build.cpu_abi); }Private void Uploadexceptiontoserver() {//todo Upload Exception Message to Your Web Server}}
How to use

Configure it in the OnCreate method of application to

 Public  class TestApp extends application {    Private StaticTESTAPP sinstance;@Override     Public void onCreate() {Super. OnCreate (); Sinstance = This;//Set an exception handler for the app here, and then our program can catch the unhandled exceptionCrashhandler Crashhandler = Crashhandler.getinstance (); Crashhandler.init ( This); } Public StaticTestAppgetinstance() {returnSinstance; }}

The original text on the sparkyuan.me, reprint annotated Source: http://sparkyuan.github.io/2016/03/28/use Uncaughtexceptionhandler to handle uncaught exceptions/

Use Uncaughtexceptionhandler to handle uncaught exceptions in Android

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.