从应用程序实时读取logcat

时间:2014-09-17 06:32:08

标签: android logcat

我想从应用程序中读取logcat(并在日志中显示特定字符​​串的屏幕)。 但是到目前为止我尝试的所有内容都会导致应用停止(按钮看起来很紧,键盘什么也没做) 有任何想法吗? 到目前为止,这是我的代码(从互联网上复制):

try {
    Runtime.getRuntime().exec("su").waitFor();
    Runtime.getRuntime().exec("logcat -c").waitFor();

    Process process = Runtime.getRuntime().exec("logcat");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = bufferedReader.readLine()) != null) {
        if(line.contains(s)){
            Toast.makeText(MainActivity.this, "found S!", Toast.LENGTH_SHORT).show();
            break;
        }
    }
}catch (IOException e) {}

2 个答案:

答案 0 :(得分:2)

试试这段代码:

    log = (TextView)findViewById(R.id.log);
    logContainer = (ScrollView)findViewById(R.id.logContainer);

        new AsyncTask<Void, String, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Process process = Runtime.getRuntime().exec("logcat");
                    BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));

                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        if (line.contains("<<<<<<<<YOUR TAG>>>>>>>>"))
                            publishProgress(line);
                    }
                }
                catch (IOException e) {
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(String... values) {
                log.append(values[0] + "\n");
                logContainer.post(new Runnable() {
                    @Override
                    public void run() {
                        logContainer.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }.execute();

答案 1 :(得分:0)

您可以运行logcat并阅读服务中的日志。

请参阅logdog,我用它来阅读logcat,它运行正常。

简单示例:

/* put these code in onCreate() of a service */
Process process = Runtime.getRuntime().exec("su");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
DataOutputStream dos = new DataOutputStream(process.getOutputStream());
dos.writeBytes("logcat -b events -v time\n");
dos.flush();

/* read log, put these code out of onCreate() in service and periodically call this code */
while (reader.ready()) {
    line = reader.readLine();
    //handle the log
}