Friday, March 21, 2014

How to Store Log when Android Application Crashes

Add these two classes to your application and call in your class where you want catch exceptions

CrashReporter.report(context);
 
public class CrashReporter {
  public static void report(Context context) {
    if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {

      Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(context));
    }
  }
}


public class CustomExceptionHandler implements UncaughtExceptionHandler {
  private UncaughtExceptionHandler defaultUEH;
  private Context context;
private String localPath = "path where you want to store log file";
  /*
   * if any of the parameters is null, the respective functionality will not be
   * used
   */
  public CustomExceptionHandler(Context context) {
    this.context = context;
    this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
  }
  @Override
  public void uncaughtException(Thread t, Throwable e) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    String filename = null;
    try {

      filename = "filename.txt";
    } catch (NameNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    if (filename != null) {
      writeToFile(stacktrace, filename);
    }

    defaultUEH.uncaughtException(t, e);
  }

  private void writeToFile(String stacktrace, String filename) {
    try {

      BufferedWriter bos = new BufferedWriter(new FileWriter(localPath + "/" + filename));
      bos.write(stacktrace);
      bos.flush();
      bos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

No comments:

Post a Comment