话说自从决定之后 ,这两个月的生活节奏真是超忙,已被加班摧残到不知人间模样。
这篇文章的出发点在于,此前的一个场景,嵌入式开发有时候需要分析数据,某次联调需要给外部提供某项数据日志,而不提供其他数据。
当这么一个需求提出,我当时的第一反应是,用文件读写将需要保存的信息写入到外设存储设备中 。
于是就有了如下 工具类 :
public class Logger {
// 将字符串写入到文本文件中
public void writeTxtToFile(String strcontent, String filePath, String fileName) {
//生成文件夹之后,再生成文件,不然会出错
makeFilePath(filePath, fileName);
String strFilePath = filePath+fileName;
// 每次写入时,都换行写
String strContent = strcontent + "\r\n";
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + strFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
// 生成文件
public File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
// 生成文件夹
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
Log.i("error:", e+"");
}
}
}
调用时,只需如下 ,传入参数(内容,存放路径,文件名)即可
writeTxtToFile(content, filePath, fileName);
直到程序运行后我才意识到虽然启用文件读写会对程序原本的流程造成时间片开销的影响,如果数据量大,后果不言而喻。
于是转换思路。想起五月初的时候AndroidBus线下开发交流,北京TalkingData的韩广利分享了一种日志思路,他为此还写了个Demo,Logger(文末会将链接及相关PDF献上)。
思路转换后的构想是:直接调用安卓系统的Logcat,将需要的日志过滤出来,并存到指定外部存储路径。
那么,Logcat是一个完全独立于我们应用的程序,且偏向系统之外的程序,如何调用呢,自然是用Java提供的
Process process = Runtime.getRuntime().exec(“xxx”);
此方法返回一个java.lang.Process对象,该对象可以得到之前开启的进程的运行结果,还可以操作进程的输入输出流。
Process对象有以下几个方法:
1、destroy() 杀死这个子进程
2、exitValue() 得到进程运行结束后的返回状态
3、waitFor() 得到进程运行结束后的返回状态,如果进程未运行完毕则等待直到执行完毕
4、getInputStream() 得到进程的标准输出信息流
5、getErrorStream() 得到进程的错误输出信息流
6、getOutputStream() 得到进程的输入流
既然可以拿到进程的IO流,那一切就好办了。
对应的执行相关的Logcat过滤命令就好。如下
Runtime.getRuntime().exec(“logcat -f file -b main -v threadtime”)
再 获取相应的IO流,process.getInputStream()进行操作即可
public static void main(String[] args) throws IOException {
String cmd = "logcat -f file -b main -v threadtime";
final Process process = Runtime.getRuntime().exec(cmd);
printMessage(process.getInputStream());
}
private static void printMessage(final InputStream input) {
new Thread(new Runnable() {
public void run() {
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
try {
while((line=bf.readLine())!=null) {
//......
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
这样做的好处在于,完全处于另一个进程进行日志的操作,不会对原本应用产生任何影响。
关于 Logcat更多的命令行,可以参考这里。
转载自万境绝尘:http://blog.csdn.net/tumuzhuanjia/article/details/39555445/
在此感谢韩广利的精彩分享。
韩广利的分享PDF:http://download.csdn.net/detail/lebang08/9880192
[韩广利的日志工具类项目链接]:(https://github.com/GuangliHan/AndroidLoggerAPK)