Android Programming Realization of Exception Capture and Log Log File Saving in Project

  • 2021-08-21 21:23:26
  • OfStack

This article describes the Android programming project exception capture and corresponding Log log file saving function. Share it for your reference, as follows:

To do program development, it is definitely inseparable from dealing with BUG, and it is even more inseparable from the emergence of program anomalies. At the time of development, we can find or handle Exception in programs by means of on-and-off debugging, log printing, exception catching tools, etc. When the customer uses our application, the program has problems. How can we know? Of course, we can add third-party tools such as AU statistics. What else can be done? That is to save the exception information in the form of documents, If the user is in use when the program is abnormal, you can let the user send the corresponding log information to us or customer service personnel. Better still, do a good job in the program and send the log to the designated server (remember to add network authority in the program). We can also get the log, and we can find the problem and deal with it.

Key code for exception capture:


/**
 * UncaughtExceptionHandler Thread uncaught exception controllers are used to handle uncaught exceptions.   Implement this interface and register as the default uncaught exception handling in the program 
 *  This allows you to do some exception handling when an uncaught exception occurs   For example, collect exception information and send error reports   Wait. 
 *
 * @description : 
 * @author ldm
 * @date 2016-4-18  Morning 11:31:19
 */
public class MyExceptionHandler implements UncaughtExceptionHandler {
  //  Context 
  private Context mContext;
  //  Do you want to turn on upload 
  public boolean openUpload = true;
  // Log File path 
  private static final String LOG_FILE_DIR = "log";
  // log Suffix name of file 
  private static final String FILE_NAME = ".log";
  private static MyExceptionHandler instance = null;
  //  System default exception handling (by default, the system terminates the current exception program) 
  private UncaughtExceptionHandler mDefaultCrashHandler;
  private MyExceptionHandler(Context cxt) {
    //  Get the default exception handler for the system 
    mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
    //  Set the current instance as the default exception handler for the system 
    Thread.setDefaultUncaughtExceptionHandler(this);
    //  Get Context For easy internal use 
    this.mContext = cxt.getApplicationContext();
  }
  public synchronized static MyExceptionHandler create(Context cxt) {
    if (instance == null) {
      instance = new MyExceptionHandler(cxt);
    }
    return instance;
  }
  /**
   *  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 {
      //  Save export exception log information to SD Card 
      saveToSDCard(ex);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      //  If the system provides a default exception handler, it is left to the system to end our program, otherwise it is up to us to end ourselves 
      Toast.makeText(mContext,
          " Sorry, the program has made an error and is about to exit :\r\n" + ex.getLocalizedMessage(),
          Toast.LENGTH_LONG).show();
      if (mDefaultCrashHandler != null) {
        mDefaultCrashHandler.uncaughtException(thread, ex);
      } else {
        ex.printStackTrace();
      }
    }
  }
  /**
   *  Save the file to SD Card 
   *
   * @description : 
   * @author ldm
   * @date 2016-4-18  Morning 11:37:17
   */
  private void saveToSDCard(Throwable ex) throws Exception {
    File file = FileUtil.getAppointFile(mContext.getPackageName()
        + File.separator + LOG_FILE_DIR,
        getDataTime("yyyy-MM-dd-HH-mm-ss") + FILE_NAME);
    PrintWriter pw = new PrintWriter(new BufferedWriter(
        new FileWriter(file)));
    //  Export the time when the exception occurred 
    pw.println(getDataTime("yyyy-MM-dd-HH-mm-ss"));
    //  Export mobile phone information 
    savePhoneInfo(pw);
    pw.println();
    //  Export call stack information for exceptions 
    ex.printStackTrace(pw);
    pw.close();
  }
  /**
   *  Save hardware information of mobile phone 
   *
   * @description : 
   * @author ldm
   * @date 2016-4-18  Morning 11:38:01
   */
  private void savePhoneInfo(PrintWriter pw) throws NameNotFoundException {
    //  Applied version name and version number 
    PackageManager pm = mContext.getPackageManager();
    PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(),
        PackageManager.GET_ACTIVITIES);
    pw.print("App Version: ");
    pw.print(pi.versionName);
    pw.print('_');
    pw.println(pi.versionCode);
    pw.println();
    // android Version number 
    pw.print("OS Version: ");
    pw.print(Build.VERSION.RELEASE);
    pw.print("_");
    pw.println(Build.VERSION.SDK_INT);
    pw.println();
    //  Mobile phone manufacturer 
    pw.print("Manufacturer: ");
    pw.println(Build.MANUFACTURER);
    pw.println();
    //  Mobile phone model 
    pw.print("Model: ");
    pw.println(Build.MODEL);
    pw.println();
  }
  /**
   *  Returns time according to time format 
   *
   * @description : 
   * @author ldm
   * @date 2016-4-18  Morning 11:39:30
   */
  private String getDataTime(String format) {
    SimpleDateFormat df = new SimpleDateFormat(format);
    return df.format(new Date());
  }
}

When using, we need to initialize in Application:


public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    MyExceptionHandler.create(this);
  }
}

Register Application in the AndroidManifest. xml file:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.ldm.exception"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />
  <uses-permission android:name="android.permission.INTERNET" />
  <application
    android:name="com.ldm.exception.MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
      android:name="com.ldm.activity.MainActivity"
      android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>

Note: For more information about Android Manifest permission control file, please click here to view Android permission operation instructions

File upload method has written well, but no specific implementation, such as 1 but there are log files upload or log files reached 1 fixed size to upload, this will be based on the actual situation to determine.

When there is an exception in our application, there is a folder with the name of our application package in the mobile phone folder, and there is a log file in it.

Attachment: The complete Demo click here to download it.

For more readers interested in Android related content, please check the topics on this site: "Summary of Android Debugging Skills and Common Problem Solutions", "Introduction and Advanced Tutorial of Android Development", "Summary of Android Basic Component Usage", "Summary of View Skills in Android View", "Summary of Android Layout layout Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: