You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取断开网络的详情?Android中BroadcastReceiver/NetworkCallback实现咨询

Getting Details of Disconnected Networks on Android: BroadcastReceiver vs NetworkCallback

Hey there! Let's break down how you can track disconnected networks on Android—since you're already aware that the old go-to methods (like EXTRA_NETWORK_INFO, getNetworkInfo()) are deprecated, and getAllNetworks() only returns currently active networks.


First, Let's Talk About BroadcastReceiver

The old CONNECTIVITY_ACTION broadcast is pretty much obsolete for this use case now:

  • Starting with API 29, this broadcast is restricted for background apps, so you can't rely on it to get consistent updates.
  • Even on older versions, the data you'd get from it about disconnected networks is vague and not as detailed as you need.
    Bottom line: Skip BroadcastReceiver for this—it's not reliable anymore for getting disconnected network details.

Google built this as the modern replacement for network state tracking, and it's perfect for getting details about networks that just disconnected. Here's how to make it work:

Step 1: Create & Register the NetworkCallback

You'll need to subclass NetworkCallback and override key methods to catch network disconnects, then register it with a NetworkRequest.

// Get the ConnectivityManager system service
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

// Build a request to listen for all network types (or narrow it down to WIFI/CELLULAR if needed)
val networkRequest = NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
    .build()

// Define your callback logic
val networkCallback = object : ConnectivityManager.NetworkCallback() {
    // This fires when a network is disconnected
    override fun onLost(network: Network) {
        super.onLost(network)
        // Grab the capabilities of the disconnected network
        val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
        
        networkCapabilities?.let { caps ->
            // Figure out what type of network just disconnected
            val isWifi = caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
            val isCellular = caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
            
            // Get extra details like if it was a metered network
            val wasMetered = caps.isMetered
            
            // Now you have all the details you need!
            Log.d("NetworkLogs", "Disconnected: ${if(isWifi) "WIFI" else "CELLULAR"} | Metered: $wasMetered")
        }
    }

    // This triggers when there are no available networks at all
    override fun onUnavailable() {
        super.onUnavailable()
        Log.d("NetworkLogs", "No active networks left!")
    }
}

// Register the callback to start listening
connectivityManager.registerNetworkCallback(networkRequest, networkCallback)

Step 2: Don't Forget to Unregister

To avoid memory leaks, make sure to unregister the callback when you're done with it (like in your Activity's onDestroy()):

override fun onDestroy() {
    super.onDestroy()
    connectivityManager.unregisterNetworkCallback(networkCallback)
}

Why This Works Better

  • Unlike getAllNetworks(), the onLost() callback gives you direct access to the Network object that just went down. You can use getNetworkCapabilities(network) to pull all sorts of details about it—network type, metered status, bandwidth, and more.
  • This works on API 21 and above, so it's compatible with most modern Android devices.
  • It's the official Google-recommended method, so you won't run into the same deprecation issues as the old BroadcastReceiver approach.

Quick Recap

  • Avoid BroadcastReceiver: It's limited, deprecated, and unreliable for this use case.
  • Use NetworkCallback: The onLost() method gives you the disconnected network's object, and NetworkCapabilities lets you extract all the details you need.

内容的提问来源于stack exchange,提问作者Sathish Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:34:22