How to Check Internet Connection in Kotlin?
If the Android application is developing, which is internet-based, then there must be a feature that checks for internet connectivity and informs the user there is no internet available. So in this article, it’s been demonstrated step by step. On how to check the internet connectivity. Have a look at the following image which gives an overview of the discussion.
Step by Step Implementation
Step 1: Create an empty activity project
Create an empty activity android studio project. Refer to How to Create/Start a New Project in Android Studio, to know how to create an empty activity project. And select Kotlin as the programming language.
Step 2: Working with acitivity_main.xml file
- The main layout of the application contains only one button. Which upon clicking, a toast appears which contains the status of the connectivity.
- To implement the same UI invoke the following code inside the acitivity_main.xml file.
Step 3: Working with MainActivity.kt file
- The MainActivity.kt file contains some already built-in API which used to handle the network connectivity.
- First, we should register the activity with the ConnectivityManager service.
- Second, we need to check for the android version. if the version is below M uses activeNetworkInfo API, or if the version is equal to or above M use NetworkCapabilities API.
- To implement the same invoke the following code inside the MainActivity.kt file comments are added for better understanding.