Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Debugging with Stetho in Android
Next article icon

Debugging with Stetho in Android

Last Updated : 15 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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://geeksforgeeks.com/apk/res/android"     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">                  <!-- 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.


Next Article
Debugging with Stetho in Android

A

abhijat_sarari
Improve
Article Tags :
  • Java
  • Kotlin
  • Android
Practice Tags :
  • Java

Similar Reads

    Desugaring in Android
    Google has officially announced Kotlin as a recommended language for Android Development and that's why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of
    4 min read
    How to Access SQLite Database in Android For Debugging?
    A software library that provides a relational database management system is called SQLite. It allows the users to interact with RDBMS. The lite in SQLite denotes the lightweight when it comes to setup, database administration, and resources required. In SQLite, a database is stored in a single file
    10 min read
    How to Debug Database in Android?
    The Android Debug Database library is a useful tool for troubleshooting databases and shared preferences in Android apps. In this article we would be looking forward to using this library and get our hand on it, so continue reading, and indulge. First thing's first, What's Exactly an Android Debug D
    3 min read
    How to Measure Method Execution Time in Android Debug Build?
    We use a variety of approaches to apply certain features to our Android applications whenever we create them. We create one method and apply it to all of our projects. These strategies are responsible for growing the number of people who use our software by delivering a variety of unique features. H
    3 min read
    What is Android Studio?
    Android Studio is the official Integrated Development Environment (IDE) for Android App development. It is a powerful tool that allows developers to build high-quality applications for the Android platform. It has complete tools for the process of Android App development. From writing code to testin
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences