Stetho简介
stetho是Facebook开发的一框基于Chrome开发者工具的Debug库。近半年来,因为公司内网禁止了代理,Charles就没有办法使用了~~尝试了使用Stetho抓包,效果不错。当然,Stetho还有其他强调的功能。功能如下:
- Elements:查看View的层次结构
- Network:网络抓包
- Resources:查看本地SharePrefenrence和本地Sqlite DB
- Console:app执行js
- 其他:其他功能没怎么用过~~~
Stetho项目引入
网上主流的做法是官网描述的做法:
compile 'com.facebook.stetho:stetho:1.4.2'
compile 'com.facebook.stetho:stetho-okhttp3:1.4.2'
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build()
首先声明一下,这样的写法没有问题。在Release build的时候Stetho自己会disable所有的功能,所以release包的网络请求和数据都是安全的。
比较不完美的地方是"compile"依赖编译,gradle定义compile关键字会为所有build type都引入依赖。也就是说release的apk里面也会打进Stetho的依赖。从逻辑上说,apk里面不应该打入无用的依赖。所以,我决定在release版本下去掉stetho依赖。
需求分析:
1、只在debug引入Stetho依赖。
这个容易解决。gradle的“debugCompile”关键字可以解决这个问题。
2、引入“debugCompile”关键字之后,官网推荐的写法就会有点问题。release打包的时候会提示找不到Stetho的相关依赖包~~~
为了解决这个问题,我为release/debug 分别创建了两个逻辑分支,执行不同逻辑。
代码如下:
build.gradle:
//stetho
debugCompile 'com.facebook.stetho:stetho:1.3.1'
debugCompile 'com.facebook.stetho:stetho-okhttp3:1.4.1'
在src目录下,分别创建release/java,debug/java目录,保持与main目录下的包名一致,创建StethoUtils类


在Application中初始化Stetho:

在OKHttpClient实例化的注入StethoInterceptor:

代码如上,这样的写法可以在release包中去掉stetho的jar包依赖。
附录
stetho使用注意事项:
- 记得翻墙~~ 不翻墙的话,chrome开发者工具看到的是白屏
网友评论