在APP正式環(huán)境中對(duì)于用戶產(chǎn)生的一些問題田度,不方便判斷的異惩逯妫或者一些實(shí)用的定位問題的信息樟氢。但是又不能把用戶的手機(jī)連接到電腦上冈绊。尤其是像我們應(yīng)用的http請(qǐng)求的數(shù)據(jù)都是加密的,即使通過抓包也無法看到數(shù)據(jù)格式埠啃,這時(shí)候多想能看到用戶手機(jī)輸出的log啊死宣。所以我就想能不能通過手機(jī)獲取控制臺(tái)的log并顯示顯示出來呢。要實(shí)現(xiàn)這種功能需要準(zhǔn)備兩個(gè)庫
1.日志收集的庫
https://github.com/ljuns/LogCollector
2.顯示浮窗
https://github.com/princekin-f/EasyFloat
有了這兩個(gè)庫我們就可以愉快的開始了:
第一步:開始日志獲取
LogCollector.getInstance(application)
.setCleanCache(true)
.setTag("OkHttp")
.start()
第二步:顯示浮窗
private fun showFloatWindown() { EasyFloat.with(this)
.setTag("logFloat")
.setShowPattern(ShowPattern.FOREGROUND)
.setMatchParent(widthMatch = true, heightMatch = false)
.setAppFloatAnimator(null)
.setLayout(R.layout.common_float_app_log, OnInvokeView { val rcvLog = it.findViewById<RecyclerView>(R.id.rcvLog) val llConsoler = it.findViewById<LinearLayout>(R.id.llConsoler) val tvClear = it.findViewById<TextView>(R.id.tvClear) tvClear.setOnClickListener { LogCollector.getInstance(application).logChangeObserver.clear() } val logChangeObserver = LogCollector.getInstance(application).logChangeObserver val logAdapter = LogAdapter(logChangeObserver.arrayList as ArrayList<String>) rcvLog.setAdapter(logAdapter) logChangeObserver.addObserver(logAdapter) it.findViewById<View>(R.id.iv_head).setOnClickListener { //如果顯示則隱藏碴开,如果隱藏則關(guān)閉 if(llConsoler.visibility == View.VISIBLE){ llConsoler.visibility = View.GONE it.setBackgroundColor(Color.TRANSPARENT) }else{ llConsoler.visibility = View.VISIBLE it.setBackgroundColor(getColorRes(R.color.transparent40)) } } })
.show()
}
這樣實(shí)現(xiàn)就可以直接獲取當(dāng)前控制臺(tái)已經(jīng)輸出的信息了毅该。并保存到sdcard目錄
但是如果我想一直實(shí)時(shí)獲取控制臺(tái)的信息潦牛,并顯示到手機(jī)頁面呢。這時(shí)候需要對(duì)日志收集庫做一些小小的修改。
找到源碼中的LogRunnable類寝殴,在run方法中添加一個(gè)while循環(huán)
private class LogRunnable implements Runnable { volatile boolean isCrash = false; @Override public void run() {
while (!isCrash){
List<String> getCommandLine = new ArrayList<>(); createGetCommand(getCommandLine); BufferedReader reader = null; BufferedWriter writer = null; try { createCleanCommand(); // 獲取 logcat Process process = Runtime.getRuntime().exec( getCommandLine.toArray(new String[getCommandLine.size()])); reader = new BufferedReader( new InputStreamReader(process.getInputStream(), UTF8));// writer = new BufferedWriter(// new OutputStreamWriter(new FileOutputStream(mCacheFile), UTF8)); String str; while (!isCrash && ((str = reader.readLine()) != null)) { createCleanCommand(); if (filterStringType(str)) { continue; } // 寫數(shù)據(jù)// writer.write(str);// writer.newLine();// writer.flush(); //直接寫到內(nèi)存中 logChangeObserver.addStr(str); } } catch (IOException e) { e.printStackTrace(); } finally { CloseUtils.close(reader); CloseUtils.close(writer);
}
}
}
}
然后通過ArrayList將日志字符串保存到內(nèi)容中,交給RecyclerView去顯示贞绳。
這樣所有的工作就完成了冈闭。