Read logcat programmatically for an application

后端 未结 1 1820
清酒与你
清酒与你 2020-12-29 15:53

I\'ve read this article already. But it seems most of the text it shows are not in my application. How can I filter the message and let it only shows the log for my applicat

相关标签:
1条回答
  • 2020-12-29 16:06

    Try following code to get logs of your application only.

    public final class MyAppLogReader {
    
        private static final String TAG = MyAppLogReader.class.getCanonicalName();
        private static final String processId = Integer.toString(android.os.Process
                .myPid());
    
        public static StringBuilder getLog() {
    
            StringBuilder builder = new StringBuilder();
    
            try {
                String[] command = new String[] { "logcat", "-d", "-v", "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)) {
                        builder.append(line);
                        //Code here
                    }
                }
            } catch (IOException ex) {
                Log.e(TAG, "getLog failed", ex);
            }
    
            return builder;
        }
    }
    

    Edit

    Add below permission to your AndroidManifest file

    <uses-permission android:name="android.permission.READ_LOGS" />
    
    0 讨论(0)
提交回复
热议问题