以编程方式从代码中读取日志并与android应用中的字符串匹配 [英] Read logs from code programmatically and matching with a string in android app

查看:30
本文介绍了以编程方式从代码中读取日志并与android应用中的字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何通过编程方式从android类读取日志(详细,调试等),然后在Android中搜索字符串或与提供的字符串匹配.

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.

有时我们需要处理一些与系统或内核层相关的事件.但是由于我们对这些代码的访问受到限制,因此无法处理它们.我们可以通过adb查看logcat,还可以看到一些来自内核/框架层的日志.

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?

推荐答案

以下是任何Android应用程序对此的解决方案:

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

这篇关于以编程方式从代码中读取日志并与android应用中的字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