"Android Development experience" We're going to be friendly and tell the user that the program is going to crash.

Source: Internet
Author: User

? ? Reprint Please specify Source: http://blog.csdn.net/zhaokaiqiang1992

? ? Although our program will undergo rigorous testing before it is officially launched. In order to ensure the robustness of the program and a good user experience, however, a person's test or a few people's Test team, can not be compared with tens or even hundreds of thousands of of users. So. Pre-launch of the program in the user's hand is played, but also the common thing, but. Suppose we don't do special treatment. The system comes with a program crash prompt is really scary, users will be overwhelmed after seeing. Therefore, we need a solution. is when the program is about to crash. Give the user a more friendly hint. To tell him that the program was going to crash immediately.

? ? It's like the following:



? ? ? Is it a little more friendly?

? ? The following explanation is how to implement.

Suppose you want to implement such a function. What we need to focus on is one interface within the thread class, Uncaughtexceptionhandler, and another setting Thread.setdefaultuncaughtexceptionhandler (), what are these two things for?

? ?? Uncaughtexceptionhandler this interface is when thread is to be terminated because of an uncaught exception. The callback interface that will be invoked.

? ? The Thread.setdefaultuncaughtexceptionhandler () approach, however, is to set the default handler that is called when a thread terminates abruptly because it did not catch an exception, and no other handler is defined for the thread.

? ? So, assuming we want to handle the processing logic of our program when it crashes, we just need to implement the Uncaughtexceptionhandler interface and invoke the Thread.setdefaultuncaughtexceptionhandler () setting.

? ? The following is a demo sample code

? ? First of all. First, give the code for the activity above

Package Com.example.exceptiondemo;import Android.app.activity;import Android.os.bundle;import Android.view.View; public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Register the default non-catching exception handling class Thread.setdefaultuncaughtexceptionhandler (Appexception.getappexceptionhandler ()); Appmanager.getappmanager (). addactivity (this);} public void btn (view view) {//Except 0 error, program crashes int c = 1/0;}}

? ?in this code, it is helpful to write an exception that will occur, except for 0. So just click on the button. The program will crash.

? ? Below, we want to implement the interface ourselves. Here, I inherited the exception class.

Package Com.example.exceptiondemo;import Java.lang.thread.uncaughtexceptionhandler;import android.app.Activity; Import Android.app.alertdialog;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.os.looper;import android.widget.Toast;/** * * @ ClassName:com.example.exceptiondemo.AppException * @Description: Application Exception class: Used to catch exceptions * @author Zhaokaiqiang * @date 2014-11-2 pm 10:06:49 * */public class Appexception extends Exception implements Uncaughtexceptionhandler {private static Final long serialversionuid = -6262909398048670705l;private String message;private thread.uncaughtexceptionhandler Mdefaulthandler;private appexception () {super (); This.mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler () ;} Public appexception (String message, Exception EXCP) {super (message, EXCP); This.mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler ();} Public String GetMessage () {return message;} public void Setmessage (String message) {This.messaGE = message;} /** * Get app Exception crash processing Object * * @param context * @return */public static appexception Getappexceptionhandler () {return new Appexc Eption ();} @Overridepublic void uncaughtexception (thread thread, Throwable ex) {if (!handleexception (ex) && Mdefaulthandler = null) {mdefaulthandler.uncaughtexception (thread, ex);}}  /** * Define exception handling by itself * * @param ex * @return true: the exception is handled; otherwise false */private Boolean handleexception (Throwable ex) {if (ex = = NULL) {return false;} Final Activity activity = Appmanager.getappmanager (). currentactivity (); if (Activity = = null) {return false;} New Thread () {@Overridepublic void run () {looper.prepare (); Toast.maketext (Activity, "the program is going to collapse", Toast.length_short). Show (); new Alertdialog.builder (activity). Settitle ("hint"). Setcancelable (False). Setmessage ("Pro. The program immediately crashes ... "). Setneutralbutton (" Never Mind ", new Onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog,int which) {Appmanager.getappmanager (). Exitapp (activity);}}). Create (). Show (); Looper.loop ();}}. Start (); return True;}} 

? ?after making excuses. We need to deal with our own logic in the Uncaughtexception () method, where I pop up a dialog box prompting the user program to crash, so. is a little more friendly. The AppManager class in the code is a management class for activity. Here is the code

Package Com.example.exceptiondemo;import Java.util.stack;import Android.app.activity;import Android.app.activitymanager;import android.content.context;/** * * @ClassName: Net.oschina.app.AppManager * @ Description:activity Management class: For managing activity and exiting the program * @author Zhaokaiqiang * @date 2014-11-2 Morning 11:27:55 * */public class Appmanage R {private static stack<activity> activitystack;private static AppManager instance;private AppManager () {}/** * single real Example */public static AppManager Getappmanager () {if (instance = = null) {instance = new AppManager ();} return instance;} /** * Add activity to stack */public void addactivity (activity activity) {if (Activitystack = = null) {Activitystack = new stack&lt ; Activity> ();} Activitystack.add (activity);} /** * Gets the current activity (last pressed in the stack) */public activity currentactivity () {Activity activity = activitystack.lastelement (); return activity;} /** * Ends the current activity (last pressed in the stack) */public void finishactivity () {Activity activity = activitystack.lastelement (); Finishactivity (activity);} /** * Ends the specified activity */public void finishactivity (activity activity) {if (activity! = null) {Activitystack.remove (activity); Activity.finish (); activity = NULL;}} /** * Ends the activity */public void Finishactivity (class<?> cls) {for (activity Activity:activitystack) {if (Activ) of the specified class name Ity.getclass (). Equals (CLS)) {finishactivity (activity);}}} /** * End all activity */public void finishallactivity () {for (int i = 0, size = activitystack.size (); i < size; i++) {if ( Null! = Activitystack.get (i)) {activitystack.get (i). Finish ();}} Activitystack.clear ();} /** * Exit application */public void Exitapp (context context) {try {finishallactivity (); Activitymanager activitymgr = (activitymanager) context.getsystemservice (Context.activity_service); Activitymgr.killbackgroundprocesses (Context.getpackagename ()); System.exit (0);} catch (Exception e) {}}}

? ? Demo:https://github.com/zhaokaiqiang/exceptiondemo

"Android Development experience" We're going to be friendly and tell the user that the program is going to crash.

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.