Android LogCat 以编程方式 - 所有进程

Android LogCat programmatically - all processes

是否可以读取所有进程的 LogCat 消息? (就像在 android studio 中我们选择 'No Filter' 选项一样)

当我执行这个时:

    File filename = new File(Environment.getExternalStorageDirectory() + "/mylog.txt");
    if (filename.exists()) {
        filename.delete();
    }

    String cmd = "logcat -f " + filename.getAbsolutePath();
    Runtime.getRuntime().exec(cmd);

它只写入连接到我的应用程序的日志。

从 android 版本 4.1+ 开始,您无法再读取其他应用程序的 logcat。请参阅 this 以供参考。

读取其他4.1以下版本应用的日志

Runtime.getRuntime().exec("logcat -c").waitFor();
Process process = Runtime.getRuntime().exec("logcat -v long *:*");
BufferedReader reader = 
new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
    String nextLine = reader.readLine();
    if (!nextLine.contains("LogWatcher-D")) {
        Log.w("LogWatcher-D", "See: " + nextLine);
    }
}

您需要授予 <uses-permission android:name="android.permission.READ_LOGS" /> 权限。

Reference

想清楚的可以参考this