public class NoteLog {
//Log信息 保存路径
private static final String FILE_PATH = "/sdcard/log/";
private static final String LOG_PATH = FILE_PATH + "log.txt";
private static final int LOG_FILE_MAX_SIZE = 50;//50 KB
static Thread readLogthread;
static BufferedReader reader = null;
static Boolean isStop = false;
static FileOutputStream out = null;
public static void startNoteLog() {
startNoteLogThread();
}
public static void stopNoteLog() {
isStop = true;
closeLogReader();
if (readLogthread != null) {
readLogthread.interrupt();
}
}
private static void startNoteLogThread() {
/** 开启线程用于监听log输出的信息 **/
readLogthread = new Thread() {
@Override
public void run() {
try {
readLogcatInfo();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeLogReader();
}
}
};
readLogthread.start();
}
private static void readLogcatInfo() throws IOException {
Process mLogcatProc = null;
String line = "";
// 清除LOG
Runtime.getRuntime().exec("logcat -c");
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");
commandLine.add("-v");
commandLine.add("time");
commandLine.add("-s");
commandLine.add("AndroidRuntime:e"); // *表示所有TAG(*:e)
mLogcatProc = Runtime.getRuntime().exec(
commandLine.toArray(new String[commandLine.size()]));
reader = new BufferedReader(new InputStreamReader(mLogcatProc
.getInputStream()));
while (!isStop && (line = reader.readLine()) != null) {
write(line);
}
}
private static void write(String data) {
try {
File file = new File(FILE_PATH);
if (!file.exists()) {
file.mkdir();
}
File logFile = new File(LOG_PATH);
if (logFile.exists()) {
if (logFile.length() > 1024 * LOG_FILE_MAX_SIZE) {
logFile.delete();
}
}
out = new FileOutputStream(LOG_PATH, true);
if (data != null && !data.contains("beginning")) {
out.write(data.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void closeLogReader() {
try {
if (out != null) {
out.close();
out = null;
}
if (reader != null) {
reader.close();
reader = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在manifest.xml中增加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_LOGS" />