[Android development experience] We need to tell users that the program is about to crash and android is about to crash.

Source: Internet
Author: User

[Android development experience] We need to tell users that the program is about to crash and android is about to crash.

Reprinted please indicate the source: http://blog.csdn.net/zhaokaiqiang1992

Although our programs will undergo rigorous tests before they are officially launched to ensure program robustness and good user experience, one-person testing or several-person testing teams, it cannot be compared with tens of thousands or even hundreds of thousands of users. Therefore, it is also common that the newly launched program has been crashed in the hands of users. However, if we do not perform special processing, the system's built-in program crash prompt is really too scary, the user will be overwhelmed after seeing it. Therefore, we need a solution, that is, to give the user a more friendly prompt when the program is about to crash and tell him that the program is about to crash.

It is like the following:



Is this more friendly?

The following describes how to implement it.

To implement this function, we need to pay attention to an interface in the Thread class, UncaughtExceptionHandler, and another setting Thread. setDefaultUncaughtExceptionHandler (). What are the two things?

The UncaughtExceptionHandler interface is the called callback interface when the Thread is terminated due to an uncaptured exception.

The Thread. setDefaultUncaughtExceptionHandler () method is used to set the default handler called when the Thread stops suddenly because no exception is caught and no other handler is defined for the Thread.

Therefore, if we want to implement the processing logic when our processing program crashes, we only need to implement the UncaughtExceptionHandler interface and call Thread. setDefaultUncaughtExceptionHandler () to set it.

The following is the sample code.

First, give the code of 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); // registers the default uncaptured exception handling class Thread. setDefaultUncaughtExceptionHandler (AppException. getAppExceptionHandler (); AppManager. getAppManager (). addActivity (this);} public void btn (View view) {// zero division error, the program will crash int c = 1/0 ;}}

In this Code, we intentionally wrote an operation that causes exceptions, except for zero. Therefore, the program will crash if you click the button.

Next, we need to implement the interface by ourselves. Here, I inherit 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. logoff; import android. widget. toast;/***** @ ClassName: com. example. predictiondemo. appException * @ Description: Application exception class: used to catch exceptions * @ author zhaokaiqiang * @ Date 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, Exc Eption excp) {super (message, excp); this. mDefaultHandler = Thread. getDefaultUncaughtExceptionHandler ();} public String getMessage () {return message;} public void setMessage (String message) {this. message = message;}/*** get the exception handling object of the APP ** @ param context * @ return */public static AppException getAppExceptionHandler () {return new AppException ();} @ Overridepublic void uncaughtException (Thread thread, Thro Wable ex) {if (! HandleException (ex) & mDefaultHandler! = Null) {mDefaultHandler. uncaughtException (thread, ex) ;}/ *** custom exception handling *** @ param ex * @ return true: the exception information is processed; otherwise, false */private boolean handleException (Throwable ex) {if (ex = null) {return false;} final Activity = AppManager. getAppManager (). currentActivity (); if (activity = null) {return false;} new Thread () {@ Overridepublic void run () {loid. prepare (); Toast. makeText (activity, "the program is about to collapse", Toast. LENGTH_SHORT ). show (); new AlertDialog. builder (activity ). setTitle ("prompt "). setCancelable (false ). setMessage ("dear, the program crashes immediately... "). setNeutralButton ("OK", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {AppManager. getAppManager (). exitApp (activity );}}). create (). show (); logoff. loop ();}}. start (); return true ;}}

After an excuse is implemented, we need to process our own logic in the uncaughtException () method. In this case, the pop-up dialog box prompts the user program to crash, which is more friendly. The AppManager class in the Code is an Activity management class. below 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: used to manage the Activity and exit the Program * @ author zhaokaiqiang * @ date 11:27:55 **/public class AppManager {private static Stack <Activity> activityStack; private static AppManager insta Nce; private AppManager () {}/ *** Single instance */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 <Activity> ();} activityStack. add (activity);}/*** get the current Activity (the last pushed in the stack) */public Activity currentActivity () {Activity activity = ActivityStack. lastElement (); return activity;}/*** ends the current Activity (the last pushed 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 with the specified Class name */public void finishActivity (Class <?> Cls) {for (Activity activity: activityStack) {if (activity. getClass (). equals (cls) {finishActivity (activity) ;}}/*** end all activities */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: A small program always crashes.

Debug to check the exception points and causes.
 
Help: android development. Every time HTTP is initiated, the program crashes.

There is no problem with the code written in a single line, but you can think about whether it is a long connection process to initiate an http request. It is time-consuming. How can you put it in the UI thread, otherwise you will put it in the thread pool, or else you will just open a single thread. It is definitely not feasible to put it in the UI thread.

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.