今天偶然的在网络上看到应用层直接抓取系统日志的方法,我停下脚步就研究了下到底怎么实现的,github上已经有大牛写了aar包出来直接AS引用就可以了。
github地址:https://github.com/fatangare/LogcatViewer
其实核心代码就一行,执行了Android Shell下的logcat命令而已。
/system/bin/logcat -b main
public static final String LOGCAT_SOURCE_BUFFER_MAIN = "main";
public static final String LOGCAT_SOURCE_BUFFER_RADIO = "radio";
public static final String LOGCAT_SOURCE_BUFFER_EVENTS = "events";
/**
* Top Logcat logger directory to save log entries.
*/
private static final String LOG_RECORD_DIR = "/LogcatViewer/";
/**
* Get directory where logs are saved.
*
* @param context application context.
* @return directory File object.
*/
public static File getRecordDir(Context context) {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + LOG_RECORD_DIR + context.getPackageName());
}
int logSize=1;
private void runLogcatSubscriber() {
Process process = null;
//Execute logcat system command
try {
process = Runtime.getRuntime().exec("/system/bin/logcat -b " + LOGCAT_SOURCE_BUFFER_MAIN);
} catch (IOException e) {
PrintLog.d(""+e);
}
//Read logcat log entries
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String logEntry;
boolean isRun=true;
//Till request to kill thread is not received, keep reading log entries
while (isRun) {
//Read log entry.
logEntry = reader.readLine();
logSize++;
runOnUiThread(new Runnable() {
@Override
public void run() {
printInfo.setText(""+logSize);
}
});
PrintLog.d(logEntry);
//If recording is on, save log entries in mRecordingData in order to save them
// after every LOG_SAVING_INTERVAL interval
}
} catch (IOException e) {
//Fail to read logcat log entries
PrintLog.d(""+e);
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (process!=null) {
process.destroy();
}
}
return;
}