0

我正在尝试找到一种在 Activity 的 TextView 中显示日志消息的好方法。我尝试在 TextView 中显示 logcat 消息,但每次打开和关闭 Fragment 时结果都会有所不同,并且并非所有消息都显示出来。我正在登录多个活动和课程,所以我试图找到一种不将其耦合到每个课程的登录方式。有没有 logcat 或其他东西的替代品,我可以访问和显示的某种类型的系统日志记录?或者任何有用的库或任何东西?

谢谢

4

3 回答 3

2

在登录 Android 时,我绝对推荐: https ://github.com/JakeWharton/timber

例如,你不需要一直做那个烦人的 TAG,因为 Timber 会为你做这件事。

关于您的问题,我认为您可以做些什么来在木材中种植自己的树。这将确保所有日志记录都通过那里,并且您可以从那里捕获并记录您想要的所有内容。查看他在应用程序中种植树的示例:https ://github.com/JakeWharton/timber/blob/master/timber-sample/src/main/java/com/example/timber/ExampleApp.java 现在这个位于应用程序层中,因此您需要以某种方式将它们提取到您的活动中。一个快速的方法,不是很漂亮的方法,我认为你可以做的是将日志存储在一个集合中,并让这个静态访问以从应用程序中获取。

顺便说一句,我很好奇你为什么想要这个,为什么 Android Studio 的日志工具不够好?:)

于 2016-04-24T20:06:25.690 回答
1

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

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();
    }
}
于 2016-04-29T01:43:20.577 回答
0

Toast 在一个小弹出窗口中提供有关操作的简单反馈:

Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show();

在此处输入图像描述

于 2016-04-24T20:01:52.053 回答