ConnectivityManager.getActiveNetwork返回值咨询:toString输出数字解析
Hey there! Let's break down your questions about getActiveNetwork() and that mysterious number in your log output.
1. Return Type of getActiveNetwork()
The getActiveNetwork() method returns an instance of android.net.Network (not a primitive type like int or boolean). This object represents a live network connection on the device, serving as your gateway to access details about the network's capabilities, properties, and even binding sockets to it.
2. What Does the Number in network.toString() Mean?
That number you're seeing in your log is the unique Network ID assigned to the active network instance by the Android system. The default toString() implementation of the Network class simply returns this integer ID, which the system uses internally to distinguish between different network connections (for example, switching from WiFi to mobile data will generate a new Network with a different ID).
If you want more meaningful information about the network instead of just an ID, use the ConnectivityManager to fetch the network's capabilities. Here's a quick replacement for your current log statement:
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Network network = connectivityManager.getActiveNetwork(); if (network != null) { NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); // Check if the network is WiFi boolean isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI); // Check if the network has internet access boolean hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); Log.e(TAG, "Network Type: " + (isWifi ? "WiFi" : "Mobile Data") + ", Has Internet: " + hasInternet); }
A quick heads-up: getActiveNetwork() requires API level 21 or higher, and you'll need the ACCESS_NETWORK_STATE permission declared in your AndroidManifest.xml to use it.
内容的提问来源于stack exchange,提问作者aman arora

