Android logcat应用指南


  本文标签:Android logcat

  Android是由谷歌推出的一款基于Linux平台的开源手机操作系统  。已经推出就伸手广大编程人员的喜爱  。在这里我们就先从Android logcat的相关应用来对这一系统进行一个深入的了解,以此方便我们的实际应用  。

  选项与说明 

  1. -s 默认设置过滤器   
  2. - f 文件 输出到日志文件   
  3. -c 清除日志   
  4. -d 获取日志   
  5. -g 获取日志的大小   
  6. - v 格式 设置日志(见下面的格式打印格式) 

  - v 格式与例范例

  1. brief W/tag ( 876): message   
  2. process W( 876) message (tag)   
  3. tag W/tag : message   
  4. thread W( 876:0x37c) message   
  5. raw message   
  6. time 09-08 05:40:26.729 W/tag ( 876): message   
  7. threadtime 09-08 05:40:26.729 876 892 W tag : message   
  8. long [ 09-08 05:40:26.729 876:0x37c W/tag ] message  

  代码例子:

  AndroidManifest.xml添加读取权限

  1. < uses-permission android:name=
    "android.permission.READ_LOGS" />   
  2. < uses-permission android:name=
    "android.permission.READ_LOGS" /> 

  清除日志

  1. try {   
  2. Runtime.getRuntime().exec("logcat -c");   
  3. } catch(Exception e) {   
  4. try {  
  5. Runtime.getRuntime().exec("logcat -c");  
  6. } catch(Exception e) {  

  获取日志

  1. try {   
  2. ArrayList< String> commandLine = new ArrayList< String>();   
  3. commandLine.add( "logcat");   
  4. commandLine.add( "-d");   
  5. commandLine.add( "-v");   
  6. commandLine.add( "time");   
  7. commandLine.add( "-s");   
  8. commandLine.add( "tag:W");   
  9. Process process = Runtime.getRuntime().exec
    ( commandLine.toArray( new String[commandLine.size()]));   
  10. BufferedReader bufferedReader = new BufferedReader
    ( new InputStreamReader(process.getInputStream()), 1024);   
  11. String line = bufferedReader.readLine();   
  12. while ( line != null) {   
  13. log.append(line);   
  14. log.append("\n")   
  15. }   
  16. } catch ( IOException e) {   
  17. }   
  18. try {  
  19. ArrayList< String> commandLine = new ArrayList< String>();  
  20. commandLine.add( "logcat");  
  21. commandLine.add( "-d");  
  22. commandLine.add( "-v");  
  23. commandLine.add( "time");  
  24. commandLine.add( "-s");  
  25. commandLine.add( "tag:W");  
  26. Process process = Runtime.getRuntime().exec
    ( commandLine.toArray( new String[commandLine.size()]));  
  27. BufferedReader bufferedReader = new BufferedReader
    ( new InputStreamReader(process.getInputStream()), 1024);  
  28. String line = bufferedReader.readLine();  
  29. while ( line != null) {  
  30. log.append(line);  
  31. log.append("\n")  
  32. }  
  33. } catch ( IOException e) {  

  结果:

  1. 09-08 09:44:42.267 W/tag ( 754): message1   
  2. 09-08 09:44:42.709 W/tag ( 754): message2   
  3. 09-08 09:44:43.187 W/tag ( 754): message3   
  4. 09-08 09:44:45.295 E/tag ( 754): message8