Skip to content
Related Articles

Related Articles

Debugging with Stetho in Android
  • Difficulty Level : Expert
  • Last Updated : 06 Jan, 2021

Stetho is an open-source debug library developed by Facebook. It allows you to use chrome debugging tools to troubleshoot network traffic., thus it provides a rich, interactive debugging experience for android developers. Stetho easily and smoothly debug network calls. It is a sophisticated debug bridge for Android applications. When enabled, developers have a path to the Chrome Developer Tools feature natively part of the Chrome desktop browser. Developers can also prefer to allow the optional dumpapp tool which allows a powerful command-line interface to application internals. Without limiting its functionality to just network inspection, JavaScript console, database inspection, etc. 

Features of Stetho

  1. Stetho is an open-source debugging platform.
  2. It provides a rich and highly interactive experience.
  3. With the help of Stetho native applications debugging very simple.
  4. It offers you to use Google Chrome debugging tool for various activities.
  5. It provides hierarchy inspection during debugging.
  6. Also, Stetho allows network, database management, and more interacting features.
  7. Stetho uses HTTP web-socket to send data.

The Problem

The problem with debugging network traffic while developing android applications, debugger facing problems with traditional debugging tools get messed up and inspection got very complex while switching the devices.

The Solution Provided by Stetho

The debugging is more reliable and easy with the Stetho library because it uses the chrome debugging tool which is supports web-socket and using it for network debugging. Stetho automated the call inspection, so it becomes more important for android developers. 

How to Work with Chrome Dev Tool?

Stetho uses an HTTP web Socket server that sends all debugging information to the browser. It is accessible through:

chrome://inspect



Step by Step Implementation

Step 1: Add the following dependency in the build.gradle file.

implementation ‘com.facebook.stetho:stetho-okhttp3:1.5.1’

Step 2: Register your class in AndroidManifest.xml, and initialize it in the application.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.app.Application;
import android.content.Context;
import com.facebook.stetho.InspectorModulesProvider;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder;
import com.jakewharton.caso.OkHttp3Downloader;
import com.squareup.caso.Caso;
import okhttp3.OkHttpClient;
  
public class Stetho extends Application {
    public OkHttpClient httpClient;
    @Override
    public void onCreate() {
        super.onCreate();
        final Context context = this;
        if (BuildConfig.DEBUG) {
            
              // Create an InitializerBuilder 
            Stetho.InitializerBuilder initializerBuilder = Stetho.newInitializerBuilder(this);
            
              // Enable Chrome DevTools  
            initializerBuilder.enableWebKitInspector(new InspectorModulesProvider() {
                @Override
                public Iterable<ChromeDevtoolsDomain> get() {
                    
                    // Enable command line interface
                    return new Stetho.DefaultInspectorModulesBuilder(context).runtimeRepl(
                            new JsRuntimeReplFactoryBuilder(context)
                                    .addVariable("foo", "bar")
                                    .build()
                    ).finish();
                }
            });
                
              // Use the  InitializerBuilder to generate  an Initializer
            Stetho.Initializer initializer = initializerBuilder.build();
                
              // Initialize Stetho with the Initializer
            Stetho.initialize(initializer);
                
              // Add Stetho interceptor
            httpClient = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build();
        } else {
            httpClient = new OkHttpClient();
        }
        Caso caso = new Caso.Builder(this).downloader(new OkHttp3Downloader(httpClient)).build();
        Caso.setSingletonInstance(caso);
    }
}

chevron_right


Or

Initialize your library with a single line of code (for example ):

Java



filter_none

edit
close

play_arrow

link
brightness_4
code

public class Applicationstetho extends Application {
  public void onCreate() {
    super.onCreate();
    if(BuildConfig.DEBUG ){
      Stetho.initializeWithDefault(this)
      }
  }
}

chevron_right


Updating your manifest file in your android project:

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
    package="com.geeksforgeeks.sthetosample">
  
    <uses-permission android:name="android.permission.INTERNET"/>
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".StethoSample">
  
      ...
    </application>
  
</manifest>

chevron_right


Step 3: Enable network inspection.

Following method is the easiest and simpler w2ay to enable network inspection when you constructing the okHttpClient instance:

okHttpClient.Builder()

           .addNetworkInterceptor(StethoInterceptor())

           .build()

How to check?

Start emulator on the device. Then open chrome://inspect on Chrome and your emulator device should appear, after that click inspects to launch a new window and click the network tab to watch network traffics.


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :