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.