Android Apk抓取日誌並保存的方法

原文鏈接:https://github.com/fatangare/LogcatViewer

今天偶然的在網絡上看到應用層直接抓取系統日誌的方法,我停下腳步就研究了下到底怎麼實現的,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;
    }
	

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章