Check Internet Connection Status in Android

Check Internet Connection Status in Android

Android allows to check if device is connected to the internet, and also we can determine what type of network connection currently available (Wi-Fi, cellular).

To get the internet connection status, we need to request the ACCESS_NETWORK_STATE permission in the manifest file.

app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app">

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

    <application>
        ...
    </application>

</manifest>

We get an instance of ConnectivityManager which allows getting the NetworkCapabilities for active network. By using the hasTransport() method, we check internet connection status.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val connManager = getSystemService(Context.CONNECTIVITY_SERVICE)
                as ConnectivityManager

        val capabilities = connManager.getNetworkCapabilities(connManager.activeNetwork)

        if (capabilities != null) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    Log.d("MY_APP", "Connected to Wi-Fi network")
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    Log.d("MY_APP", "Connected to cellular network")
                }
                else -> {
                    Log.d("MY_APP", "No Internet access")
                }
            }
        } else {
            Log.d("MY_APP", "No Internet access")
        }
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.