1

我想读取 Android 系统级日志文件。所以我使用以下代码:

        Process mLogcatProc = null;
    BufferedReader reader = null;
    try {
        mLogcatProc = Runtime.getRuntime().exec(
                new String[] { "logcat", "-d",
                        "AndroidRuntime:E [Your Log Tag Here]:V *:S" });

        reader = new BufferedReader(new InputStreamReader(mLogcatProc
                .getInputStream()));

        String line;
        final StringBuilder log = new StringBuilder();
        String separator = System.getProperty("line.separator");

        while ((line = reader.readLine()) != null) {
            log.append(line);
            log.append(separator);
        }

    }

    catch (IOException e) {}
    finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {}

    }

我也在 AndroidManifest.xml 中使用过。但我看不懂任何一行。StringBuilder 日志为空。并且 mLogcatProc.waitFor 方法返回 0。

那么如何阅读日志呢?

4

3 回答 3

2

不能从普通(非 suid)android 应用程序执行此操作。

这是因为进程需要以 root 身份(或从 adb)运行才能读取 Android 中的 logcat 文件。如果您的 [rooted] 手机上安装了终端仿真器,请尝试运行 logcat - 除非您 su 到 root,否则它会拒绝您访问日志缓冲区的权限。

您的 StringBuffer 最终为空的原因是该进程将错误消息输出到 stderr(并且您正在通过 BufferedReader 读取 stdin)。

于 2010-12-29T07:07:55.817 回答
2

如果您向 AndroidManifest.xml 添加正确的权限,则原始帖子中的代码有效

 <uses-permission android:name="android.permission.READ_LOGS" />

PS:当然,您必须将代码中的“[Your Log Tag Here]”替换为您的实际标签;-)

于 2011-01-21T11:38:19.380 回答
1

查看 LogCollector 的源代码,应该可以解决您的问题。http://code.google.com/p/android-log-collector/

于 2010-12-29T07:32:13.277 回答