安卓通过包名获取指定app的日志记录
- 思路
- 通过包名获取pid
- 使用logcat获取log
- [logcat -d –pid=$(pidof -s pkg_name)](https://blog.csdn.net/hello_java_android/article/details/90109704 “原来这个是有的”)
- 代码实现(仅供参考)
- 参考
思路
通过app包名获取app的pid,再使用logcat获取log
通过包名获取pid
// 参考菜鸟教程linux ps命令, 有一定差异
// USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ps | grep packageName
// 直接返回包名对应应用当前的pid
pidof "包名"
// 安卓app获取自身的pid
int pid = android.os.Process.myPid();
使用logcat获取log
// -d 不阻塞
// -v 筛出不要的日志 chatty 我的app日志输出较快,被禁言了(狗头)
logcat -d | grep pid | grep -v chatty >> /sdcard/logs/log_file.txt
logcat -d –pid=$(pidof -s pkg_name)
代码实现(仅供参考)
/** * 安卓手机记录日志 * 以pid筛选,所以app要换线程了记得调用 * log -d 不阻塞 -c 清空缓存log * grep -v 筛选(不要的) */
public void recordLogs(String packageName, String mark){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd", Locale.CHINA);
//此app的pid
//int pid = android.os.Process.myPid();
String pidStr = execShell("pidof "+ packageName +" \n");
int pid = -1;
try {
pid = Integer.parseInt(pidStr.substring(0, pidStr.length() - 1));
}catch (NumberFormatException e){
e.printStackTrace();
return;
}
Log.d("yayale", "pid" + pid);
String shell = " logcat -d | grep " + pid + " | grep -v chatty >> /sdcard/logs/log_"+ mark + "_" + sdf.format(new Date()) + ".txt \n";
execShell(shell);
Log.d("yayale", "recorded log " + packageName);
}
/** * 执行shell */
public String execShell(String cmd) {
Log.d("adb", "run shell:" + cmd);
String result = "";
try {
DataOutputStream dataOutputStream;
Process process = Runtime.getRuntime().exec("su \n");
OutputStream outputStream = process.getOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(cmd + "\n");
dataOutputStream.flush();
dataOutputStream.close();
outputStream.close();
//获取执行结果
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder();
int read;
char[] buffer = new char[4096];
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
result = output.toString();
Log.d("adb", result);
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
参考
思路
pid获取-1-ps
pid获取-2-pidof
pid获取-3-pidof-参数
logcat
chatty
ps
grep
adb执行结果
本文地址:https://blog.csdn.net/G_eto/article/details/107519422