Android应用中需要过滤相应的log,通过log来获取数据,监控方法如下:
package com.example.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
public class ScannerLogParser {
private Process logParserProcess = null;
private List<Integer> times;
public void start() {
if (logParserProcess != null) {
return;
}
times = new ArrayList<Integer>();
new Thread() {
@Override
public void run() {
try {
//清掉以前的log
Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
}
BufferedReader reader = null;
try {
/**过滤tag =zzml 级别的debug的主缓冲区中的log*/
String[] cmd = { "logcat", "-b", "main", "zzml:D", "*:S" };
Log.v("zzml", cmd.toString());
logParserProcess = Runtime.getRuntime().exec(cmd);
reader = new BufferedReader(new InputStreamReader(logParserProcess.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains("hello")) {//log中含有的关键字
continue;
}
Log.v("zzml", "监控到数据--》"+line);
String[] strs = line.split("hello");
if (strs.length != 2) {
continue;
}
String str = strs[1].trim();
if (str.endsWith("ms")) {
try {
Integer time = Integer.valueOf(str.substring(0, str.length()-2));
times.add(time);
} catch (Exception e) { }
}
}
logParserProcess.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
logParserProcess = null;
}
}
}.start();
}
/**
* 停止log监听
*/
public void stop() {
logParserProcess.destroy();
logParserProcess = null;
}
public List<Integer> getTimes() {
return times;
}
}
具体使用:
<pre name="code" class="java">// 启动log监控分析线程
ScannerLogParser logParser = new ScannerLogParser();
logParser.start();
//结束时停止log分析线程
logParser.stop();
<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" />