这是一个读取日志的例子 。
你可以改变这个写入一个文件而不是一个TextView 。
需要AndroidManifest权限:
码:
public class LogTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { Process process = Runtime.getRuntime().exec("logcat -d"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); StringBuilder log = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { log.append(line); } TextView tv = (TextView) findViewById(R.id.textView1); tv.setText(log.toString()); } catch (IOException e) { } } }
Logcat可以直接写入一个文件:
public static void saveLogcatToFile(Context context) { String fileName = "logcat_"+System.currentTimeMillis()+".txt"; File outputFile = new File(context.getExternalCacheDir(),fileName); @SuppressWarnings("unused") Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath()); }
有关logcat的更多信息:请参阅
或者你可以试试这个varian
尝试{ 最终文件path=新文件( Environment.getExternalStorageDirectory(),“DBO_logs5”); if(!path.exists()){ path.mkdir(); } 调用Runtime.getRuntime()。EXEC( “logcat -d -f”+ path + File.separator +“dbo_logcat” +“.txt”); catch(IOException e){ e.printStackTrace(); }
public static void writeLogToFile(Context context) { String fileName = "logcat.txt"; File file= new File(context.getExternalCacheDir(),fileName); if(!file.exists()) file.createNewFile(); String command = "logcat -f "+file.getAbsolutePath(); Runtime.getRuntime().exec(command); }
以上方法将所有日志写入文件。 也请在Manifest文件中添加下面的权限