Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaDebugging with Stetho in Android

Debugging with Stetho in Android

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. We are going to implement this project using both Java and Kotlin Programming Language for Android.

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 is 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 an 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 supports web-socket and uses 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: Adding Dependency to the build.gradle File

Go to Module build.gradle file and add this dependency and click on Sync Now button.

implementation 'com.facebook.stetho:stetho-okhttp3:1.5.1'

Step 2: Register the Class in AndroidManifest.xml, and Initialize it in the Application

Java




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);
    }
}


Kotlin




import android.app.Application
import android.content.Context
import com.facebook.stetho.InspectorModulesProvider
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
  
class Stetho : Application() {
      
    private lateinit var httpClient: OkHttpClient
      
    override fun onCreate() {
        super.onCreate()
        val context: Context = this
          
        if (BuildConfig.DEBUG) {
            // Create an InitializerBuilder
            val initializerBuilder: Stetho.InitializerBuilder = newInitializerBuilder(this)
            // Enable Chrome DevTools
            initializerBuilder.enableWebKitInspector(object : InspectorModulesProvider() {
                fun get(): Iterable<ChromeDevtoolsDomain> {
                    // Enable command line interface
                    return DefaultInspectorModulesBuilder(context).runtimeRepl(
                        JsRuntimeReplFactoryBuilder(context).addVariable("foo", "bar").build()
                    ).finish()
                }
            })
  
            // Use the  InitializerBuilder to generate  an Initializer
            val initializer: Stetho.Initializer = initializerBuilder.build()
  
            // Initialize Stetho with the Initializer
            initialize(initializer)
  
            // Add Stetho interceptor
            httpClient = Builder().addNetworkInterceptor(StethoInterceptor()).build()
        } else {
            httpClient = OkHttpClient()
        }
        val caso: Caso = Builder(this).downloader(OkHttp3Downloader(httpClient)).build()
        Caso.setSingletonInstance(caso)
    }
}


OR

Initialize your Library with a Single Line of Code:

Java




import android.app.Application;
  
public class ApplicationStetho extends Application {
    public void onCreate() {
        super.onCreate();
        
        if(BuildConfig.DEBUG ){
            Stetho.initializeWithDefault(this);
        }
    }
}


Kotlin




import android.app.Application
  
class ApplicationStetho : Application() {
    override fun onCreate() {
        super.onCreate()
          
        if (BuildConfig.DEBUG) {
            Stetho.initializeWithDefault(this)
        }
    }
}


Updating the Manifest File in the Android Project:

XML




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://neveropen.com/apk/res/android"
    package="com.neveropen.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">
          
        <!-- Remaining Nodes -->
    </application>
  
</manifest>


Step 3: Enable Network Inspection.

The following method is the easiest and simpler way to enable network inspection when you constructing the okHttpClient instance:

okHttpClient.Builder().addNetworkInterceptor(StethoInterceptor()).build()

How to Check?

Run the 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.

RELATED ARTICLES

Most Popular

Recent Comments