我需要以某种方式监视 LogCat 日志,这意味着当我的服务运行时,我需要读取 LogCat 中的新条目。
目前我只知道如何检索一次日志:
Process mLogcatProc = null;
BufferedReader reader = null;
try
{
mLogcatProc = Runtime.getRuntime().exec(new String[]
{"logcat", "-d", "ActivityManager:I *:S" });
reader = new BufferedReader(new InputStreamReader
(mLogcatProc.getInputStream()));
String line;
final StringBuilder log = new StringBuilder();
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
如果我删除 -d 选项,它将不会退出,但也不会工作。
那么如何修改下面的代码以便不断从 LogCat 读取新条目呢?
我是按照刘嘉豪的建议这样做的:
ReadThread thread;
public void startRecordingLogs()
{
if(thread == null || !thread.isAlive())
{
ReadThread thread = new ReadThread();
thread.start();
}
}
public String stopRecordingLogs()
{
String results = thread.stopLogging();
return results;
}
private class ReadThread extends Thread{
String results;
Process process;
Object lockObject = new Object();
public void run(){
synchronized(lockObject)
{
process = Runtime.getRuntime().exec("logcat -v time");
reader = new BufferedReader(new InputStreamReader (process.getInputStream()));
String line;
final StringBuilder log = new StringBuilder();
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
}
results = log.toString();
}
public String stopLogging()
{
process.destroy();
synchronized(lockObject)
{
return results;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)