Checking Network Status

The Android SDK provides utilities for gathering information about the current state of a network. This is useful for determining whether a network connection is available before trying to use a network resource. By validating network connectivity before attempting to make a connection, you can avoid many of the failure cases common in mobile device networking applications and provide your end users with a more pleasant user experience.

Retrieving Network Status Information Programmatically

Applications need to register the android.permission.ACCESS_NETWORK_STATE permission in the Android manifest file to read the network status of the device. To alter the network state of the device, the application must also have the android.per-mission.CHANGE_NETWORK_STATE permission.

Developers can leverage the ConnectivityManager class (android.net. ConnectivityManager) to access network status information about the device programmatically. You can get an instance of ConnectivityManager by using the familiar getSystemService() method of the application's Context object:

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

When you have a valid instance of ConnectivityManager, you can request the mobile (cellular) network information by using the getNetworkInfo() method:

NetworkInfo netlnfo =

conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

The NetworkInfo class (android.net.Networklnfo) has a number of methods for retrieving important information about the network state, including whether the network is available, connected, and roaming:

boolean isMobileAvail = netInfo.isAvailable(); boolean isMobileConn = netInfo.isConnected(); boolean isRoamingConn = netInfo.isRoaming();

The NetworkInfo class also has many other methods for determining fine-grained network status information. These can be read about in the documentation.

Checking Server Availability Programmatically

Even if a network is available and connected, there is no guarantee that the remote server you want to communicate with is accessible from the network. However, ConnectivityManager has a handy method called requestRouteToHost() that allows you to attempt to validate traffic, using a given network type (for example, mobile network, Wi-Fi) and IP address is possible.

0 0

Post a comment