在应用程序的开头使用Application类。这样可以进行正确的文件和日志处理。
下面的代码在以下位置创建一个日志文件:
/ExternalStorage/MyPersonalAppFolder/logs/logcat_XXX.txt
XXX是当前时间(以毫秒为单位)。每次您运行应用程序时,都会创建一个新的logcat_XXX.txt文件。
public class MyPersonalApp extends Application { public void onCreate() { super.onCreate(); if ( isExternalStorageWritable() ) { File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" ); File logDirectory = new File( appDirectory + "/logs" ); File logFile = new File( logDirectory, "logcat_" + System.currentTimeMillis() + ".txt" ); // create app folder if ( !appDirectory.exists() ) { appDirectory.mkdir(); } // create log folder if ( !logDirectory.exists() ) { logDirectory.mkdir(); } // clear the previous logcat and then write the new one to the file try { Process process = Runtime.getRuntime().exec("logcat -c"); process = Runtime.getRuntime().exec("logcat -f " + logFile); } catch ( IOException e ) { e.printStackTrace(); } } else if ( isExternalStorageReadable() ) { // only readable } else { // not accessible } } public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if ( Environment.MEDIA_MOUNTED.equals( state ) ) { return true; } return false; } public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if ( Environment.MEDIA_MOUNTED.equals( state ) || Environment.MEDIA_MOUNTED_READ_ONLY.equals( state ) ) { return true; } return false; }}您需要在.manifest文件中使用正确的权限和应用程序类的名称:
<uses-permission android:name="android.permission.READ_LOGS" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><application android:name=".MyPersonalApp" ... >
编辑:
如果您只想保存某些特定活动的日志。
更换:
process = Runtime.getRuntime().exec("logcat -f " + logFile);与:
process = Runtime.getRuntime().exec( "logcat -f " + logFile + " *:S MyActivity:D MyActivity2:D");



