Translated from: Baidu. To better obtain the network connection status of the device, Android provides two classes to do this, namely connectivitymanager and networkinfo. Generally, we do not need to create them manually.
Connectivitymanager object instance. We can obtain an instance through context object context.
ConnectivityManager connManager = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE);
Connectivitymanager does not have much function, but it can get the networkinfo object (get the current network connection status ). You can obtain the networkinfo object in three ways. However, if you want to know the network connection status immediately, the following method works best:
NetworkInfo info = connManager.getActiveNetworkInfo();
Alternatively, you can use connectivitymanager to obtain a group of available networkinfo objects in the system. Each networkinfo represents a network type (e.g. WiFi ).
NetworkInfo info = connManager.getAllNetworkInfo();
You can obtain all information about a network type through the networkinfo object. You can check whether a network type is currently available. If you have already connected to the network, you can obtain the network that you are currently connected to. Below are some important networkinfo methods. The result of these methods is displayed on the screen (WIFI or UMTS network information)
info.isAvailable()info.isConnected()info.isConnectedOrConnecting()info.getState()info.getDetailedState()info.getTypeName()info.getType()info.getSubtypeName()info.getSubtype()
Networkinfo showing only disconnected states
Networkinfo showing an established WiFi connection
Networkinfo showing an established UMTS connection
To access the network, you must explicitly declare the permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Related Articles:
- Android: Getting notified of connectivity
Changes