Monitor Internet Connection Changes in Android

Monitor Internet Connection Changes in Android

Android allows to monitor network connectivity changes, and we can determine when the device connects to the internet or disconnects.

To monitor internet connection changes, 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 registering the NetworkCallback. It used to notify about internet connection changes.

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

package com.example.app

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
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 networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                Log.d("MY_APP", "Internet connection available")
            }

            override fun onLost(network: Network?) {
                Log.d("MY_APP", "Internet connection lost")
            }
        }

        connManager.registerDefaultNetworkCallback(networkCallback)
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.