Android 实现在界面实时打印log

要实现在Android 界面实时打印log,需要注意以下三点:
1、需要文件用来存储log
2、要实现实时打印,本文采用广播的形式
3、打印的log 以多个textview 的形式展现出来

既然要通过文件来保存log,自然少不了要对文件进行增删 读写的操作,代码如下:

public class FileController {

    private Context mContext;
    private volatile static FileController m_instance;
    private final String LOG_FILENAME = "LOG_FILE";
    private FileController(){
    }

    public static synchronized FileController getFileControl() {
        if (m_instance == null) {
            synchronized (RpcTestDataControlIF.class) {
                if (m_instance == null) {
                    m_instance = new FileController();
                }
            }
        }
        return m_instance;
    }

    public void init(Context context) {
        mContext = context;
    }


    public void deleteLogFile(){
        try {
            File file = new File(mContext.getFilesDir(), LOG_FILENAME);

            if(file.exists()){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String readFromLogFile() {
        File file = new File(mContext.getFilesDir(), LOG_FILENAME);
        String data = null;
        BufferedReader br = null;
        if(!file.exists())
            return null;
        try {
            br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n\r");
                line = br.readLine();
            }
            data = sb.toString();
            if(!data.isEmpty()){
                return data;
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return data;
        }
    }

    public void writeToLogFile(String s) {
        if (s == null) return;
        FileOutputStream outputStream = null;

        try {
            File file = new File(mContext.getFilesDir(), LOG_FILENAME);
            outputStream = new FileOutputStream(file, true); // will overwrite existing data

            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        try {
            outputStream.write(s.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

FileController 初始化的时候需要传入Context 对象的实例,方便获取文件路径。

至此,实现了读写log 文件的操作,在log打印界面初始化的时候可以读取到已经存储到log文件中的log。在log界面可以将

读取到的log 以textview 的形式打印出来,大体代码如下:

public class LogFragment extends Fragment {
    private ScrollView loggerText;
    private LinearLayout logfield;

    private LogReceiver logReceiver;

//监听广播,实时添加textview
    private class LogReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String text = arg1.getStringExtra(...);
            logTextToScroll(text);
        }
    }


//界面初始化的时候可读取已经保存的log
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_log, container, false);
        loggerText = v.findViewById(R.id.log);
        logfield = v.findViewById(R.id.linearLayout1);

        logTextToScroll(FileController.getFileControl().readFromLogFile());
        return v;
    }


//注册广播
 @Override
    public void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter();

        logReceiver = new LogReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(LOG_TEXT_ACTION);
        getActivity().registerReceiver(logReceiver, intentFilter);
    }


@Override
    public void onResume() {
        super.onResume();
        loggerText.post(new Runnable() {
            @Override
            public void run() {
                loggerText.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

//注销receiver
    @Override
    public void onStop() {
        super.onStop();
        getActivity().unregisterReceiver(logReceiver);
    }


//删除log文件
    @Override
    public void onDestroy() {
        super.onDestroy();
        FileController.getFileControl().deleteLogFile();
    }

//将带有log的textview 添加进布局中
private void logTextToScroll(String s){
        if(s == null || s.isEmpty())
            return;

        TextView t = new TextView(getContext());
        s += "\n";
        t.setText(s);
        logfield.addView(t);
    }

//清除界面的log,可以在界面添加button 或者菜单,通过点击实现清除log
    private void clearLog(){
        for(int i = 0; i < logfield.getChildCount(); i++){
            TextView t = (TextView) logfield.getChildAt(i);
            t.setText("");
            logfield.removeAllViews();
        }
    }

}

至此,界面的log打印的逻辑已经差不多了,现在要做的就是在你需要打印log的代码的地方添加写入log文件以及发送广播的操作,这样log就能打印到你所设计的界面上了,如下:

    private void logMessage(String message){

//添加时间点
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String log = timestamp.toString() + "\n" + message + "\n\r";
        Intent intent = new Intent(LOG_TEXT_ACTION);
        intent.putExtra(LOG_TEXT_EXTRA, log);
        sendBroadcast(intent);
        FileController.getFileControl().writeToLogFile(log);
    }

 

你可能感兴趣的:(Android,UI)