Android Apk抓取日志并保存的方法

今天偶然的在网络上看到应用层直接抓取系统日志的方法,我停下脚步就研究了下到底怎么实现的,github上已经有大牛写了aar包出来直接AS引用就可以了。

github地址:https://github.com/fatangare/LogcatViewer

其实核心代码就一行,执行了Android Shell下的logcat命令而已。

/system/bin/logcat -b main
 public static final String LOGCAT_SOURCE_BUFFER_MAIN = "main";
    public static final String LOGCAT_SOURCE_BUFFER_RADIO = "radio";
    public static final String LOGCAT_SOURCE_BUFFER_EVENTS = "events";

    /**
     * Top Logcat logger directory to save log entries.
     */
    private static final String LOG_RECORD_DIR = "/LogcatViewer/";

    /**
     * Get directory where logs are saved.
     *
     * @param context application context.
     * @return directory File object.
     */
    public static File getRecordDir(Context context) {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + LOG_RECORD_DIR + context.getPackageName());
    }
    int logSize=1;
    private void runLogcatSubscriber() {
        Process process = null;

        //Execute logcat system command
        try {
            process = Runtime.getRuntime().exec("/system/bin/logcat -b " + LOGCAT_SOURCE_BUFFER_MAIN);
        } catch (IOException e) {
            PrintLog.d(""+e);
        }

        //Read logcat log entries
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String logEntry;
            boolean isRun=true;
            //Till request to kill thread is not received, keep reading log entries
            while (isRun) {
                //Read log entry.
                logEntry = reader.readLine();
                logSize++;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            printInfo.setText(""+logSize);
                        }
                    });
                PrintLog.d(logEntry);
                //If recording is on, save log entries in mRecordingData in order to save them
                // after every LOG_SAVING_INTERVAL interval
            }
        } catch (IOException e) {
            //Fail to read logcat log entries
            PrintLog.d(""+e);
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process!=null) {
                process.destroy();
            }
        }
        return;
    }
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值