Android crash restart, android crash

Source: Internet
Author: User

Android crash restart, android crash
During Android Application Development, exceptions may occur for the application being used due to exceptions and force shutdown. This will lead to unfriendly user experience. To solve this problem, we need to capture and handle exceptions. There are two types of exceptions in Java: Error and RuntimeException. The former does not need to be processed, and we often process the latter. So how can we capture exceptions during the running of a thread? We can use the custom class implementation.
Thread. UncaughtExceptionHandler interface and re-write the uncaughtException (Thread thread, Throwable ex) method to handle exceptions in the running Thread. In Android, we can implement our own Application class, then implement the UncaughtExceptionHandler interface, and handle exceptions in the uncaughtException method. Here we close the App and start the Activity we need. The code below is as follows:



Public class MyApplication extends Application implements
Thread. UncaughtExceptionHandler {
@ Override
Public void onCreate (){
Super. onCreate ();
// Set Thread Exception Handler
Thread. setDefaultUncaughtExceptionHandler (this );
}

@ Override
Public void uncaughtException (Thread thread, Throwable ex ){
System. out. println ("uncaughtException ");
System. exit (0 );
Intent intent = new Intent (this, MainActivity. class );
Intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP |
Intent. FLAG_ACTIVITY_NEW_TASK );
StartActivity (intent );
}

}
Finally, you need to configure the Application tag android: name = ". myApplication ", let the entire Application use our custom Application class, so that the Application can be restarted when the Application encounters a crash exception.
If the following exception is thrown in any Activity, the application restarts after an exception occurs. If the exception is not handled, the application is closed.

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.