Android调试工具 stetho

项目地址:https://github.com/facebook/stetho

在android studio中使用:



1. 添加jar  (下载地址:https://github.com/facebook/stetho/releases/tag/v1.1.0  )

(需要 stetho-1.1.0.jar    ?和  stetho-urlconnection-1.1.0.jar

添加完成后在bulid.gradle中显示:



2 在你的application类中添加:Stetho.initialize(Stetho..... 初始化Stetho工具


public class myApplication extends Application {

    @Override

    public void onCreate() {

        super.onCreate();

        Stetho.initialize(Stetho

                .newInitializerBuilder(this)

                .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))

                .enableWebKitInspector(

                        Stetho.defaultInspectorModulesProvider(this)).build());

    }



}


3 开启网络调试:

a.假如使用 HttpURLConnection 需要使用StethoURLConnectionManager类(在stetho-urlconnection JAR中) 并且注意在请求头中添加Accept-Encoding: gzip

以下是官方封装的一个Networker请求类:


public class Networker {

  private static Networker sInstance;



  private final Executor sExecutor = Executors.newFixedThreadPool(4);



  private static final int READ_TIMEOUT_MS = 10000;

  private static final int CONNECT_TIMEOUT_MS = 15000;



  private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";

  private static final String GZIP_ENCODING = "gzip";



  public static synchronized Networker get() {

    if (sInstance == null) {

      sInstance = new Networker();

    }

    return sInstance;

  }



  private Networker() {

  }



  public void submit(HttpRequest request, Callback callback) {

    sExecutor.execute(new HttpRequestTask(request, callback));

  }



  private class HttpRequestTask implements Runnable {

    private final HttpRequest request;

    private final Callback callback;

    private final StethoURLConnectionManager stethoManager;



    public HttpRequestTask(HttpRequest request, Callback callback) {

      this.request = request;

      this.callback = callback;

      stethoManager = new StethoURLConnectionManager(request.friendlyName);

    }



    @Override

    public void run() {

      try {

        HttpResponse response = doFetch();

        callback.onResponse(response);

      } catch (IOException e) {

        callback.onFailure(e);

      }

    }



    private HttpResponse doFetch() throws IOException {

      HttpURLConnection conn = configureAndConnectRequest();

      try {

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        InputStream rawStream = conn.getInputStream();

        try {

          // Let Stetho see the raw, possibly compressed stream.

          rawStream = stethoManager.interpretResponseStream(rawStream);

          InputStream decompressedStream = applyDecompressionIfApplicable(conn, rawStream);

          if (decompressedStream != null) {

            copy(decompressedStream, out, new byte[1024]);

          }

        } finally {

          if (rawStream != null) {

            rawStream.close();

          }

        }

        return new HttpResponse(conn.getResponseCode(), out.toByteArray());

      } finally {

        conn.disconnect();

      }

    }



    private HttpURLConnection configureAndConnectRequest() throws IOException {

      URL url = new URL(request.url);



      // Note that this does not actually create a new connection so it is appropriate to

      // defer preConnect until after the HttpURLConnection instance is configured.  Do not

      // invoke connect, conn.getInputStream, conn.getOutputStream, etc before calling

      // preConnect!

      HttpURLConnection conn = (HttpURLConnection)url.openConnection();

      try {

        conn.setReadTimeout(READ_TIMEOUT_MS);

        conn.setConnectTimeout(CONNECT_TIMEOUT_MS);

        conn.setRequestMethod(request.method.toString());



        // Adding this disables transparent gzip compression so that we can intercept

        // the raw stream and display the correct response body size.

        requestDecompression(conn);



        SimpleRequestEntity requestEntity = null;

        if (request.body != null) {

          requestEntity = new ByteArrayRequestEntity(request.body);

        }



        stethoManager.preConnect(conn, requestEntity);

        try {

          if (request.method == HttpMethod.POST) {

            if (requestEntity == null) {

              throw new IllegalStateException("POST requires an entity");

            }

            conn.setDoOutput(true);



            requestEntity.writeTo(conn.getOutputStream());

          }



          // Ensure that we are connected after this point.  Note that getOutputStream above will

          // also connect and exchange HTTP messages.

          conn.connect();



          stethoManager.postConnect();



          return conn;

        } catch (IOException inner) {

          // This must only be called after preConnect.  Failures before that cannot be

          // represented since the request has not yet begun according to Stetho.

          stethoManager.httpExchangeFailed(inner);

          throw inner;

        }

      } catch (IOException outer) {

        conn.disconnect();

        throw outer;

      }

    }

  }



  private static void requestDecompression(HttpURLConnection conn) {

    conn.setRequestProperty(HEADER_ACCEPT_ENCODING, GZIP_ENCODING);

  }



  @Nullable

  private static InputStream applyDecompressionIfApplicable(

      HttpURLConnection conn, @Nullable InputStream in) throws IOException {

    if (in != null && GZIP_ENCODING.equals(conn.getContentEncoding())) {

      return new GZIPInputStream(in);

    }

    return in;

  }



  private static void copy(InputStream in, OutputStream out, byte[] buf) throws IOException {

    if (in == null) {

      return;

    }

    int n;

    while ((n = in.read(buf)) != -1) {

      out.write(buf, 0, n);

    }

  }



  public static class HttpRequest {

    public final String friendlyName;

    public final HttpMethod method;

    public final String url;

    public final byte[] body;



    public static Builder newBuilder() {

      return new Builder();

    }



    HttpRequest(Builder b) {

      if (b.method == HttpMethod.POST) {

        if (b.body == null) {

          throw new IllegalArgumentException("POST must have a body");

        }

      } else if (b.method == HttpMethod.GET) {

        if (b.body != null) {

          throw new IllegalArgumentException("GET cannot have a body");

        }

      }

      this.friendlyName = b.friendlyName;

      this.method = b.method;

      this.url = b.url;

      this.body = b.body;

    }



    public static class Builder {

      private String friendlyName;

      private HttpMethod method;

      private String url;

      private byte[] body = null;



      Builder() {

      }



      public Builder friendlyName(String friendlyName) {

        this.friendlyName = friendlyName;

        return this;

      }



      public Builder method(HttpMethod method) {

        this.method = method;

        return this;

      }



      public Builder url(String url) {

        this.url = url;

        return this;

      }



      public Builder body(byte[] body) {

        this.body = body;

        return this;

      }



      public HttpRequest build() {

        return new HttpRequest(this);

      }

    }

  }



  public static enum HttpMethod {

    GET, POST

  }



  public static class HttpResponse {

    public final int statusCode;

    public final byte[] body;



    HttpResponse(int statusCode, byte[] body) {

      this.statusCode = statusCode;

      this.body = body;

    }

  }



  public interface Callback {

    public void onResponse(HttpResponse result);

    public void onFailure(IOException e);

  }

}

我自己试着调用network类:


public void sendOneReq() {

        Networker.HttpRequest request = Networker.HttpRequest.newBuilder()

                .friendlyName("Bai Du")

                .method(Networker.HttpMethod.GET)

                .url("http://www.baidu.com")

                .build();

        Networker.get().submit(request, mStoreRssResponse);

    }

    private final Networker.Callback mStoreRssResponse = new Networker.Callback() {



        @Override

        public void onResponse(Networker.HttpResponse result) {

            if (result.statusCode == 200) {

                String page22222=new String(result.body);

                System.out.println("page22222 : "+page22222);

            }else{

                System.out.println("result.statusCode is not 200");

            }



        }



        @Override

        public void onFailure(IOException e) {

            System.out.println("onFailure");

        }

    };

b.使用okhttp

工程依赖包如下:

commons-cli-1.2.jar

okhttp-2.3.0.jar

okio-1.3.0.jar

stetho-1.0.1.jar

stetho-okhttp-1.0.1.jar

一个简单使用:

  1. public class Net {
  2.    private static final boolean debug = true;
  3.    private static OkHttpClient okHttpClient = new OkHttpClient();
  4.    static {
  5.        if (debug) {
  6.            okHttpClient.networkInterceptors().add(new StethoInterceptor());
  7.        }
  8.    }
  9.    public static final void askBaidu() {
  10.        Request request = new Request.Builder().url("http://www.baidu.com")
  11.                .build();
  12.        try {
  13.            Response response = okHttpClient.newCall(request).execute();
  14.            String reslut = response.body().string();
  15.        } catch (IOException e) {
  16.            e.printStackTrace();
  17.        }
  18.    }
  19. }


4 查看结果:

在Chrome浏览器中输入  chrome://inspect/#devices

显示:

(注: 真机中是不会显示webView的。。)

点击 inspect 显示:



补充:

好像这个东西在某些机子上会崩溃。。

来自为知笔记(Wiz)

时间: 2024-10-25 08:47:38

Android调试工具 stetho的相关文章

Android调试工具及方法

转自:http://www.cnblogs.com/feisky/archive/2010/01/01/1637566.html Logcat Dump一份系统消息的日志.这些消息包括模拟器抛出错误时的堆栈跟踪. Android Log 一个记录日志的类,用来将消息写入模拟器上的日志文件中.如果你在DDMS上运行logcat的话你可以就实时查看消息.在你的代码中加入几个写日志方法的调用.为了使用Log类,你只需要调用Log.v()(详细),Log.d()(debug),Log.i()(infor

Android调试工具 adb

Android调试工具 ADB ADB Android Debug Bridge. ADB工具位于Android SDK安装目录的platform-tools子目录. 主要功能: 运行设备的shell(命令行) 管理模拟器或设备的端口映射 计算机和设备之间上传/下载文件 将本地apk软件安装至模拟器或android设备 常用命令: adb connect 192.168.1.103 adb devices adb remount adb install [-r] *.apk adb shell

Android调试工具_ Stetho

Stetho是Facebook开源的一个Android平台调试工具. Stetho能实如今不root手机的情况下,通过Chrome查看App的布局,Sqlite,SharedPreference.Network等.此外它还支持创建Dump文件. 使用Stetho非常重要的一点是要明确Stetho是一个调试工具.理论上是仅仅能用于Debug包的,假设应用到Release包上,你的app的数据就所有暴露出来了. 我们的代码就是以这个为中心来实现的. 核心代码实现: 首先要加入Stetho的引用 Gr

Android 调试工具集【转】

1.TraceView1)功能:用于热点分析和性能优化,分析每个函数占用的CPU时间,调用次数,函数调用关系等 2)方法: a)在程序代码中加入追踪开关 import android.os.Debug; …… android.os.Debug.startMethodTracing(“/data/tmp/test”);// 先建/data/tmp目录 ……// 被追踪的程序段 android.os.Debug.stopMethodTracing(); b)编译,运行后,设备端生成/data/tmp

