android check internet connection, android internet, connectivity manager android kotlin,  check internet connection android studio

How to check internet connection in android using Kotlin

It is usually an important step to make sure that the user is notified whenever the application is not working due to a lack of internet connection. This ensures that the user finds an option and checks the internet connection before trying to access the features of the app

When the internet connection is not present or cannot connect to a user’s phone and tries to access an application and doesn’t get the notification or alert warning, the user experience with the app will automatically drop and will think the app is not working.

When the notification is displayed to the user that there is no internet connection and they will need to check on the internet connection, the user automatically knows that the error lies on his side

In this article, we shall focus on how to check the internet connection in android using kotlin language where we shall discuss what is needed and how to identify when there is no internet connection in the device that the user is using.

To begin checking whether the device has internet connection android using kotlin, in the project that you are working on

  • Open the manifest file and add the internet permission and check network state permission. This permission is required by the methods that are used in the main activity

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

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

For a new project with only one activity, the full android manifest file code will be as shown below

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.checkinternet">

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

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

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.CheckInternet">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

 

  • In the xml file, leave it as it is but for others they use a button to be clicked so that it can trigger the check connectivity status. For us we do prefer checking the connectivity as the first thing after opening or launching the app
  • In the main activity file, you will need to add the code that checks the internet connection status in android

Add the below code on the onCreate method

val ConnectionManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val networkInfo = ConnectionManager.activeNetworkInfo

        if (networkInfo != null && networkInfo.isConnected == true) {

            Toast.makeText(this@MainActivity, "Connection is available", Toast.LENGTH_LONG).show()

        } else {

            Toast.makeText(this@MainActivity, "Connection is not available", Toast.LENGTH_LONG).show()

        }

When the connection is available, a toast message is displayed with the message that connection is available and when the connection is not available or not established a toast message will notify the user of the app that the connection is not available

The toast message sometimes does not communicate the message well and most users may not pay attention to it.

Another alternative from using the toast is the alert dialog that will require an action from the user. The alert dialog ensures that it attracts the attention of the user and has to do something.

The alert dialog is only added when the connection is not established

Use the code below to alternate the toast with the alert dialog in the else section

val builder = AlertDialog.Builder(this)

            builder.setTitle("Connection status")

            builder.setMessage("Please check your connection before you continue")

            builder.setPositiveButton(android.R.string.yes) { dialog, which ->

                Toast.makeText(applicationContext,

                        android.R.string.yes, Toast.LENGTH_SHORT).show()

            }

            builder.setNegativeButton(android.R.string.no) { dialog, which ->

                Toast.makeText(applicationContext, android.R.string.no, Toast.LENGTH_SHORT).show()

            }

            builder.show()

The full code for main activity is as below

package com.example.checkinternet

import android.content.Context

import android.net.ConnectivityManager

import android.os.Bundle

import android.widget.Toast

import androidx.appcompat.app.AlertDialog

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    var builder: AlertDialog.Builder? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val ConnectionManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val networkInfo = ConnectionManager.activeNetworkInfo

        if (networkInfo != null && networkInfo.isConnected == true) {

            //continue with the other functions

        } else {

            val builder = AlertDialog.Builder(this)

            builder.setTitle("Connection status")

            builder.setMessage("Please check your connection before you continue")

            builder.setPositiveButton(android.R.string.yes) { dialog, which ->

                Toast.makeText(applicationContext,

                        android.R.string.yes, Toast.LENGTH_SHORT).show()

            }

 

            builder.setNegativeButton(android.R.string.no) { dialog, which ->

                Toast.makeText(applicationContext,

                        android.R.string.no, Toast.LENGTH_SHORT).show()

            }

 

            }

            builder.show()

        }

    }

}

 

That’s all for this article on how to check internet connection in android. Run your application and turn of internet or mobile data and observe the behavior