Android Development

Issue Tracker Android Updates Android Home Home Contact

Internet-based Networking in Android

Internet-based networking in Android refers to the process of enabling communication between an Android device and remote servers or web services over the internet using standard protocols. These services typically reside on cloud infrastructure or external systems and provide functionality such as data retrieval, authentication, or file uploads.

While not every app requires internet connectivity, most modern applications, especially in corporate or enterprise settings depend heavily on such communication for real-time data access, cloud synchronization, or remote updates.

JSON (JavaScript Object Notation) is the most common format for exchanging data in these interactions. Android apps often use APIs based on REST or GraphQL standards to send and receive structured data from remote back-end services.

Outgoing: Java/Kotlin object(s) → JSON → Server

Incoming: Server → JSON → Java/Kotlin object(s)

These Java/Kotlin objects are typically defined as data classes in Kotlin or POJOs (Plain Old Java Objects) in Java. They serve as structured representations of the data and are serialized to JSON when sending data, and deserialized from JSON when receiving data.

Declaring Internet Permissions

To perform network communication in Android, declare the INTERNET permission in your app’s AndroidManifest.xml file. Without this permission, app will not be allowed to access the internet.


<uses-permission android:name="android.permission.INTERNET" />

Additionally, for Android 9 (API level 28) or higher, handle cleartext (HTTP) traffic explicitly, since it's blocked by default. To allow it, modify networkSecurityConfig or use HTTPS.


<application
    android:networkSecurityConfig="@xml/network_security_config"
    ... >
</application>

And your res/xml/network_security_config.xml file might look like:


<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">yourdomain.com</domain>
    </domain-config>
</network-security-config>

Protocols Used in Networking

Networking in Android (as well as in other platforms) is built upon a few standard and widely used protocols:

  • HTTP/HTTPS: Hypertext Transfer Protocol (Secure); used for most REST APIs and general web communication.
  • TCP/IP: Transmission Control Protocol over Internet Protocol, ensures reliable transmission.
  • UDP: User Datagram Protocol; used where speed is more critical than reliability (e.g., video streaming).
  • WebSockets: Full-duplex communication used for real-time data like chat apps.
  • FTP: File Transfer Protocol, less common in mobile apps today.

Note: These protocols are platform-independent and are the core of nearly all network communication regardless of device or OS.

How Android Implements Networking

Android supports networking primarily by using the standard Java networking APIs, such as HttpURLConnection, which provide the basic mechanisms to send and receive data over the network using protocols like HTTP and HTTPS.

However, to improve performance, security, and convenience, Android and the wider ecosystem have developed optimized libraries and wrappers around these core APIs. For example, OkHttp is a popular HTTP client library that efficiently handles connection pooling, transparent GZIP compression, caching, and robust error handling. It is now integrated closely into Android and often in past had replaced direct use of HttpURLConnection.

Starting with Android 9 (API level 28), the platform’s implementation of HttpURLConnection is backed internally by OkHttp. This means that apps using the familiar HttpURLConnection API automatically benefit from OkHttp’s advantages such as connection pooling, transparent response caching, and improved security, without any code changes.

Embedding OkHttp as the internal implementation of HttpURLConnection offers significant advantages by improving performance, efficiency, and security without requiring modification of existing networking code. Features like connection pooling, transparent caching, and HTTP/2 support are automatically utilized under the hood. This integration allows Android apps to benefit from OkHttp’s modern HTTP capabilities while maintaining full backward compatibility with the standard HttpURLConnection API.

However, to use OkHttp’s advanced features—such as interceptors, detailed logging, or WebSocket support—explicit use of the OkHttp library directly is required.

Together, HttpURLConnection and OkHttp enable Android apps to perform network operations securely and efficiently, minimizing boilerplate code while making full use of the underlying Java networking stack. Main features of both libraries are summarized below:

HttpURLConnection

