The Android system "abnormal exit of the program" has a negative impact on the user experience of the application. You can inherit the UncaughtExceptionHandler class to capture exceptions during application running and give friendly prompts. Use the Thread. setDefaultUncaughtExceptionHandler () method to set the exception handling class to the Thread.
1. Exception Handling class, the Code is as follows:
Public class CrashHandler implements UncaughtExceptionHandler {public static final String TAG = "CrashHandler"; private static CrashHandler INSTANCE = new CrashHandler (); private Context mContext; private Thread. uncaughtExceptionHandler mDefaultHandler; private CrashHandler () {} public static CrashHandler getInstance () {return INSTANCE;} public void init (Context ctx) {mContext = ctx; mDefaultH Andler = Thread. getDefaultUncaughtExceptionHandler (); Thread. setDefaultUncaughtExceptionHandler (this) ;}@ Override public void uncaughtException (Thread thread, Throwable ex) {// if (! HandleException (ex) & mDefaultHandler! = Null) {// mDefaultHandler. uncaughtException (thread, ex); //} else {// android. OS. process. killProcess (android. OS. process. myPid (); // System. exit (10); //} System. out. println ("uncaughtException"); new Thread () {@ Override public void run () {loid. prepare (); new AlertDialog. builder (mContext ). setTitle ("prompt "). setCancelable (false ). setMessage ("the program crashed... "). setNeutralButton ("I know", new OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {System. exit (0 );}}). create (). show (); logoff. loop ();}}. start ();}/*** custom error handling, collecting error messages, sending error reports, and other operations are completed here. developers can customize the exception handling logic ** @ param ex * @ return true: If the exception information is processed, false */private boolean handleException (Throwable ex) is returned) {if (ex = null) {return true;} // new Handler (loler. getMainLooper ()). post (new Runnable () {// @ Override // public void run () {// new AlertDialog. builder (mContext ). setTitle ("prompt ")//. setMessage ("the program crashed... "). setNeutralButton ("I know", null )//. create (). show (); //}); return true ;}}
2. Thread binding Exception Handling
Public class CrashHandlerActivity extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); CrashHandler crashHandler = CrashHandler. getInstance (); crashHandler. init (this); // The input parameter must be Activity; otherwise, AlertDialog is not displayed. // Create error throw new NullPointerException ();}}
Demo:Http://code.google.com/p/android-custom-view/downloads/list
Reprinted address:
Http://orgcent.com/android-uncaughtexceptionhandler-exception/ | radish cabbage blog