Check Internet Connection Continuously in Android Studio

Hey Developer, If you want to Check Internet Connection Continuously in Android Studio, while the application running in the background.

I will share the way to monitor the Network Connection Continuously in an Activity or Fragment and we will use Network Callback with a live data observer. So, without further delay, let’s see: Step-By-Step.

Check Internet Connection Continuously in Android Studio

Step 1: First, create a new project

  • Open Android Studio.
  • Create a new project.
  • Filling in the project details.
  • Click on finish, now your project is successfully created.

Step 2: add important permission

Now open Android Manifest, and add the most 2 important permission.

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

Step 3: Create a new XML layout

Create a new XML layout for showing network errors, when you go offline.

  • Go to res
  • layout
  • Right click on layout and select new then select Layout Resource File
  • Give name as network_error.xml and click ok.

Now open the network_error.xml file and write the below code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/light_purple"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/errorImageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_network_error"
        tools:ignore="ContentDescription" />

    <TextView
        android:id="@+id/errorTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/network_error"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorImageView" />

    <TextView
        android:id="@+id/errormsgTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/internet_check"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: include network error layout

After creating the network error layout and include the network error layout to activity_main.

Open activitiy_main.xml and write the following code in the activity_main.xml

<include
    android:id="@+id/networkError"
    android:visibility="gone"
    layout="@layout/network_error"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Now design part is completed, let’s move to check the internet connection continuously

Step 5: Create a new Kotlin Class

Create a new Kotlin Class name as NetworkConnection.

package com.techpassmaster.androidcheckinternetconnection

class NetworkConnection(){
}

Step 6: Pass a context as a parameter

Now pass a context as a parameter and extend the class with LiveData()

class NetworkConnection(private val context: Context) : LiveData() {

}

Step 7: Create connectivityManager

Create connectivityManager which will be extending ConnectivityManager and it is responsible for Monitor network connection, Attempt to fail network when connectivity to a network is lost and etc and also you have to create a networkConnectionCallback variable for NetworkCallback in which you have to get two callbacks:

  • onLost
  • onAvailable
class NetworkConnection(private val context: Context) : LiveData() {

private val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private lateinit var networkConnectionCallback: ConnectivityManager.NetworkCallback

}

Step 8: Create connectivityManagerCallback

Create connectivityManagerCallback function for post the false value, when the connection is lost, and post true value when the internet is available. write the below code.

private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {    
networkConnectionCallback = object : ConnectivityManager.NetworkCallback() {

        override fun onLost(network: Network) {
            super.onLost(network)
            postValue(false)
        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            postValue(true)
        }
    }
    return networkConnectionCallback
}
}

Step 9: Create updateNetworkConnection

Now create the updateNetworkConnection function which is used to post the true value and the internet is connected and also creates a variable that overrides the OnRecive function and it is responsible to update Network Connection.

private fun updateNetworkConnection() {
        val activeNetworkConnection: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetworkConnection?.isConnected == true)
}

private val networkReceiver= object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            updateNetworkConnection()
        }
}

Step 10: Override two fucntion

So this is the last step, just you have to override two functions.

  • onActive
  • onInactive

Write the below code.

override fun onActive() {
super.onActive()    
updateNetworkConnection()
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
            connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
        }
        else -> {
            context.registerReceiver(
                networkReceiver,
                IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            )
        }
    }
}

override fun onInactive() {
    super.onInactive()
    connectivityManager.unregisterNetworkCallback(connectivityManagerCallback())
}

Final NetworkConnection code for Check Internet Connection Continuously

So the final code for continuously checking network connection would be.

  • network_error.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/light_purple"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/errorImageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_network_error"
        tools:ignore="ContentDescription" />

    <TextView
        android:id="@+id/errorTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/network_error"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorImageView" />

    <TextView
        android:id="@+id/errormsgTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/internet_check"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical">

    <include
        android:id="@+id/networkError"
        android:visibility="gone"
        layout="@layout/network_error"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
  • NetworkConnection.kt
@file:Suppress("DEPRECATION")

package com.techpassmaster.androidcheckinternetconnection

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkInfo
import android.os.Build
import androidx.lifecycle.LiveData

@Suppress("DEPRECATION")
class NetworkConnection(private val context: Context) : LiveData<Boolean>() {

    private val connectivityManager: ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    private lateinit var networkConnectionCallback: ConnectivityManager.NetworkCallback

    override fun onActive() {
        super.onActive()

        updateNetworkConnection()
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
                connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
            }
            else -> {
                context.registerReceiver(
                    networkReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
                )
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        connectivityManager.unregisterNetworkCallback(connectivityManagerCallback())
    }

    private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {

        networkConnectionCallback = object : ConnectivityManager.NetworkCallback() {

            override fun onLost(network: Network) {
                super.onLost(network)
                postValue(false)
            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                postValue(true)
            }
        }
        return networkConnectionCallback
    }

    private fun updateNetworkConnection() {
        val activeNetworkConnection: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetworkConnection?.isConnected == true)
    }

    private val networkReceiver= object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            updateNetworkConnection()
        }
    }
}

Now call the Network connection observer in the Activity or Fragment for checking internet is connected or not.

  • Open Main Activity and write the below code.
@file:Suppress("DEPRECATION")

package com.techpassmaster.androidcheckinternetconnection

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkInfo
import android.os.Build
import androidx.lifecycle.LiveData

@Suppress("DEPRECATION")
class NetworkConnection(private val context: Context) : LiveData<Boolean>() {

    private val connectivityManager: ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    private lateinit var networkConnectionCallback: ConnectivityManager.NetworkCallback

    override fun onActive() {
        super.onActive()

        updateNetworkConnection()
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
                connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
            }
            else -> {
                context.registerReceiver(
                    networkReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
                )
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        connectivityManager.unregisterNetworkCallback(connectivityManagerCallback())
    }

    private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {

        networkConnectionCallback = object : ConnectivityManager.NetworkCallback() {

            override fun onLost(network: Network) {
                super.onLost(network)
                postValue(false)
            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                postValue(true)
            }
        }
        return networkConnectionCallback
    }

    private fun updateNetworkConnection() {
        val activeNetworkConnection: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetworkConnection?.isConnected == true)
    }

    private val networkReceiver= object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            updateNetworkConnection()
        }
    }
}
Recommended Reading:

I hope you liked the post. If you have any questions regarding this post. Feel free to comment and share the post with other developers.

Happy Learning!!!  🙂

Leave a Reply