HttpURLConnection is the basic class provided by Java (and supported on Android) to send and receive HTTP requests and responses. It supports:

  • GET, POST, PUT, DELETE methods
  • Input and output streams for reading/writing data
  • Automatic redirect handling
  • GZIP compression
  • HTTPS connections using SSL/TLS

How to Use HttpURLConnection:


val url = URL("https://api.example.com/data")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()

val inputStream = connection.inputStream
val response = inputStream.bufferedReader().use { it.readText() }
connection.disconnect()

Advantages:

  • Native to Java; no additional libraries required
  • Efficient for simple and direct HTTP communication
  • Fully supported across all Android versions

Limitations:

  • Verbose and low-level API, requiring more boilerplate code
  • No built-in support for features like retries, caching, logging, or connection reuse
  • Not ideal for handling modern REST APIs
  • Harder to maintain and extend for complex networking tasks

OkHttp

OkHttp is a modern and feature-rich third-party HTTP client developed by Square. As of Android 4.4 (API level 19), HttpURLConnection internally uses OkHttp as its backend implementation, bringing many of OkHttp’s improvements automatically.

Why Use OkHttp?

  • Built-in connection pooling, transparent GZIP compression, and disk-based response caching
  • Supports both synchronous and asynchronous network calls
  • Extensible with interceptors for logging, authentication, retries, custom headers, etc.
  • Handles advanced features like redirects, timeouts, and SSL pinning

val client = OkHttpClient()
val request = Request.Builder()
    .url("https://www.zyasin.com/data")
    .build()

client.newCall(request).enqueue(object : Callback {
    override fun onResponse(call: Call, response: Response) {
        val body = response.body?.string()
    }

    override fun onFailure(call: Call, e: IOException) {
        // Handle failure
    }
})

Threads and Handlers in Networking

What is a Thread?

A Thread is a unit of execution. In Android, network calls must not be made on the main thread, or else a NetworkOnMainThreadException is thrown. Calls must offload to a background thread.

What is a Handler?

A Handler is associated with a Looper (usually the main thread) and allows background threads to communicate or post updates back to the UI thread.


val handler = Handler(Looper.getMainLooper())
Thread {
    val result = fetchDataFromNetwork()
    handler.post {
        textView.text = result
    }
}.start()
  

Thread Pools

A ThreadPoolExecutor allows to manage multiple concurrent threads. It reuses threads and limits the number of active threads.


val executor = Executors.newFixedThreadPool(4)
executor.execute {
    val result = fetchDataFromNetwork()
    runOnUiThread {
        textView.text = result
    }
}
  
  • Better resource management
  • Ideal for multiple background tasks
  • Reduces thread creation overhead

Note: HttpURLConnection or OkHttp doesn’t manage threading. Threads need explicit management using a thread pool or Kotlin coroutines when performing network operations to avoid blocking the main thread.

Why We Rarely Use HttpURLConnection or OkHttp Directly?

While educational, HttpURLConnection and even OkHttp are considered low-level networking APIs. They lack built-in support for features such as request queuing, lifecycle awareness, JSON parsing, or coroutine integration.

In real-world Android development, higher-level libraries and frameworks, such as Retrofit, Volley, or those based on Kotlin Coroutines and WorkManager, are typically preferred to simplify code, improve readability, and integrate more effectively with modern Android app architecture.

Networking Libraries

Tool Description
Retrofit Type-safe REST client by Square. Uses OkHttp internally. Supports converters (e.g., Gson, Moshi), interface-based APIs, coroutine and RxJava support.
Volley Network library from Google. Good for smaller apps or frequent image loading and caching.
Coroutines + OkHttp Asynchronous programming with Kotlin Coroutines and OkHttp, reducing boilerplate and improving readability.
RxJava / RxAndroid Reactive programming libraries for managing asynchronous streams. Commonly used with Retrofit or OkHttp for complex event chains or threading.
WorkManager Background task scheduler with guaranteed execution for deferrable, persistent tasks (e.g., sync with server).