我正在开发一个
Android应用程序.我注意到一个非常罕见的错误,导致我的应用程序崩溃.不幸的是,我的智能手机在发生时从未连接到我的电脑.那么,有没有办法在我的应用程序启动时自动将所有日志(尤其是抛出的runtimeexceptions)保存到文件中,以便我可以将此文件复制到我的电脑并分析错误?应用程序的每次启动都应该覆盖该文件,以便它只包含上次运行的日志…我该如何实现?
问候
解决方法
您可以通过以下链接找到帮助
Writing crash reports into device sd card
您不需要添加外部库.
import com.wordpress.doandroid.Training.R; import android.app.Activity; import android.os.Bundle; public class CaptureExceptionActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Sets the default uncaught exception handler. This handler is invoked // in case any Thread dies due to an unhandled exception. Thread.setDefaultUncaughtExceptionHandler(new CustomizedExceptionHandler( "/mnt/sdcard/")); String nullString = null; System.out.println(nullString.toString()); setContentView(R.layout.main); } }
和Handler实现
import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.text.SimpleDateFormat; import java.util.Date; import android.os.Environment; import android.util.Log; public class CustomizedExceptionHandler implements UncaughtExceptionHandler { private UncaughtExceptionHandler defaultUEH; private String localPath; public CustomizedExceptionHandler(String localPath) { this.localPath = localPath; //Getting the the default exception handler //that's executed when uncaught exception terminates a thread this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } public void uncaughtException(Thread t,Throwable e) { //Write a printable representation of this Throwable //The StringWriter gives the lock used to synchronize access to this writer. final Writer stringBuffSync = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringBuffSync); e.printStackTrace(printWriter); String stacktrace = stringBuffSync.toString(); printWriter.close(); if (localPath != null) { writeToFile(stacktrace); } //Used only to prevent from any code getting executed. // Not needed in this example defaultUEH.uncaughtException(t,e); } private void writeToFile(String currentStacktrace) { try { //Gets the Android external storage directory & Create new folder Crash_Reports File dir = new File(Environment.getExternalStorageDirectory(),"Crash_Reports"); if (!dir.exists()) { dir.mkdirs(); } SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); String filename = dateFormat.format(date) + ".STACKTRACE"; // Write the file into the folder File reportFile = new File(dir,filename); FileWriter fileWriter = new FileWriter(reportFile); fileWriter.append(currentStacktrace); fileWriter.flush(); fileWriter.close(); } catch (Exception e) { Log.e("ExceptionHandler",e.getMessage()); } } }
不要忘记在清单WRITE_EXTERNAL_STORAGE中添加此权限