0xAliHn
0xAliHn

Reputation: 19280

Read logs from code programmatically and matching with a string in android app

How can we read logs(verbose,debug etc) programmatically from android class and then search for a string or matching with a provided string in android.

Sometimes we need to handle some system or kernel layer related event. But as we have limited access of those code we can't handle them. We can see the logcat via adb and also see some log comes from kernel/framework layer.

Now the question is, How we can override or handling some event in our app based on those logs?

Upvotes: 1

Views: 889

Answers (1)

0xAliHn
0xAliHn

Reputation: 19280

Here is a solution to this from any android app:

We need to make a class with some code like below:

public class LogsUtil {
    private static final String processId = Integer.toString(android.os.Process
            .myPid());

    public static StringBuilder readLogs() {
        StringBuilder logBuilder = new StringBuilder();
        try {
            String[] command = new String[] { "logcat", "-d", "threadtime" };
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(processId)) {
                    logBuilder.append(line);
                    //Code here
                }
            }
        } catch (IOException e) {
        }
        return logBuilder;
    }
}

Then need to write below code in our activity from where we need to check the logs string:

//read the logs    
StringBuilder logs = LogsUtil.readLogs();

    if(logs.toString().contains("your_text"))
        //your code
    else //your code

Upvotes: 1

Related Questions