【问题标题】:How can I print the full logcat history in a TextView in Android?如何在 Android 的 TextView 中打印完整的 logcat 历史记录?
【发布时间】:2016-04-24 03:47:30
【问题描述】:

我正在使用 logcat 在我的 Android 应用程序中记录消息,我希望能够访问这些消息并将它们显示在 DialogFragment 的 TextView 中。消息列表非常不一致,每次打开和关闭对话框时都会发生变化。它会显示一次完整的历史记录,然后在下一次擦除时,有时会显示更多消息。每次打开对话框时,我可以做些什么来显示所有消息(用于运行)?我是在错误的时间运行该过程还是什么?或者缓冲区应该在其他地方处理吗?谢谢。

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_view_logs:
            // View Logs MenuItem tapped
            if (logsDialogFragment == null) {
                logsDialogFragment = new LogsDialogFragment();
            }
            logsDialogFragment.show(getFragmentManager(), "dialog");
            return true;
        case R.id.action_exit:
            // Exit MenuItem tapped
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public class LogsDialogFragment extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Log.i(WifiDirectHandler.LOG_TAG, "Viewing Logs");
    AlertDialog.Builder dialogBuilder =  new  AlertDialog.Builder(getActivity())
        .setTitle(getString(R.string.title_logs))
        .setNegativeButton(getString(R.string.action_close),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                }
            }
        );

    LayoutInflater i = getActivity().getLayoutInflater();
    View rootView = i.inflate(R.layout.fragment_logs_dialog, null);

    TextView logTextView = (TextView) rootView.findViewById(R.id.logTextView);
    logTextView.setMovementMethod(new ScrollingMovementMethod());

    try {
        Process process = Runtime.getRuntime().exec("logcat -d");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        StringBuilder log = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains(WifiDirectHandler.LOG_TAG)){
                // Removes log tag and PID from the log line
                log.append(line.substring(line.indexOf(": ") + 2)).append("\n");
            }
        }
        logTextView.setText(log.toString());
    } catch (IOException e) {
    }

    dialogBuilder.setView(rootView);
    return dialogBuilder.create();
}
}

【问题讨论】:

  • logTextView 显示结果吗?
  • 是的,但是每次打开和关闭对话框的结果都不一样。
  • 结果不一样,很自然,Log cat 显示不一样,看详细,你可能不一样..

标签: android android-fragments logging logcat android-logcat


【解决方案1】:

消息的 logcat 缓冲区不是很大,所以旧消息只会从 logcat 中删除,如果您需要完整的日志 - 将 logcat 消息保存到 sdcard 上的文件,然后从中读取信息。此方法会将所有当前消息保存到文件中:

public static void saveLogcatToFile(Context context) {
        String fileName = "yourlogname.log";
        File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/YourAppName", fileName);
        try {
            @SuppressWarnings("unused")
            Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

上面的代码只是某个时间点的日志快照。如果您想连续写入日志,请使用带有 FileLogger 的 Java 日志记录并写入。

【讨论】:

    【解决方案2】:
    Please add permission in manifest for logcat <uses-permission android:name="android.permission.READ_LOGS" />
    

    【讨论】:

      【解决方案3】:

      我最终将历史记录保存到一个成员变量中,并且每次打开对话框时只附加新的日志行。

      public class LogsDialogFragment extends DialogFragment {
      
          private StringBuilder log = new StringBuilder();
      
          @Override
          public Dialog onCreateDialog(Bundle savedInstanceState) {
              // Sets the Layout for the UI
              LayoutInflater i = getActivity().getLayoutInflater();
              View rootView = i.inflate(R.layout.fragment_logs_dialog, null);
      
              TextView logTextView = (TextView) rootView.findViewById(R.id.logTextView);
              logTextView.setMovementMethod(new ScrollingMovementMethod());
      
              try {
                  Process process = Runtime.getRuntime().exec("logcat -d");
                  BufferedReader bufferedReader = new BufferedReader(
                          new InputStreamReader(process.getInputStream()));
      
                  StringBuilder log = new StringBuilder();
                  String line;
                  while ((line = bufferedReader.readLine()) != null) {
                      if (line.contains(WifiDirectHandler.LOG_TAG)){
                          // Removes log tag and PID from the log line
                          log.append(line.substring(line.indexOf(": ") + 2)).append("\n");
                      }
                  }
      
                  this.log.append(log.toString().replace(this.log.toString(), ""));
                  logTextView.setText(this.log.toString());
              } catch (IOException e) {
                  Log.e("wifiDirectHandler", "Failure reading logcat");
              }
      
              // Creates and returns the AlertDialog for the logs
              AlertDialog.Builder dialogBuilder =  new  AlertDialog.Builder(getActivity())
                  .setTitle(getString(R.string.title_logs))
                  .setNegativeButton(getString(R.string.action_close),
                      new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int whichButton) {
                              dialog.dismiss();
                          }
                      }
                  ).setView(rootView);
              return dialogBuilder.create();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-02
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多