SoFunction
Updated on 2025-04-09

How to use CrashHandler to get application crash information

Crash should inevitably occur during daily development. No matter how perfect your program is written, it is impossible to completely avoid crash. It may be due to bugs in the underlying Android, or due to insufficient model adaptation or poor network conditions. When crash occurs, the system will kill the executing program, which is a crash or reminder that the user that the program has stopped running. This is very unfriendly to the user and is something we don’t want to see. Earlier, when the user crashes, we developers cannot know why the program crashes. Even if we want to solve this bug, we cannot know the user’s crash information at the time, so we are often powerless. Fortunately, Android provides a way to deal with this kind of problem. Next, let’s see what methods Android provides to us to solve this difficult problem.

1. setDefaultUncaughtExceptionHandler in Thread class

/** 
 * Sets the default uncaught exception handler. This handler is invoked in 
 * case any Thread dies due to an unhandled exception. 
 * 
 * @param handler 
 *      The handler to set or null. 
 */  
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {  
   = handler;  
}  

This method can actually solve the crash problem of our application. Set the system's default exception handler. When crash occurs in the system, the system will call back the uncaughtException method of UncaughtExceptionHandler. Exception information can be obtained in the uncaughtException method. You can choose to store the exception information. You can choose the storage method yourself. Then upload the crash information to the server through the network at the appropriate time. In this way, our developers can analyze the user crash scenario and repair it in the subsequent version. We can also pop up a dialog box when crash occurs, telling the user program to crash, and then exit

2. Implement your own exception capture class

1) Create an exception Handler, named CrashHandler, the code is as follows

/**
  *Exception capture class
  * Created by qiudengjiao on 2017/9/29.
  */ 
 
public class CrashHandler implements  { 
 
  private static final String TAG = "CrashHandler"; 
  private static final boolean DEBUG = true; 
 
  private static final String PATH = ().getPath() + "/ryg_test/log/"; 
  private static final String FILE_NAME = "crash"; 
 
  //The suffix name of the log file  private static final String FILE_NAME_SUFFIX = ".trace"; 
 
  private static CrashHandler sInstance = new CrashHandler(); 
 
  //The system default exception handling (by default, the system will terminate the current exception program)  private  mDefaultCrashHandler; 
 
  private Context mContext; 
 
  //The construction method is private, preventing multiple instances from being constructed externally  private CrashHandler() { 
  } 
 
  public static CrashHandler getInstance() { 
    return sInstance; 
  } 
 
  /**
    * Initialization
    *
    * @param context
    */ 
 
  public void init(Context context) { 
    //Get the default exception handler of the system    mDefaultCrashHandler = (); 
    //Set the current instance as the system default exception handler    (this); 
    //Get Context for easy internal use    mContext = (); 
  } 
 
  /**
    * This is the most critical function. When there is an uncaught exception in the program, the system will automatically call the #uncaughtException method.
    * thread is the thread that has an uncaught exception, and ex is an uncaught exception. With this throwable, we can get exception information
    *
    * @param thread
    * @param throwable
    */ 
  @Override 
  public void uncaughtException(Thread thread, Throwable throwable) { 
    try { 
      //Export exception information to the SD card      dumpExceptionToSDCard(throwable); 
      // Here you can upload exception information to the server through the network, so that developers can analyze logs and solve bugs      uploadExceptionToServer(); 
    } catch (IOException e) { 
      (); 
    } 
 
    //Print out the current call stack information    (); 
 
    //If the system provides the default exception handler, it will be handed over to the system to end our program, otherwise we will end ourselves    if (mDefaultCrashHandler != null) { 
      (thread, throwable); 
    } else { 
      (()); 
    } 
  } 
 
  /**
    * Save to memory card
    * Here we can also choose other saving methods according to the project needs
    *
    * @param throwable
    * @throws IOException
    */ 
  private void dumpExceptionToSDCard(Throwable throwable) throws IOException { 
    //If the SD card does not exist or cannot be used, the exception information cannot be written to the SD card    if (!().equals(Environment.MEDIA_MOUNTED)) { 
      if (DEBUG) { 
        (TAG, "sdcard unmounted,skip dump exception"); 
        return; 
      } 
    } 
 
    File dir = new File(PATH); 
    if (!()) { 
      (); 
    } 
    long current = (); 
    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current)); 
    //Create a log file at the current time    File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX); 
 
    try { 
      PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); 
      //Export the time when the exception occurred      (time); 
 
      //Export mobile phone information      dumpPhoneInfo(pw); 
 
      (); 
      //Export the call stack information of exception      (pw); 
 
      (); 
    } catch (Exception e) { 
      (TAG, "dump crash info failed"); 
    } 
  } 
 
  /**
    * Collect equipment parameter information
    *
    * @param pw
    * @throws
    */ 
  private void dumpPhoneInfo(PrintWriter pw) throws  { 
    //The version name and version number of the application    PackageManager pm = (); 
    PackageInfo pi = ((), PackageManager.GET_ACTIVITIES); 
    ("App Version: "); 
    (); 
    ('_'); 
    (); 
 
    //android version number    ("OS Version: "); 
    (); 
    ("_"); 
    (.SDK_INT); 
 
    //Mobile phone manufacturer    ("Vendor: "); 
    (); 
 
    //Mobile phone number    ("Model: "); 
    (); 
 
    //cpu architecture    ("CPU ABI: "); 
    (Build.CPU_ABI); 
  } 
 
  /**
    * Upload exception information to the server
    */ 
  private void uploadExceptionToServer() { 
    //Write the logic uploaded to the server here  } 
} 

From the above code, we can see that when the application crashes, the CrashHandler class will write exception information and device information to the SD card. Here, you can also handle it according to your project needs. For example, it can also be stored in the database and then handed over the exception to the system for processing. The system will help us abort the program. If the system does not have a default exception handling mechanism, it will abort itself. Of course, you can choose to upload the exception information to the server. We do not implement this logic here. In actual development, we need to upload the exception information to the server.

3. How to use CrashHandler

In fact, using CrashHandler is also very simple. We can set CrashHandler when Application is initialized, as shown below:

/**
  * Custom Application class
  * Created by qiudengjiao on 2017/9/29.
  */ 
 
public class App extends Application { 
  @Override 
  public void onCreate() { 
    (); 
    init(); 
  } 
 
  private void init() { 
    //Initialize the exception capture class CrashHandler    ().init(this); 
  } 
} 

Through the above operations, our program can capture crash, and can also view the user's crash information from the server. That's all today to recommend a good book to you: Android development art, authored by Ren Yugang. I believe everyone knows that the content of this book is still very good and worth reading. It is more suitable for students with certain Android foundations. It will be the National Day holiday soon. I wish you a happy National Day.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.