通过Android中的背景服务定期将LogCat输出写入文件



我想通过服务将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"选项,则该服务崩溃了。

现在,您必须将手机扎根于r/w。

在subtest.xml上授予read_logs的权限。然后将此代码写入活动的

的ongreate()
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");

最新更新