How do you scan logcat output and post event based on found text?

点点圈 提交于 2019-12-22 01:26:15

问题


I would like to scan logcat activity and post and event if I find my desired text. I am trying to approach here:

Logging logcat activity

but I would like to know how to react to what I find in the log, such as posting an event so another object can handle it.


回答1:


Get the string of all log messages as posted in the answer you mentioned. Then, simply search the string using regular expressions.

For example,

String result = //... get the logs ...

if(result.contains("trigger text i am looking for")){
  myObject.raiseEvent();
}

EDIT

If you are trying to do a constant monitoring of the logcat, this will be much more difficult. For one, the process might get shut down without warning. So you need a way to keep it running, or to constantly check that it is running.

Secondly, the solution you linked to would not work in this case, as that waits until stopLogging is called, then returns the entire log for the recorded interval.

Also, you'll have to modify that code so that it has a list of trigger words and their associated callback functions to run.

while ((line = reader.readLine()) != null){
 for(int i =0; i < triggerList.size(); i++){
   TriggerPhrase trigger = triggerList.get(i);
   if(line.contains(trigger.phrase))
   {
     trigger.onTriggerPhrase(line);
   }
 } 
}

where TriggerPhrase is a simple class that has a String phrase member variable and an object that implements a callback function.

public static class TriggerPhrase implements TriggerListener{
  String phrase;
  TriggerListener callback;
}

public interface TriggerListener{
   public void onTriggerPhrase();
}

Then before you start listening the logs, you populate the triggerPhrases List in the LogCat listener.

TriggerPhrase monkeyPhrase = new TriggerPhrase();
monkeyPhrase.phrase = "monkeys";
monkeyPhrase.callback = new TriggerListener(){
  public void onTriggerPhrase(){
    notifyUser("found the phrase `monkeys` in the logcat");
  }
};
triggerPhrases.add(monkeyPhrase);
//etc.


来源:https://stackoverflow.com/questions/16429349/how-do-you-scan-logcat-output-and-post-event-based-on-found-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!