アプリ内に実装することで、独自のログ書き込みシステムをセットアップできますjava.lang.Thread.UncaughtExceptionHandler
。
例えば
public class myExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
private String localPath;
public myExceptionHandler(String localPath) {
this.localPath = localPath;
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread t, Throwable e) {
final long ts = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ts);
final String timestamp = new SimpleDateFormat("HH_mm_ss_SSS")
.format(cal.getTime());
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
String stacktrace = result.toString();
printWriter.close();
String filename = "logcat"+timestamp + ".txt";
if (localPath != 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();
}
}
}
次のように MainActivity からこのハンドラーを呼び出します。
Thread.setDefaultUncaughtExceptionHandler(new myExceptionHandler("Put your target directory/folder path where you would like to store the log file"));
これで、アプリがクラッシュするたびに、コードで使用したフォルダーにログファイルが書き込まれます。