Stetho是Facebook開(kāi)源的一個(gè)Android應(yīng)用的調(diào)試工具
使用很簡(jiǎn)單而且也有很多資源介紹
參考資源
Android開(kāi)發(fā)調(diào)試神器Stetho介紹-只有你想不到?jīng)]有你看不到
使用步驟
1. 項(xiàng)目添加依賴。
compile "com.facebook.stetho:stetho:1.3.1"
compile "com.facebook.stetho:stetho-okhttp3:1.3.1"
如果使用了okhttp,則需要添加第二個(gè)依賴
2. 初始化 Stetho
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
3. 修改網(wǎng)絡(luò)請(qǐng)求(可選)
new OkHttpClient.Builder() .
addNetworkInterceptor(new StethoInterceptor()) .build()
4. 運(yùn)行你的項(xiàng)目
在chrome中訪問(wèn) chrome://inspect
找到你的項(xiàng)目 點(diǎn)擊 inspect
如果發(fā)現(xiàn)一直在轉(zhuǎn)圈,需要先翻墻
使用技巧
1. 動(dòng)態(tài)加載開(kāi)啟Stetho
在一般開(kāi)發(fā)中我們通常是在debug版本下想入Stetho,而在release版本上去除,網(wǎng)資料大都是使用debugCompile的方式
debugCompile 'com.facebook.stetho:stetho:1.3.1'
這樣存在一個(gè)弊端是需要再在debug目錄再添加一個(gè)Application
受同事啟發(fā),使用DexClassLoader動(dòng)態(tài)加載的方式可以再方便的引入Stetho,并且不會(huì)影響apk的大小
- 首先新建一個(gè)app工程,引入Stetho依賴后,里面只需要添加一個(gè)類
package com.aleaf.debug;
import android.content.Context;
import android.util.Log;
import com.facebook.stetho.Stetho;
public class StethoReflection {
private static final String TAG = "StethoReflection";
public void initStetho(Context context){
Log.d(TAG,"initStetho context="+context);
//chrome://inspect
Stetho.initializeWithDefaults(context);
}
}
編譯一個(gè)debug版的apk出來(lái),并安裝到手機(jī)上
- 在需要使用Stetho的app的Application里面使用
DexClassLoader引入
public class MApplication extends Application {
public void onCreate() {
//chrome://inspect
if(BuildConfig.DEBUG){//debug版才開(kāi)啟
ReflectDebugUtil.reflectInitStetho(this);
}
}
}
ReflectDebugUtil.java
public class ReflectDebugUtil {
public static final String DEBUG_PACKGE = "com.aleaf.debug";
public static final String DEBUG_STETHO_CLASS_NAME = "com.aleaf.debug.StethoReflection";
private void reflectInitStetho(Context context){
try {
Context stethoContext = context.createPackageContext(
DEBUG_PACKGE, Context.CONTEXT_INCLUDE_CODE
| Context.CONTEXT_IGNORE_SECURITY);
String outDir = context.getFilesDir() + File.separator + "debug";
if(!new File(outDir).exists()){
new File(outDir).mkdirs();
}
DexClassLoader dexLoader = new DexClassLoader(
stethoContext.getApplicationInfo().sourceDir,//dst apk surce path
outDir,//
context.getApplicationInfo().nativeLibraryDir,//.so
context.getClassLoader());
Class<?> clazz = dexLoader.loadClass(DEBUG_STETHO_CLASS_NAME);
Object ste = clazz.newInstance();
Method m = clazz.getMethod("initStetho",Context.class);
m.invoke(ste,context);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這樣做的好處時(shí)應(yīng)用apk完全不需要引入Stetho的sdk,打開(kāi)關(guān)閉調(diào)試也很方便,只需要安裝卸載debug的apk即可