概述
stetho是Facebook開源的一個(gè)Android調(diào)試工具,項(xiàng)目地址:facebook/stetho 通過Stetho,開發(fā)者可以使用chrome的inspect功能,對(duì)Android應(yīng)用進(jìn)行調(diào)試和查看。 功能概述
stetho提供的功能主要有:
在這里,筆者先承認(rèn)這個(gè)文章有點(diǎn)標(biāo)題黨了——在我實(shí)際使用體驗(yàn)過后,第一感覺是:這個(gè)所謂神器也沒有特別神的感覺…造成首次使用感覺不太好的原因在于:
后面將會(huì)對(duì)Dump App和Network Inspection進(jìn)行詳細(xì)介紹(其他的幾個(gè)功能都比較簡單)。
初始化Stetho
首先引入在安卓項(xiàng)目中引用必要的依賴包,可以使用gradle,也可以直接下載jar包。
dependencies { compile 'com.facebook.stetho:stetho:1.5.0' }
需要注意的是如果使用Javascript Console需要額外引入facebook/stethostetho-js-rhino和mozilla/rhino。 然后在應(yīng)用的Application初始化時(shí),進(jìn)行Stetho初始化。這些都在官網(wǎng)有詳細(xì)的說明,不再贅述了。
開始使用
由于大部分功能依賴于Chrome DevTools 所以第一步你需要先打開Chrome,然后在瀏覽器地址欄輸入:chrome://inspect 接觸過前端開發(fā)或者Webview開發(fā)的捧油應(yīng)該是很熟悉這個(gè)套路了。你會(huì)看到一個(gè)如下界面:
inspect界面
你會(huì)發(fā)現(xiàn)這里有兩項(xiàng),是因?yàn)槲业倪@個(gè)示例應(yīng)用有兩個(gè)進(jìn)程。由于App的每個(gè)進(jìn)程都會(huì)單獨(dú)創(chuàng)建一個(gè)Application,所以在應(yīng)用包含多個(gè)進(jìn)程時(shí),Stetho也會(huì)為每個(gè)進(jìn)程都初始化一次。那么這里我要調(diào)試的是主進(jìn)程,就點(diǎn)擊第一項(xiàng)inspect就行了。 接下來我們就開始搞事情了:
View Hierarchy
查看布局層級(jí)沒啥好說的,但是之前提到,由于系統(tǒng)的view層級(jí)也包括進(jìn)來了,所以我們Activity的Layout層級(jí)都很深,每次一層一層點(diǎn)開很難找,這里提供一個(gè)簡便方法,在Elements面板,按Ctrl + F,搜索 @android:id/content 即可快速定位到我們當(dāng)前界面根布局,例如這里的Constraintlayout:
Database Inspection
點(diǎn)擊Resource-Web SQL即可查看App的數(shù)據(jù)庫:
Javascript Console
在Console面板,輸入context可以看到目前的ApplicationContext:
輸入如下代碼彈出Toast:
importPackage(android.widget);importPackage(android.os);var handler = new Handler(Looper.getMainLooper());handler.post(function() { Toast.makeText(context, "Hello from JavaScript", Toast.LENGTH_LONG).show() });
應(yīng)用場(chǎng)景比較有限,但是mozilla/rhino這個(gè)Javascript引擎倒是挺有意思的,可以用來做一些有趣的事情,以后有機(jī)會(huì)再分享一下。
Dump App
官方對(duì)dump app的使用說明實(shí)在太少了,感覺非常捉急。研究了一番,大概知道了使用流程,即首先需要在App內(nèi),通過enableDumpapp方法注冊(cè)自己的插件: Stetho.initialize(Stetho.newInitializerBuilder(context)
.enableDumpapp(new DumperPluginsProvider() { @Override public Iterable<DumperPlugin> get() { return new Stetho.DefaultDumperPluginsBuilder(context) .provide(new MyDumperPlugin()) .finish(); }}).enableWebKitInspector(Stetho.defaultInspectorModulesProvider(context)).build())
也可以使用默認(rèn)的插件: Stetho.initialize(Stetho.newInitializerBuilder(this)
.enableDumpapp(new DumperPluginsProvider() { public Iterable<DumperPlugin> get() { return (new Stetho.DefaultDumperPluginsBuilder(StethoNetworkApplication.this)).finish(); } }).enableWebKitInspector(Stetho.defaultInspectorModulesProvider(context)).build())
然后,stetho的github項(xiàng)目地址下有一個(gè)script文件夾:facebook/stetho-script 把這個(gè)文件夾下到本地,發(fā)現(xiàn)里面有幾個(gè)文件: .gitignore dumpapp hprof_dump.sh stetho_open.py 說實(shí)話第一眼看上去根本不知道這東西干啥用的,dumpapp這文件看起來就跟可執(zhí)行文件似的,但事實(shí)上它又不是exe,用記事本打開一看,是Python3的文件,我也是醉了…
所以使用Python3.x來運(yùn)行這個(gè)文件即可。(由于他還引用了stetho_open.py,為了看起來不那么別扭,我把幾個(gè)文件都整合在一齊,搞了一個(gè)dump.py) 這里我并沒有注冊(cè)任何插件,但是由于Stetho自帶了幾個(gè)插件,我們可以看看他們的實(shí)現(xiàn):
例如files插件,來試用一下:
即用戶發(fā)送命令時(shí),Plugin的dump方法會(huì)被調(diào)用,Plugin通過dumpContext.getStdout()來獲取輸出流,將反饋輸出到命令行:
public void dump(DumperContext dumpContext) throws DumpException { Iterator<String> args = dumpContext.getArgsAsList().iterator(); String command = ArgsHelper.nextOptionalArg(args, ""); if("ls".equals(command)) { this.doLs(dumpContext.getStdout()); } else if("tree".equals(command)) { this.doTree(dumpContext.getStdout()); } else if("download".equals(command)) { this.doDownload(dumpContext.getStdout(), args); } else { this.doUsage(dumpContext.getStdout()); if(!"".equals(command)) { throw new DumpUsageException("Unknown command: " + command); } } }
Network Inspection
其實(shí)這也是重點(diǎn)之一了。我在這里添加了一個(gè)OkHttp的Inspector。 注意:此處有坑,因?yàn)槟銜?huì)發(fā)現(xiàn)用gradle添加的stetho依賴中沒有StethoInterceptor這個(gè)類,你可以到stetho的github頁面下載一下,同事需要跟你的OkHttp版本對(duì)應(yīng),因?yàn)?.x跟3.x對(duì)應(yīng)的StethoInterceptor還有差異): 下載地址: facebook/stetho-okhttp3 facebook/stetho-okhttp 代碼示例如下: public void testOkHttp(){
Thread thread = new Thread(new Runnable() { @Override public void run() { String url = "http://www.zhihu.com/"; OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor());
OkHttpClient client = builder.build(); Request request = new Request.Builder() .url(url) .get() .build(); try { Response response = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } }});thread.start();}
運(yùn)行這個(gè)函數(shù),可以看到Network一欄的請(qǐng)求,每項(xiàng)網(wǎng)絡(luò)請(qǐng)求發(fā)出時(shí),Status處于Pending狀態(tài),收到回包后,Status等欄目都會(huì)變化,展示httpcode,請(qǐng)求耗時(shí)、回包數(shù)據(jù)類型等信息。
當(dāng)然這不是重點(diǎn)。重點(diǎn)是我們要對(duì)這個(gè)東西改造一下,他是如何抓下包來發(fā)送給Chrome的呢? 看一下StethoInterceptor的intercept函數(shù),寫了些注釋:
private final NetworkEventReporter mEventReporter = NetworkEventReporterImpl.get();public Response intercept(Chain chain) throws IOException { // 構(gòu)造一個(gè)獨(dú)特的eventID,一對(duì)網(wǎng)絡(luò)事件(請(qǐng)求和回包)對(duì)應(yīng)一個(gè)eventID String requestId = mEventReporter.nextRequestId(); Request request = chain.request(); // 準(zhǔn)備發(fā)送請(qǐng)求 RequestBodyHelper requestBodyHelper = null; if (mEventReporter.isEnabled()) { requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId); OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper); // 請(qǐng)求即將發(fā)送,構(gòu)造一個(gè)OkHttpInspectorRequest,報(bào)告給Chrome,此時(shí)Network會(huì)顯示一條請(qǐng)求,處于Pending狀態(tài) mEventReporter.requestWillBeSent(inspectorRequest); } Response response; try { // 發(fā)送請(qǐng)求,獲得回包 response = chain.proceed(request); } catch (IOException e) { // 如果發(fā)生了IO Exception,則通知Chrome網(wǎng)絡(luò)請(qǐng)求失敗了,顯示對(duì)應(yīng)的錯(cuò)誤信息 if (mEventReporter.isEnabled()) { mEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (mEventReporter.isEnabled()) { if (requestBodyHelper != null && requestBodyHelper.hasBody()) { requestBodyHelper.reportDataSent(); } Connection connection = chain.connection(); // 回包的header已收到,構(gòu)造一個(gè)OkHttpInspectorResponse,發(fā)送給Chrome用于展示 mEventReporter.responseHeadersReceived( new OkHttpInspectorResponse( requestId, request, response, connection)); // 展示回包信息 ResponseBody body = response.body(); MediaType contentType = null; InputStream responseStream = null; if (body != null) { contentType = body.contentType(); responseStream = body.byteStream(); } responseStream = mEventReporter.interpretResponseStream( requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId)); if (responseStream != null) { response = response.newBuilder() .body(new ForwardingResponseBody(body, responseStream)) .build(); } } return response; }
所以整個(gè)流程我們可以簡化為:發(fā)送請(qǐng)求時(shí),給Chrome發(fā)了條消息,收到請(qǐng)求時(shí),再給Chrome發(fā)條消息(具體怎么發(fā)的可以看NetworkEventReporterImpl的實(shí)現(xiàn)) 兩條消息通過EventID聯(lián)系起來,它們的類型分別是OkHttpInspectorRequest 和 OkHttpInspectorResponse,兩者分別繼承自NetworkEventReporter.InspectorRequest和NetworkEventReporter.InspectorResponse。我們只要也繼承自這兩個(gè)類,在自己的網(wǎng)絡(luò)庫發(fā)送和收到請(qǐng)求時(shí),構(gòu)造一個(gè)Request和Response并發(fā)送給Chrome即可。 發(fā)送部分示例:
PulseInspectorRequest 繼承自NetworkEventReporter.InspectorRequest public void reportRequestSend(PulseInspectorRequest request){ String requestId = request.id(); // request will be sent RequestBodyHelper requestBodyHelper = null; if (mEventReporter.isEnabled()) { requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId); mEventReporter.requestWillBeSent(request); // report request send if (requestBodyHelper.hasBody()) { requestBodyHelper.reportDataSent(); } } }
回包獲取成功:
public void reportRequestSuccess(PulseInspectorResponse response){ mEventReporter.responseHeadersReceived(response); mEventReporter.responseReadFinished(response.requestId()); String requestId = response.requestId(); String contentType = "application/json"; String encoding = null; InputStream responseStream = new ByteArrayInputStream(response.getResponseBody().getBytes()); InputStream responseHandlingInputStream = mEventReporter.interpretResponseStream( requestId, contentType, encoding, responseStream, new DefaultResponseHandler(mEventReporter, requestId)); try { if (responseHandlingInputStream == null) return; // 重點(diǎn)在這,這兩行代碼一定要加上,StethoInterceptor之所以不需要加, // 是因?yàn)镺kHttp本身對(duì)請(qǐng)求采取了職責(zé)鏈?zhǔn)降奶幚恚? // 雖然在StethoInterceptor的intercept函數(shù)里沒有進(jìn)行read和close // 但是后續(xù)的Interceptor會(huì)進(jìn)行這個(gè)操作,實(shí)際上這里,才把回包數(shù)據(jù)發(fā)送給了Chrome responseHandlingInputStream.read(response.getResponseBody().getBytes()); responseHandlingInputStream.close(); } catch (IOException e) { e.printStackTrace(); }}
回包獲取失敗
public void reportRequestFail(String eventId,String errMsg){ mEventReporter.httpExchangeFailed(eventId, errMsg);}
至于PulseInspectorResponse 和PulseInspectorRequest如何實(shí)現(xiàn),就依賴實(shí)際使用場(chǎng)景了。
stetho 為開發(fā)者提供了一個(gè)很好的調(diào)試手段,但是自帶的基礎(chǔ)功能還比較弱,開發(fā)者可以根據(jù)自己的需求去改造。(不過官網(wǎng)文檔是有點(diǎn)太少了……) 如果說這個(gè)工具有啥亮點(diǎn),想來想去,大概App跟Chrome的通信,火狐的rhino引擎更可以被稱之為亮點(diǎn)= .=|||3
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注