Android development uses UncaughtExceptionHandler to catch global exceptions

  • 2021-07-22 11:14:31
  • OfStack

After integrating statistics SDK (AU statistics, Baidu statistics, etc.), there is a function that is very beneficial to testing: error analysis! This function can run the program in the crash (runtimeException) problem feedback to the server, help developers improve the product, more adaptation machine.

However, these SDK are not integrated in the company's Android development, so how should such functions be realized? Let's look at how to use UncaughtExceptionHandler to catch exceptions.

First, create a class to implement UncaughtExceptionHandler interface. The code is as follows:


public class CrashHandler implements UncaughtExceptionHandler {  
 
    @Override 
    public void uncaughtException(Thread thread, Throwable ex) { 
        // Handle exceptions  
        Log.e(" Collapse ",thread.getName()+ex.toString()); 
        // Send to server  
        //dialog Reminder  
    } 
 
}

There is processing code, and then where it needs to be triggered:

Add in oncreate of activity, the entry of the program:

Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());

Isn't it very simple!


Related articles: