Handling crash exceptions in Android and restarting programs

Source: Internet
Author: User

Sometimes the program crashes due to inadequate testing or potential problems with the program, which is unacceptable, how to catch an abnormal crash of the program in Android, and then perform some necessary processing or restarting

The application of this problem annoyed me for a long time, today finally solved the problem, write an article to record.

The first thing to catch the exception of a program crash is to understand the Uncaughtexceptionhandler interface in Java, which Android inherits from the Android API:

By implementing this interface, you can handle a situation where a thread is terminated by an exception that cannot be caught. As described above, handler will report thread termination and unexplained exceptions, if no custom handler are

The thread management group is defaulted to the handler that reports the exception.

Threadgroup This class is implemented Uncaughtexceptionhandler this interface, if you want to catch an exception we can implement this interface or inherit Threadgroup, and overload Uncaughtexception method.

A more detailed description of the interface in the Java API:

I will not translate, too hard ...%>_<%. When implementing Uncaughtexceptionhandler, you must overload uncaughtexception (thread thread, throwable ex) if we do not implement the interface

That is, the catch exception is not displayed, the ex is empty, otherwise the ex is not empty, and thread is the thread that is out of the exception.

The next code, implementing the Uncaughtexceptionhandler interface, shows how the processing thread terminates abnormally:

[Java]View Plaincopy
  1. Public class Uncehandler implements Uncaughtexceptionhandler {
  2. private Thread.uncaughtexceptionhandler Mdefaulthandler;
  3. public static final String TAG = "Catchexcep";
  4. CATCHEXCEP Application;
  5. Public Uncehandler (catchexcep application) {
  6. //Get the system default Uncaughtexception processor
  7. Mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler ();
  8. this.application = Application;
  9. }
  10. @Override
  11. public void uncaughtexception (thread thread, Throwable ex) {
  12. if (!handleexception (ex) && Mdefaulthandler! = null) {
  13. //If the user does not handle it, let the system default exception handler handle
  14. Mdefaulthandler.uncaughtexception (thread, ex);
  15. }else{
  16. try{
  17. Thread.Sleep (2000);
  18. }catch (Interruptedexception e) {
  19. LOG.E (TAG, "error:", e);
  20. }
  21. Intent Intent = new Intent (Application.getapplicationcontext (), mainactivity.   Class);
  22. Pendingintent restartintent = pendingintent.getactivity (
  23. Application.getapplicationcontext (), 0, intent,
  24. Intent.flag_activity_new_task);
  25. //Exit program
  26. Alarmmanager mgr = (alarmmanager) application.getsystemservice (Context.alarm_service);
  27. Mgr.set (ALARMMANAGER.RTC, System.currenttimemillis () + + ,
  28. Restartintent); //1 seconds to restart the app
  29. Application.finishactivity ();
  30. }
  31. }
  32. /**  
  33. * Custom error handling, collect error messages to send error reports and so on are done here.
  34. *
  35. * @param ex
  36. * @return true: Returns False if the exception information is processed;
  37. */
  38. Private Boolean handleexception (Throwable ex) {
  39. if (ex = = null) {
  40. return false;
  41. }
  42. //Use Toast to display exception information
  43. New Thread () {
  44. @Override
  45. public Void Run () {
  46. Looper.prepare ();
  47. Toast.maketext (Application.getapplicationcontext (), "Sorry, the program is abnormal and is about to exit.",
  48. Toast.length_short). Show ();
  49. Looper.loop ();
  50. }
  51. }.start ();
  52. return true;
  53. }
  54. }


By handling the exception in the global class of Android application, if you do not know the role of application, please check this link: application

[Java]View Plaincopy
  1. Public class Catchexcep extends application{
  2. arraylist<activity> list = new arraylist<activity> ();
  3. public void init () {
  4. //Set the Crashhandler as the default processor for the program
  5. Uncehandler catchexcep = new Uncehandler (this);
  6. Thread.setdefaultuncaughtexceptionhandler (CATCHEXCEP);
  7. }
  8. /** 
  9. * Delete Activity object in activity list when activity is closed */
  10. public void Removeactivity (Activity a) {
  11. List.remove (a);
  12. }
  13. /** 
  14. * Add activity object to Activity list */
  15. public void Addactivity (Activity a) {
  16. List.add (a);
  17. }
  18. /** 
  19. * Close all activity*/in the activity list
  20. public void Finishactivity () {
  21. For (Activity activity:list) {
  22. if (null! = activity) {
  23. Activity.finish ();
  24. }
  25. }
  26. //Kill the app process
  27. Android.os.Process.killProcess (Android.os.Process.myPid ());
  28. }
  29. }


Then artificially create an exception:

[Java]View Plaincopy
  1. Button btn;
  2. TextView TV;
  3. private CATCHEXCEP Application;
  4. @Override
  5. protected void OnCreate (Bundle savedinstancestate) {
  6. super.oncreate (savedinstancestate);
  7. Setcontentview (R.layout.activity_main);
  8. BTN = (Button) Findviewbyid (R.ID.BTN);
  9. TV = (TextView) Findviewbyid (r.id.tv);
  10. Application = (CATCHEXCEP) getapplication ();
  11. Application.init ();
  12. Application.addactivity (this);
  13. Btn.setonclicklistener (this);
  14. }
  15. /** 
  16. * Human-made anomalies */
  17. public Void Press () {
  18. New Thread (new Runnable () {
  19. @Override
  20. public Void Run () {
  21. Tv.settext ("DFSD");
  22. }
  23. }). Start ();
  24. }
  25. @Override
  26. public void OnClick (View v) {
  27. Press ();
  28. }
  29. }


The appeal code will be able to implement an exception that cannot be caught by the application, kill the current process, and restart an application.

Where I was troubled: I searched a lot of information, killed the abnormal process, restarted the application, and the Web application was calling StartActivity (intent) through the Application object and then killing the exception process. But how I tried was not successful,

The process was killed, but the application did not start up, and if the exception process is not killed, then close the application will have to close two times, obviously unacceptable. Some of the online methods are wrong: The following blog:

http://blog.csdn.net/xianming01/article/details/7711160

Http://blog.csdn.net/ryantang03/article/details/9336295?reload

Their approach captures exceptions, kills abnormal processes, but is not able to restart the application.

How to kill the abnormal process, restart the application, you have to use Pendingintent, this class is Android in the intent class packaging, specifically I will write a blog, I can also go to see the Android API.

Launching it via Alarmmanager and shutting down open activity kills the exception process to enable the restart of the app.

Reference Links:

http://zheyiw.iteye.com/blog/1670990

Handling crash exceptions in Android and restarting programs

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.