Android开发——android调试工具集【转】

转:http://www.cnblogs.com/halzhang/archive/2010/08/11/1797097.html 1. 查看当前堆栈 1) 功能:在程序中加入代码,使可以在logcat中看到打印出的当前函数调用关系 2) 方法: new Exception(“print trace”).printStackTrace(); 2. MethodTracing 1) 功能:用于热点分析和性能优化,分析每个函数占用的CPU时间,调用次数,函数调用关系等 2) 方法: a) 在程序代码

Facebook 调试工具Stetho配置入门

I decided to spend a few hours on Stetho.Stetho is a sophisticated debug bridge for Android applications. How to enable itIt is very simple to enable Stetho.Just add these lines to your build.gradle: dependencies { // Stetho core compile 'com.faceboo

android调试工具adb命令大全

转载: 一.adb介绍SDK的Tools文件夹下包含着Android模拟器操作的重要命令adb,adb的全称为(Android Debug Bridge就是调试桥的作用.通过adb我们可以在Eclipse中方面通过DDMS来调试Android程序.借助这个工具,我们可以管理设备或手机模拟器的状态.还可以进行以下的操作: 1.快速更新设备或手机模拟器中的代码,如应用或Android 系统升级: 2.在设备上运行shell命令: 3.管理设备或手机模拟器上的预定端口: 4.在设备或手机模拟器上复制或

使用Android调试工具ddms测试app性能

1. 本来装的是最新的jdk-6u21-windows-x64.exe,然后下载了最新的eclipse-jee-luna-SR2-win32-x86_64.zip,没想到竟然报错,一查竟然还不兼容,不是都X64么....无语 然后又卸载了JDK,  换了个X32的jdk-6u45-windows-i586.exe  打开竟然又报错了 一查报错信息,知道一个是X32一个是X64的.......... 于是又去下载eclipse442win32.zip和jdk-8u45-windows-i586.e

android调试工具DDMS的使用详解

具体可见http://developer.android.com/tools/debugging/ddms.html. DDMS为IDE和emultor.真正的android设备架起来了一座桥梁.开发人员可以通过DDMS看到目标机器上运行的进程/现成状态,可以 android的屏幕到开发机上,可以看进程的heap信息,可以查看logcat信息,可以查看进程分配内存情况,可以像目标机发送短信以及打电话,可 以像android开发发送地理位置信息.可以像gdb一样attach某一个进程调试. SDK