Stetho是Facebook開源的一個Android平臺調試工具。html
Stetho能實現在不root手機的狀況下,經過Chrome查看App的佈局,Sqlite,SharedPreference。Network等。此外它還支持建立Dump文件。
java
使用Stetho很是重要的一點是要明確Stetho是一個調試工具。理論上是僅僅能用於Debug包的,假設應用到Release包上,你的app的數據就全部暴露出來了。android
咱們的代碼就是以這個爲中心來實現的。
git
Gradle 文件裏直接加入Stetho的依賴。
github
compile 'com.facebook.stetho:stetho-okhttp:1.1.1' debugCompile 'com.facebook.stetho:stetho:1.1.1'
位置例如如下圖所看到的,在主projectsrc文件夾下,建立debug文件夾。假設不需要Dump功能的話僅僅需要新建 AndroidManifest 文件和Application 文件就能夠。
AndroidManifest中指明Debug從DebugApplication 啓動app。chrome
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.debug.xsldebug"> <application tools:replace="android:name" android:name=".activity.message.XSLDebugApplication" /> </manifest>網絡
DebugApplication繼承應用程序原先的的Application,並加入Stetho初始化相關代碼。
app
<pre name="code" class="java">public class XSLDebugApplication extends XSLApplication { @Override public void onCreate() { super.onCreate(); Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) .build()); } private static class XSLDumperPluginsProvider implements DumperPluginsProvider { private final Context mContext; public XSLDumperPluginsProvider(Context context) { mContext = context; } @Override public Iterable<DumperPlugin> get() { ArrayList<DumperPlugin> plugins = new ArrayList<DumperPlugin>(); for (DumperPlugin defaultPlugin : Stetho.defaultDumperPluginsProvider(mContext).get()) { plugins.add(defaultPlugin); } plugins.add(new XSLDumperPlugin()); return plugins; } } }
通過以上的設置,app已經支持Stetho的基礎功能。 可以經過Chrome的設備檢查或者 直接訪問 chrome://inspect/#devices 來查找當前鏈接的設備框架
假設要想支持查看Network信息,還需要進行下面的額外的配置ide
使用Okhttp網絡框架,可以很是方便的集成Stetho,假設使用的是HttpURLConnection,會麻煩很是多。咱們的網絡框架已是Okhttp2.2+。因此很是方便的就可以集成Stetho。
public String okHttpPost(String url, List<BasicNameValuePair> nameValuePairs) { String result = StringUtils.EMPTY_STRING; OkHttpClient client = OkHttpClientFactory.createDefault(); if (BuildConfig.DEBUG) { //debug 包裏面,加入Stetho-okhttp的支持 client.networkInterceptors().add(new com.facebook.stetho.okhttp.StethoInterceptor()); } Request request = new Request.Builder() .url(url) .post(getFormEncodingBuilder(nameValuePairs).build()) .build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (Exception e) { e.printStackTrace(); } return result; }僅僅有Debug包才需要支持Stetho。Release包不需要。
但是即便是Release包。這行代碼也會Build,因此最開始的依賴裏面。Stetho-Okhttp的依賴要是Compile的而不是debugCompile。
1. 查看佈局
2. 查看Sqlite,並支持運行Sql語句。注意:命令行不是打在 Console窗體的哦。
3. 查看Network請求。
4. 建立Dump. 事實上這個功能本人沒有去嘗試,因爲沒有dump的需求。
杏樹林研發 梁建彬