LoginSignup
1

Android Network接続確認を監視するコードをサクッと書いてみる

Last updated at Posted at 2023-05-15

AndroidでNetworkへの接続を確認する

自分で作ったことなかったので、サクッとやったメモ
https://github.com/kkhouse/Playground/tree/main/AndroidProject/Network/connecticitySample

sealed class NetworkStatus {
    object Unknown: NetworkStatus()
    object Connected: NetworkStatus()
    object Disconnected: NetworkStatus()
}

class NetworkConnectivityServiceImpl(
    context: Context,
    request: NetworkRequest = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .build(),
): NetworkConnectivityService  {
    private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    override val networkStatus: Flow<NetworkStatus> = callbackFlow {
        val connectivityCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                trySend(NetworkStatus.Connected)
            }

            override fun onUnavailable() {
                trySend(NetworkStatus.Disconnected)
            }

            override fun onLost(network: Network) {
                trySend(NetworkStatus.Disconnected)
            }
        }
        connectivityManager.registerNetworkCallback(request, connectivityCallback)
        awaitClose {
            connectivityManager.unregisterNetworkCallback(connectivityCallback)
        }
    }
        .distinctUntilChanged()
        .flowOn(Dispatchers.IO)

}
  • ConnectivityManagerがCallbackだったので、callbackFlowでラップする。

  • ChannelにてtrySendすることで値の変更を送信する。

val networkStatus = NetworkConnectivityServiceImpl(context).networkStatus.stateIn(
        initialValue = NetworkStatus.Unknown,
        scope = viewModelScope,
        started = WhileSubscribed(5000)
    )

ViewModel等で監視すればComposable側で使える。(上はベタガキですが、ContextはDIした方が良いです。)

Screenshot 2023-05-16 at 6.40.20.png

機内モードにするとDisconnectedなので多分動いている。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1