Android Implementation Custom Crash handler Record Crash Information Instance Code

  • 2021-08-21 21:17:01
  • OfStack

Preface

In the use of their own android applications, occasionally the system has stopped running error. If you can record the error log, it is very helpful.

App exception crash information is stored in a file.

When the application crashes, collect as much data as possible, which is convenient for subsequent positioning and tracking modifications.

If possible, try to upload the crash log to the server. 1 Some integrated services have provided corresponding functions.

The main method used is Thread. UncaughtExceptionHandler

The method is as follows

1 in application to start CrashHandler, I think should be put in the call before other modules start as early as possible.

CrashHandler.java


import android.os.Build;
import android.os.Environment;
import android.os.Process;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
 private static final String TAG = "CrashHandler";
 private static final boolean DEBUG = true;
 //  Custom stored directory 
 private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/myApp/log/";
 private static final String FILE_NAME = "crash";
 private static final String FILE_NAME_SUFFIX = ".txt";
 private String phoneInfo;
 private static CrashHandler instance = new CrashHandler();
 private Thread.UncaughtExceptionHandler mDefaultCrashHandler;

 private CrashHandler() {
 }

 public static CrashHandler getInstance() {
  return instance;
 }

 public void init() {
  mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
  Thread.setDefaultUncaughtExceptionHandler(this);
  phoneInfo = getPhoneInformation();
 }

 /**
  *  This is the most critical function. When there are uncaught exceptions in the program, the system will automatically call uncaughtException Method 
  * thread For threads with uncaught exceptions, ex For uncaught exceptions, with this ex We can get the exception information 
  */
 @Override
 public void uncaughtException(Thread thread, Throwable ex) {
  try {
   // Export exception information to SD Card 
   dumpExceptionToSDCard(ex);
   // Here, you can upload exception information to the server, which is convenient for developers to analyze the log and solve it bug
   uploadExceptionToServer();
  } catch (IOException e) {
   e.printStackTrace();
  }
  ex.printStackTrace();
  // If the system provides the default exception handler, leave it to the system to end the program, otherwise it will end itself 
  if (mDefaultCrashHandler != null) {
   mDefaultCrashHandler.uncaughtException(thread, ex);
  } else {
   try {
    Thread.sleep(2000); //  Delay 2 Spike process 
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   android.os.Process.killProcess(Process.myPid());
  }
 }

 private void dumpExceptionToSDCard(Throwable ex) throws IOException {
  // If SD If the card does not exist or cannot be used, the exception information cannot be written to SD Card 
  if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
   if (DEBUG) {
    Log.e(TAG, "sdcard unmounted,skip dump exception");
    return;
   }
  }
  File dir = new File(PATH);
  if (!dir.exists()) {
   dir.mkdirs();
  }
  long current = System.currentTimeMillis();
  String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date(current));
  File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
  try {
   PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
   pw.println(time);
   pw.println(phoneInfo);
   pw.println();
   ex.printStackTrace(pw);
   pw.close();
   Log.e(TAG, "dump crash info seccess");
  } catch (Exception e) {
   Log.e(TAG, e.getMessage());
   Log.e(TAG, "dump crash info failed");
  }
 }

 private void uploadExceptionToServer() {
  //  Send exception information to the server 
 }

 private String getPhoneInformation() {
  StringBuilder sb = new StringBuilder();
  sb.append("App version name:")
    .append(BuildConfig.VERSION_NAME)
    .append(", version code:")
    .append(BuildConfig.VERSION_CODE).append("\n");
  //Android Version number 
  sb.append("OS Version: ");
  sb.append(Build.VERSION.RELEASE);
  sb.append("_");
  sb.append(Build.VERSION.SDK_INT).append("\n");
  // Mobile phone manufacturer 
  sb.append("Vendor: ");
  sb.append(Build.MANUFACTURER).append("\n");
  // Mobile phone model 
  sb.append("Model: ");
  sb.append(Build.MODEL).append("\n");
  //CPU Architecture 
  sb.append("CPU ABI:").append("\n");
  for (String abi : Build.SUPPORTED_ABIS) {
   sb.append(abi).append("\n");
  }
  return sb.toString();
 }
}

Use, you can call the initialization method in Application


@Override
public void onCreate() {
 super.onCreate();
 // init application...
 CrashHandler.getInstance().init();
}

Summarize


Related articles: