Android Development Step-by-step 57:uncaughtexceptionhandler uncaught exception handler

Source: Internet
Author: User

When writing a program, most of the time, we will know the code block to add Try,catch, such as

   try {            mroot = inflater.inflate (r.layout.fragment_setting, container, false);            Initview (Mroot);        } catch (Exception e) {            log.error ("Settingfragment", E),        } catch (OutOfMemoryError e) {            log.error (" Settingfragment.outofmemoryerror ", e);        }

But some places forget to add, it will cause the program to collapse, the entire app will stop running, like this:


Obviously this kind of user experience is very bad, we need to avoid, in this case, we need to add a default exception handler, in the event of an exception, to be able to capture, give the user a hint or jump to the home page, so that the brutal pop-up of a program to stop running the error. OK, so let's start adding this default exception handler, usually in the rewritten application Class OnCreate (), which we need to add once the app is started.

 /** *  */package Com.figo.study;import Java.io.printwriter;import Java.io.StringWriter;import Java.io.writer;import Java.util.arraylist;import Com.figo.study.utils.crashhandler;import android.app.Activity; Import Android.app.application;import android.content.intent;import Android.util.log;import android.widget.Toast;/ ** * @author Figo * */public class MainApplication extends application{    @Override   & nbsp public void OnCreate () {        super.oncreate ();       //Set thread Exception Hand ler        Initexhandler ();</span>   }     public void Initexhandler () {        //Set the Crashhandler as the default processor for the program            Crashhandler Cat CHEXCEP = new Crashhandler (this);          Thread.setdefaultuncaughtexceptionhandler (CATCHEXCEP);      }  }
exception Handling Class Crashhandler.java

Package Com.figo.study.utils;import Java.lang.thread.uncaughtexceptionhandler;import Android.app.AlarmManager; Import Android.app.pendingintent;import Android.content.context;import Android.content.intent;import Android.os.looper;import Android.util.log;import Android.widget.toast;import Com.figo.study.aactivity;import Com.figo.study.mainapplication;public class Crashhandler implements Uncaughtexceptionhandler {private        Thread.uncaughtexceptionhandler Mdefaulthandler;      public static final String TAG = "CATCHEXCEP";            MainApplication Application; Public Crashhandler (mainapplication application) {//Get system default Uncaughtexception processor Mdefaulthandler = Th           Read.getdefaultuncaughtexceptionhandler ();      this.application = Application; } @Override public void uncaughtexception (thread thread, Throwable ex) {if (!handleexception (            EX) && Mdefaulthandler! = null) {//If the user does not handle then let the system default exception handler handle    Mdefaulthandler.uncaughtexception (thread, ex);              }else{Intent Intent = new Intent (Application.getapplicationcontext (), mainactivity.class); Pendingintent restartintent = pendingintent.getactivity (Application.getapplicationcon                                                             Text (), 0, intent, intent.flag_activity_new_task); Exit current program, jump to home mainactivity.class alarmmanager mgr = (alarmmanager) application.getsystemservice (Co ntext.                Alarm_service); Mgr.set (ALARMMANAGER.RTC, System.currenttimemillis () + 1000,restartintent);                           Restart app application.finishactivity after 1 seconds ();       }}/** * Custom error handling, collect error messages to send error reports and so on are done here.       * * @param ex * @return true: Returns False if the exception information is processed; */Private Boolean handleexception (Throwable ex) {if (ex = = null) {REturn false;                    }//Use Toast to display exception information new Thread () {@Override public void run () {                    Looper.prepare (); Toast.maketext (Application.getapplicationcontext (), "Sorry, the program has an exception and is about to exit.", Toast.length_short). Show                             ();                    Looper.loop ();            }}.start ();        return true; }    }


Android Development Step-by-step 57:uncaughtexceptionhandler uncaught exception handler

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.