Normally, if the Android app encounters an unhandled exception, a dialog box similar to the following will appear, and then force the app to exit:
If you want to change this default behavior, such as displaying a custom dialog box when an unhandled exception occurs or restarting the application, you can use the following steps to redefine the Android global exception handling event.
1. Implement the Thread. UncaughtExceptionHandler Interface
Generally, you can derive the Application class and implement the Thread. UncaughtExceptionHandler method:
[Java]
Public class GNavigatorApplication extends Application
Implements Thread. UncaughtExceptionHandler {
...
}
Public class GNavigatorApplication extends Application
Implements Thread. UncaughtExceptionHandler {
...
}
2. Define the Thread. UncaughtExceptionHandler Method
For example, restarting an Activity
[Java]
Public void uncaughtException (Thread thread, Throwable ex ){
Intent intent = new Intent (this, GNavigatorActivity. class );
Intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_NEW_TASK );
StartActivity (intent );
}
Public void uncaughtException (Thread thread, Throwable ex ){
Intent intent = new Intent (this, GNavigatorActivity. class );
Intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_NEW_TASK );
StartActivity (intent );
}
3. Reset the default Exception processing function. For example, you can reset the Exception Processing Method in the OnCreate method.
[Java]
@ Override
Public void onCreate (){
...
Thread. setDefaultUncaughtExceptionHandler (this );
}
@ Override
Public void onCreate (){
...
Thread. setDefaultUncaughtExceptionHandler (this );
}
In this way, the application will be automatically restarted when an unhandled exception occurs in the application, without the Force Close dialog box.
Author: mapdigit