Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/js-bhavyansh/network_connectivity

A simple Jetpack Compose app to monitor and display network connectivity status.
https://github.com/js-bhavyansh/network_connectivity

android-studio jetpack-compose kotlin network-connectivity network-status

Last synced: 2 days ago
JSON representation

A simple Jetpack Compose app to monitor and display network connectivity status.

Awesome Lists containing this project

README

        

# Network Connectivity Example

A simple Android application demonstrating how to detect network connectivity status using Jetpack Compose and Kotlin.

## Features
- Displays network connectivity status ("Connected" or "Unavailable") in real-time.
- Utilizes Jetpack Compose for the UI.
- Implements a ConnectivityManager to observe network state changes.

## Screenshot


First Screenshot
Second Screenshot

## Code Overview
The application consists of a `MainActivity` that sets the content view with a `NetworkScreen` composable. The NetworkScreen displays the network status text based on the current connectivity state.

**MainActivity**
The `MainActivity` sets up the content view and applies the theme.

```kotlin
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NetworkConnectivityTheme {
NetworkScreen()
}
}
}
}
```

**NetworkScreen**
The `NetworkScreen` composable displays "Connected" or "Unavailable" based on the network connectivity state.

```kotlin
@Composable
fun NetworkScreen() {
val connectionState by rememberConnectivityState()

val isConnected by remember(connectionState) {
derivedStateOf {
connectionState === NetworkConnectionState.Available
}
}

Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = if (isConnected) "Connected" else "Unavailable",
fontSize = 48.sp,
fontWeight = FontWeight.Bold
)
}
}
```

**Network Connectivity State**
The application uses a sealed interface to represent the network connection states:

```kotlin
sealed interface NetworkConnectionState {
data object Available : NetworkConnectionState
data object Unavailable : NetworkConnectionState
}
```

**Connectivity Manager**
The `ConnectivityManager` is used to observe the network connectivity state as a Flow:

```kotlin
private fun networkCallback(callback: (NetworkConnectionState) -> Unit): ConnectivityManager.NetworkCallback =
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
callback(NetworkConnectionState.Available)
}

override fun onLost(network: Network) {
callback(NetworkConnectionState.Unavailable)
}
}

fun getCurrentConnectivityState(connectivityManager: ConnectivityManager): NetworkConnectionState {
val network = connectivityManager.activeNetwork

val isConnected = connectivityManager.getNetworkCapabilities(network)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false

return if (isConnected) NetworkConnectionState.Available else NetworkConnectionState.Unavailable
}

fun Context.observeConnectivityAsFlow(): Flow = callbackFlow {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

val callback = networkCallback { connectionState -> trySend(connectionState) }

val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()

connectivityManager.registerNetworkCallback(networkRequest, callback)

val currentState = getCurrentConnectivityState(connectivityManager)
trySend(currentState)

awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}

val Context.currentConnectivityState: NetworkConnectionState
get() {
val connectivityManager =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return getCurrentConnectivityState(connectivityManager)
}
```

**Composable for Remembering Connectivity State**
The `rememberConnectivityState` composable provides a state holder for the network connection state:

```kotlin
@Composable
fun rememberConnectivityState(): State {
val context = LocalContext.current

return produceState(initialValue = context.currentConnectivityState) {
context.observeConnectivityAsFlow().collect {
value = it
}
}
}
```

## Contributing

Contributions are welcome! Please fork the repository and submit a pull request for any improvements or bug fixes.

1. Fork the repository.
2. Create your feature branch (`git checkout -b feature/your-feature`).
3. Commit your changes (`git commit -am 'Add some feature'`).
4. Push to the branch (`git push origin feature/your-feature`).
5. Create a new Pull Request.

## Contact

For questions or feedback, please contact [@Bhavyansh03-tech](https://github.com/Bhavyansh03-tech).

---