Android app sets global Exception to handle events

Source: Internet
Author: User

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
 

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.