0

I need to save the logcat output when i get an ANR error to a string variable, and display it on a text view inside my application. I have tried to do so by calling this function on button press

        Process process = Runtime.getRuntime().exec("logcat -d | grep \"ANR\" -A 38");
        BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));

        StringBuilder log = new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {

            log.append(line);
        }

        mTxtAnrinfo.setText(log.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

}

but it does not seem to work. Worse is debug isnt giving helpful information. I have also set the required manifest file permissions

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

What is it i am missing? just executing the command logcat -d | grep "ANR" -A 38 gives the required logcat data inside the shell, but when i run it from within the app, i get nothing. The lines in the while loop are null.

Thanks!

UPDATE: The app is installed as a system app, and the logs to be read are from other apps that encounter the ANR error.

Chakson
  • 23
  • 8
  • since Android 4.1 3rd-party apps can't use `android.permission.READ_LOGS` permission. You can't read logcat from your app unless it is a system app, or it has root permissions – Vladyslav Matviienko Nov 20 '19 at 13:45
  • I have seen that information, but the problem is, even as a system app i cannot get the log. At least it does not appear on the textview, since i cant debug the app once i install it as a system app – Chakson Nov 20 '19 at 13:47

1 Answers1

0

I found out a working solution.

As of Android 4.1+, apps can no longer access the logs from other apps.

The shell user is able to get the log from other applications, so a simple thing like

String[] cmd = {
            "/system/bin/sh",
            "-c",
            "logcat -d | grep \"ActivityManager: ANR\" -A 38"
        };

        Process process = Runtime.getRuntime().exec(cmd);

can give us the log from other apps. Even if the app itself can not access the needed logs from other apps, doing so will trigger the command as the shell user who has the required permissions. Just save it to a string and parse it depending on the needs. Cheers!

Chakson
  • 23
  • 8