In Android app development, there are occasional exceptions that cause the app being used to be abnormal and forced to shut down, which leads to an unfriendly user experience. To solve this problem, we need to catch the exception and do the processing. There are two kinds of exceptions in Java, namely error and RuntimeException, the former do not need us to deal with, we often deal with the latter. So how do you catch the exception of threads at run time, we can use custom classes to implement
The Thread.uncaughtexceptionhandler interface and the replication uncaughtexception (thread thread, Throwable Ex) method implement exception handling for runtime threads. 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, see the code below:
Public classMyApplicationextendsApplicationImplementsThread.uncaughtexceptionhandler {@Override Public voidonCreate () {Super. OnCreate (); //Set thread Exception HandlerThread.setdefaultuncaughtexceptionhandler ( This); } @Override Public voiduncaughtexception (thread thread, Throwable ex) {System.out.println ("Uncaughtexception"); System.exit (0); Intent Intent=NewIntent ( This, Mainactivity.class); Intent.addflags (Intent.flag_activity_clear_top|intent.flag_activity_new_task); StartActivity (Intent); } }
Finally, you need to configure the application label android:name= "in manifest. MyApplication ", let the entire application use our custom application class, which enables the effect of restarting the app when the app encounters a crash exception.
We actively throw the following exception in any activity, we will find that the application has encountered an exception restart, if not processed, the application will be closed after encountering an exception.
Throw New
Android catches exceptions and restarts apps after the app crashes