|
| 1 | +/* |
| 2 | + * Copyright 2026 Google LLC |
| 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 | +package com.google.firebase.dataconnect.core |
| 17 | + |
| 18 | +import android.content.Context |
| 19 | +import android.content.Context.CONNECTIVITY_SERVICE |
| 20 | +import android.net.ConnectivityManager |
| 21 | +import android.net.Network |
| 22 | +import android.net.NetworkCapabilities |
| 23 | +import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET |
| 24 | +import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED |
| 25 | +import android.net.NetworkRequest |
| 26 | +import android.os.Build |
| 27 | +import androidx.annotation.RequiresApi |
| 28 | +import com.google.firebase.dataconnect.util.coroutines.ConflatedSignal |
| 29 | +import com.google.firebase.dataconnect.util.coroutines.signalIfNotNull |
| 30 | +import java.util.concurrent.locks.ReentrantLock |
| 31 | +import kotlin.concurrent.withLock |
| 32 | +import kotlinx.coroutines.flow.Flow |
| 33 | +import kotlinx.coroutines.flow.emitAll |
| 34 | +import kotlinx.coroutines.flow.flow |
| 35 | + |
| 36 | +internal data object NetworkConnectivityRestored |
| 37 | + |
| 38 | +/** |
| 39 | + * Creates a cold [Flow] of [NetworkConnectivityRestored] events that monitors network connectivity |
| 40 | + * changes that potentially result in a restoration of network connectivity. |
| 41 | + * |
| 42 | + * Emissions from this flow signify that the network connectivity status has changed in a way that |
| 43 | + * suggests a network connection might now be successfully established. |
| 44 | + * |
| 45 | + * A downstream connection retry backoff mechanism can collect this flow to interrupt or abort a |
| 46 | + * retry suspension (backoff delay). Instead of waiting for the full backoff timeout to expire, the |
| 47 | + * mechanism can immediately re-attempt the connection upon receiving a |
| 48 | + * [NetworkConnectivityRestored] event. |
| 49 | + * |
| 50 | + * If the [Flow] is collected while a network appears to be available then an event will be emitted |
| 51 | + * immediately. Namely, it will not wait for some other network to become available to emit the |
| 52 | + * first event if a network is _already_ available. |
| 53 | + * |
| 54 | + * @param context The [Context] used to retrieve the [ConnectivityManager] system service. |
| 55 | + * @return A cold [Flow] emitting [NetworkConnectivityRestored] on network state transitions that |
| 56 | + * suggest that network connectivity is now (or continues to be) available. |
| 57 | + */ |
| 58 | +internal fun networkConnectivityRestoredFlow(context: Context): Flow<NetworkConnectivityRestored> { |
| 59 | + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { |
| 60 | + networkConnectivityRestoredFlowAPI24(context) |
| 61 | + } else { |
| 62 | + networkConnectivityRestoredFlowAPI23(context) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +private fun networkConnectivityRestoredFlowAPI23( |
| 67 | + context: Context |
| 68 | +): Flow<NetworkConnectivityRestored> = |
| 69 | + networkConnectivityRestoredFlow(context) { |
| 70 | + val request = NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build() |
| 71 | + registerNetworkCallback(request, it) |
| 72 | + } |
| 73 | + |
| 74 | +@RequiresApi(Build.VERSION_CODES.N) |
| 75 | +private fun networkConnectivityRestoredFlowAPI24( |
| 76 | + context: Context |
| 77 | +): Flow<NetworkConnectivityRestored> = |
| 78 | + networkConnectivityRestoredFlow(context) { registerDefaultNetworkCallback(it) } |
| 79 | + |
| 80 | +private fun networkConnectivityRestoredFlow( |
| 81 | + context: Context, |
| 82 | + registerCallback: ConnectivityManager.(ConnectivityManager.NetworkCallback) -> Unit |
| 83 | +): Flow<NetworkConnectivityRestored> = flow { |
| 84 | + val connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) |
| 85 | + checkNotNull(connectivityManager) { |
| 86 | + "getSystemService(CONNECTIVITY_SERVICE) returned null; " + |
| 87 | + "try adding android.permission.ACCESS_NETWORK_STATE to AndroidManifest.xml [yxzng5zfyg]" |
| 88 | + } |
| 89 | + check(connectivityManager is ConnectivityManager) { |
| 90 | + "internal error rfq632nm3m: getSystemService(CONNECTIVITY_SERVICE) should have returned " + |
| 91 | + "an instance of ${ConnectivityManager::class.qualifiedName}, but got $connectivityManager" |
| 92 | + } |
| 93 | + |
| 94 | + val callback = NetworkCallbackImpl() |
| 95 | + registerCallback(connectivityManager, callback) |
| 96 | + |
| 97 | + try { |
| 98 | + emitAll(callback.signal.signals) |
| 99 | + } finally { |
| 100 | + connectivityManager.unregisterNetworkCallback(callback) |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +private class NetworkCallbackImpl : ConnectivityManager.NetworkCallback() { |
| 105 | + |
| 106 | + val signal = ConflatedSignal<NetworkConnectivityRestored>() |
| 107 | + |
| 108 | + private val lock = ReentrantLock() |
| 109 | + private val availableNetworks = mutableSetOf<Network>() |
| 110 | + private val validatedNetworks = mutableSetOf<Network>() |
| 111 | + |
| 112 | + override fun onAvailable(network: Network) { |
| 113 | + val signalOrNull = |
| 114 | + lock.withLock { |
| 115 | + val networkAdded = availableNetworks.add(network) |
| 116 | + if (networkAdded) NetworkConnectivityRestored else null |
| 117 | + } |
| 118 | + |
| 119 | + signal.signalIfNotNull(signalOrNull) |
| 120 | + } |
| 121 | + |
| 122 | + override fun onLost(network: Network) { |
| 123 | + val signalOrNull = |
| 124 | + lock.withLock { |
| 125 | + availableNetworks.remove(network) |
| 126 | + val wasValidated = validatedNetworks.remove(network) |
| 127 | + // Only signal if we have other validated networks that can take over (API 23 failover) |
| 128 | + if (wasValidated && validatedNetworks.isNotEmpty()) NetworkConnectivityRestored else null |
| 129 | + } |
| 130 | + |
| 131 | + signal.signalIfNotNull(signalOrNull) |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Notifies the callback when the network block status changes (e.g. background data saver rules |
| 136 | + * are toggled). We signal when the network becomes unblocked (`blocked == false`) so consumers |
| 137 | + * can attempt to reconnect. |
| 138 | + */ |
| 139 | + @RequiresApi(Build.VERSION_CODES.Q) |
| 140 | + override fun onBlockedStatusChanged(network: Network, blocked: Boolean) { |
| 141 | + lock.withLock { availableNetworks.add(network) } |
| 142 | + if (!blocked) { |
| 143 | + signal.signal(NetworkConnectivityRestored) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * Handles capability changes for a network. |
| 149 | + * |
| 150 | + * On Android 9 (API 28) and above, this callback is invoked frequently for minor capability |
| 151 | + * updates such as signal strength (RSSI) fluctuations or bandwidth estimate changes, even if the |
| 152 | + * connection remains active and stable. |
| 153 | + * |
| 154 | + * To prevent excessive signals and unnecessary reconnection attempts by downstream consumers, |
| 155 | + * this method filters out those redundant updates and only signals when the network's validation |
| 156 | + * status (presence of [NET_CAPABILITY_VALIDATED]) actually transitions (either gained or lost). |
| 157 | + */ |
| 158 | + override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { |
| 159 | + val isValidated = networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) |
| 160 | + |
| 161 | + val signalOrNull = |
| 162 | + lock.withLock { |
| 163 | + availableNetworks.add(network) |
| 164 | + if (isValidated) { |
| 165 | + val networkAdded = validatedNetworks.add(network) |
| 166 | + if (networkAdded) NetworkConnectivityRestored else null |
| 167 | + } else { |
| 168 | + val networkRemoved = validatedNetworks.remove(network) |
| 169 | + if (networkRemoved && validatedNetworks.isNotEmpty()) NetworkConnectivityRestored |
| 170 | + else null |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + signal.signalIfNotNull(signalOrNull) |
| 175 | + } |
| 176 | +} |
0 commit comments