'How to grep specific log from android device using Java code on runtime

I'm trying to grep log from android device on runtime to perform assertion, is there a way I can achieve the same, while passing below code seems working but its keep running, how can I end this after certain time

        String log = "";
        String str;
        try {
            String myStringArray[]= {"logcat", "| grep XYZ "};
            Process process = Runtime.getRuntime().exec(myStringArray);
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            str = br.readLine();
            while (str != null) {
                log += str;
                str = br.readLine();
            }
        } catch (IOException e) {
            System.out.println("Getting IOException .......");
        }
        return log;
    } ```

I believe I'm missing something here


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source