Monitoring internet connection on Android — Jetpack Writing
Here I will share how to observe internet connections in real time.
First we have to add permissions ACCESS_NETWORK_STATE in AndroidManifest.xml, this permission aims to allow the application we create to receive internet network status information, type <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
in the manifest tag like this code below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rmf.yourapp">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
....
This tutorial can only be run from Android Nougat (Api 24), make sure set minSdk 24 in build.gradle (Module)
Second stage, create an interface with a name ConnectivityObserver.kt
interface ConnectivityObserver {
fun observe(): Flow<Status>
fun isConnected(): Status
enum class Status(val message: String) {
Available("Back online"),
Unavailable("No internet connection"),
Losing("Internet connection lost"),
Lost("No internet connection")
}
}
From the line of code above, we create an enum class Status, this class aims to provide categorized network status.
- Available : Internet connection available
- Unavailable : Internet connection is not available
- Losing : Internet connection starts to drop
- Lost : Internet connection has been lost
The network status will be observed via the observer(): Flow<Status> function, and to initialize the network status we can use the isConnected() function: Status
The third stage, after creating the interface above, our next task is to create an implementation of the interface we created.
Create a new class with the name NetworkConnectivityObserver.kt, and type the code below as follows:
@ExperimentalCoroutinesApi
class NetworkConnectivityObserver(
application: Application
) : ConnectivityObserver {
private val connectivityManager =
application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override fun observe(): Flow<ConnectivityObserver.Status> {
return callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
launch { send(ConnectivityObserver.Status.Available) }
}
override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive)
launch { send(ConnectivityObserver.Status.Losing) }
}
override fun onLost(network: Network) {
super.onLost(network)
launch { send(ConnectivityObserver.Status.Lost) }
}
override fun onUnavailable() {
super.onUnavailable()
launch { send(ConnectivityObserver.Status.Unavailable) }
}
}
connectivityManager.registerDefaultNetworkCallback(callback)
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}.distinctUntilChanged()
}
override fun isConnected(): ConnectivityObserver.Status {
return if (connectivityManager.activeNetwork != null
&&
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) != null
)
ConnectivityObserver.Status.Available
else
ConnectivityObserver.Status.Unavailable
}
}
The final stage, we can use NetworkConnectiviyObserver in MainActivity.kt
class MainActivity : ComponentActivity() {
private lateinit var connectivityObserver: ConnectivityObserver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
connectivityObserver = NetworkConnectivityObserver(application = application)
setContent {
NetworkObserverTheme {
val status by connectivityObserver.observe().collectAsState(initial = connectivityObserver.isConnected())
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Text(text = "network status: $status")
}
}
}
}
}
Thanks for reading!. Stay tuned for more Android articles by Naufal Adli. which will be coming soon and dont forget to like and follow.this artikel make Hand-crafted & Made with❤️.