1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.network
18 
19 import android.content.Context
20 import android.net.ConnectivityManager
21 import android.net.ConnectivityManager.NetworkCallback
22 import android.net.Network
23 import android.net.NetworkCapabilities
24 import android.util.Log
25 import kotlinx.coroutines.Dispatchers
26 import kotlinx.coroutines.channels.awaitClose
27 import kotlinx.coroutines.flow.Flow
28 import kotlinx.coroutines.flow.callbackFlow
29 import kotlinx.coroutines.flow.conflate
30 import kotlinx.coroutines.flow.flowOn
31 
32 class ConnectivityRepository(context: Context) {
33     private val connectivityManager = context.getSystemService(ConnectivityManager::class.java)!!
34 
<lambda>null35     fun networkCapabilitiesFlow(): Flow<NetworkCapabilities> = callbackFlow {
36         val callback = object : NetworkCallback() {
37             override fun onCapabilitiesChanged(
38                 network: Network,
39                 networkCapabilities: NetworkCapabilities,
40             ) {
41                 trySend(networkCapabilities)
42                 Log.d(TAG, "onCapabilitiesChanged: $networkCapabilities")
43             }
44 
45             override fun onLost(network: Network) {
46                 trySend(NetworkCapabilities())
47                 Log.d(TAG, "onLost")
48             }
49         }
50         trySend(getNetworkCapabilities())
51         connectivityManager.registerDefaultNetworkCallback(callback)
52 
53         awaitClose { connectivityManager.unregisterNetworkCallback(callback) }
54     }.conflate().flowOn(Dispatchers.Default)
55 
getNetworkCapabilitiesnull56     private fun getNetworkCapabilities(): NetworkCapabilities =
57         connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
58             ?: NetworkCapabilities()
59 
60     private companion object {
61         private const val TAG = "ConnectivityRepository"
62     }
63 }
64