Skip to main content

How to handle network connectivity changes using Fast Networking Library in Kotlin Android

How to handle network connectivity changes using Fast Networking Library in Kotlin Android.

In this tutorial, we will learn how to handle network connectivity changes in an Android application using the Fast Networking Library in Kotlin. The Fast Networking Library is a powerful and easy-to-use networking library that simplifies the process of making network requests in Android.

Step 1: Setting Up the Project

Before we begin, make sure you have the Fast Networking Library added to your project. You can add the library by including the following line in your app-level build.gradle file:

implementation 'com.amitshekhar.android:android-networking:1.0.2'

Sync your project with Gradle after adding the library.

Step 2: Checking Network Connectivity

To handle network connectivity changes, we first need to check the network connectivity status. We can use the ConnectivityManager class to check the network connectivity status.

Add the following permission to your AndroidManifest.xml file to access network state:

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

Next, create a function to check the network connectivity status:

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo

fun isNetworkConnected(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true
}

Step 3: Handling Network Connectivity Changes

Now that we have a function to check the network connectivity status, let's implement a network connectivity change listener using the Fast Networking Library.

Create a new class called NetworkConnectivityInterceptor and implement the Interceptor interface:

import android.content.Context
import com.amitshekhar.NetworkUtils
import com.amitshekhar.utils.NetworkHelper
import okhttp3.Interceptor
import okhttp3.Response

class NetworkConnectivityInterceptor(private val context: Context) : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
if (!NetworkUtils.isNetworkConnected(context)) {
throw NoConnectivityException()
}

val requestBuilder = chain.request().newBuilder()
return chain.proceed(requestBuilder.build())
}
}

In the intercept method, we check if the network is connected using the isNetworkConnected function we created earlier. If the network is not connected, we throw a custom exception called NoConnectivityException. Otherwise, we proceed with the network request.

Next, we need to handle the NoConnectivityException in our network requests. We can do this by adding an onError callback to our network request using the Fast Networking Library.

Here's an example of how to handle network connectivity changes in a network request:

import com.amitshekhar.NetworkUtils
import com.amitshekhar.utils.NetworkHelper
import com.rx2androidnetworking.Rx2AndroidNetworking

Rx2AndroidNetworking.get("https://api.example.com/data")
.addHeaders("Authorization", "Bearer TOKEN")
.addInterceptor(NetworkConnectivityInterceptor(this))
.build()
.setOkHttpClient(NetworkHelper.getCacheEnabledHttpClient())
.getAsJSONObject(object : JSONObjectRequestListener {
override fun onResponse(response: JSONObject?) {
// Handle the response
}

override fun onError(anError: ANError?) {
if (anError?.cause is NoConnectivityException) {
// Handle network connectivity error
} else {
// Handle other errors
}
}
})

In this example, we add the NetworkConnectivityInterceptor to our network request using the addInterceptor method. If the network is not connected, the NoConnectivityException will be thrown, and we can handle it in the onError callback.

Step 4: Registering Network Connectivity Change Receiver

To listen for network connectivity changes, we can register a BroadcastReceiver in our activity or fragment.

Create a new class called NetworkConnectivityReceiver and extend it from BroadcastReceiver:

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.widget.Toast

class NetworkConnectivityReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
val isNetworkConnected = isNetworkConnected(context)
if (isNetworkConnected) {
Toast.makeText(context, "Network connected", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Network disconnected", Toast.LENGTH_SHORT).show()
}
}
}
}

In the onReceive method, we check if the connectivity action is triggered. If the network is connected, we display a toast message.

Next, register the NetworkConnectivityReceiver in your activity or fragment:

import android.content.IntentFilter
import android.net.ConnectivityManager
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val networkConnectivityReceiver = NetworkConnectivityReceiver()

override fun onResume() {
super.onResume()
val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(networkConnectivityReceiver, intentFilter)
}

override fun onPause() {
super.onPause()
unregisterReceiver(networkConnectivityReceiver)
}
}

In the onResume method, we register the NetworkConnectivityReceiver to listen for network connectivity changes using the CONNECTIVITY_ACTION intent filter. In the onPause method, we unregister the receiver to avoid memory leaks.

That's it! You have now learned how to handle network connectivity changes using the Fast Networking Library in Kotlin Android. You can now easily check network connectivity status, handle network connectivity errors in network requests, and listen for network connectivity changes in your application.