android 应用中监控指定log并获取其数据

Android应用中需要过滤相应的log,通过log来获取数据,监控方法如下:
package com.example.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

public class ScannerLogParser {
	private Process logParserProcess = null;
	private List<Integer> times;

	public void start() {
		if (logParserProcess != null) {
			return;
		}

		times = new ArrayList<Integer>();
       
		new Thread() {
			@Override
			public void run() {
				try {
					//清掉以前的log
					Runtime.getRuntime().exec("logcat -c");
				} catch (IOException e) {
				}
				BufferedReader reader = null;
				try {
					/**过滤tag =zzml 级别的debug的主缓冲区中的log*/
					String[] cmd = { "logcat", "-b", "main", "zzml:D", "*:S" };
					Log.v("zzml", cmd.toString());
					logParserProcess = Runtime.getRuntime().exec(cmd);
					reader = new BufferedReader(new InputStreamReader(logParserProcess.getInputStream()));
					String line = null;
					while ((line = reader.readLine()) != null) {
						if (!line.contains("hello")) {//log中含有的关键字
							continue;
						}
						Log.v("zzml", "监控到数据--》"+line);
						String[] strs = line.split("hello");
						if (strs.length != 2) {
							continue;
						}
						String str = strs[1].trim();
						if (str.endsWith("ms")) {
							try {
								Integer time = Integer.valueOf(str.substring(0, str.length()-2));
								times.add(time);
							} catch (Exception e) { }
						}
					}
					logParserProcess.waitFor();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();
						} catch (IOException e) {
						}
					}
					logParserProcess = null;
				}
			}
		}.start();
	}

	/**
	 * 停止log监听
	 */
	public void stop() {
		logParserProcess.destroy();
		logParserProcess = null;
	}

	public List<Integer> getTimes() {
		return times;
	}
}
具体使用:
<pre name="code" class="java">// 启动log监控分析线程
		ScannerLogParser logParser = new ScannerLogParser();
		logParser.start();

		
	    //结束时停止log分析线程
		logParser.stop();
  <uses-permission android:name="android.permission.READ_LOGS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值