通过Android中的后台服务定期将logcat输出写入文件

时间:2015-05-05 09:00:37

标签: android

我想通过服务将logcat结果写入后台文件。我创建了一个服务,并使用以下代码来获取logcat结果。

Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
            log.append(line);
}

现在使用上面的代码,我只能写一些日志,如果我删除" -d"选项然后服务崩溃。

1 个答案:

答案 0 :(得分:0)

你必须让手机以现有的R / W为根。

在Manifest.xml上为READ_LOGS授予权限。 然后在Activity

的OnCreate()中编写此代码
String pname = getPackageName();
        String[] CMDLINE_GRANTPERMS = { "su", "-c", null };
        if (getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS, pname) != 0) {
            Log.d(TAG, "we do not have the READ_LOGS permission!");
            if (android.os.Build.VERSION.SDK_INT >= 16) {
                Log.d(TAG, "Working around JellyBeans 'feature'...");
                try {
                    // format the commandline parameter
                    CMDLINE_GRANTPERMS[2] = String.format("pm grant %s android.permission.READ_LOGS", pname);
                    java.lang.Process p = Runtime.getRuntime().exec(CMDLINE_GRANTPERMS);
                    int res = p.waitFor();
                    Log.d(TAG, "exec returned: " + res);
                    if (res != 0)
                        throw new Exception("failed to become root");
                } catch (Exception e) {
                    Log.d(TAG, "exec(): " + e);
                    Toast.makeText(getApplicationContext(), "Failed to obtain READ_LOGS permission", Toast.LENGTH_LONG).show();
                }
            }
        } else
            Log.d(TAG, "we have the READ_LOGS permission already!");

然后你的代码应该工作,如果不是

则运行它
Process process = Runtime.getRuntime().exec("su -c logcat D");