Android Networking With Kotlin

Shayaan Siddiqui
2 min readNov 23, 2020

In today’s modern landscape of apps, Networking is more than a concept; it’s a requirement. The most popular apps, use the Internet to help players keep on top on their leaderboards, connect friends together for coffee, make a purchase at a local coffee shop or even find a parking spot. Since it’s so widely used over a broad range of categories, it’s essential and in this article we will dive deep into how to use it.

Getting Started

Please verify that you have Android Studio 3.1 or higher.

In your project, please launch the “AndroidManifest.xml” file and add the following permissions above the application tag

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

Making a Network Request

In your MainActivity.kt file, we will define a value for the url. It is important to note that Network requests are not allowed to be run on the app’s main thread, also referred to as the UI Thread.

doAsync {
Request(url).run()
uiThread { longToast("Request performed") }
}

Reading the URL Content

readText() makes the network request by opening an InputStream from the url and returns a String. Log.d() writes the network response to Logcat.

val repoListJsonStr = URL(url).readText()
Log.d(javaClass.simpleName, repoListJsonStr)

readText() is adequate for most app developers, but it should be noted that there is an internal limit of 2GB. However if you anticipate exceeding that amount, it does not imply that you are unable to develop your app because there are other options. For example, BufferedReader.forEachLine() or a thrid party networking library may work.

Checking the Network Availability

Before making a network request, you should always check to see if the user has access to the network. This additional step will help ensure that the user will have a pleasant experience. For example, you maybe able to inform the user that the WiFi Radio is turned off or provide instructions on how to enable mobile data.

private fun isNetworkConnected(): Boolean {
//1
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//2
val activeNetwork = connectivityManager.activeNetwork
//3
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork)
//4
return networkCapabilities != null &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}

This function will check that the device has an active Internet connection by

  1. Retrieving an instance of ConnectivityManager from the current application context. ConnectivityManager is used to query the state of network.
  2. Getting a reference to the active network the device is using.
  3. Getting the capabilities of the active network.
  4. Checking if the active network can reach the Internet
if (isNetworkConnected()) {
doAsync {
Request(url).run()
uiThread { longToast("Request performed") }
}
} else {
AlertDialog.Builder(this).setTitle("No Internet Connection")
.setMessage("Please check your internet connection and try again")
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setIcon(android.R.drawable.ic_dialog_alert).show()
}

To test our app, we can add a debug point at the if statement; when the debugger hits the break point, you can quickly put the device/emulator into Airplane Mode and see what happens! Feel free to experiment and see what happens.

It’s all about the UI

--

--

Shayaan Siddiqui
0 Followers

Tech Enthusiast and Software Engineer