How to detect Network Status
How to detect whether network is enable or not. Can download? Can get data from the server?
Enable web button when network works fine.
In that case, we can use ConnectivityManger + NetworkInfo
ConnectivityManger
Get ConnectivityManger in Activity
ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo
Get NetworkInfo from ConnectivityManager
NetworkInfo info = cm.getActiveNetworkInfo();
Using NetworkInfo, we can get several useful information.
I defined NetworkStatus(enum) to easy to understand. This is network status wrapper
Sample
Status
public enum NetworkStatus { OFF, WIFI, MOBILE, WIMAX, BLUETOOTH, ETHERNET; }
Detect network status
public static NetworkStatus getConnectedState( ConnectivityManager manager ) { NetworkStatus status = NetworkStatus.OFF; NetworkInfo info = manager.getActiveNetworkInfo(); if ( info != null ) { if ( info.isConnected() ) { switch ( info.getType() ) { case ConnectivityManager.TYPE_WIFI: // Wifi status = NetworkStatus.WIFI; break; case ConnectivityManager.TYPE_MOBILE_DUN: // Mobile 3G case ConnectivityManager.TYPE_MOBILE_HIPRI: case ConnectivityManager.TYPE_MOBILE_MMS: case ConnectivityManager.TYPE_MOBILE_SUPL: case ConnectivityManager.TYPE_MOBILE: status = NetworkStatus.MOBILE; break; case ConnectivityManager.TYPE_BLUETOOTH: // Bluetooth status = NetworkStatus.BLUETOOTH; break; case ConnectivityManager.TYPE_ETHERNET: // Ethernet status = NetworkStatus.ETHERNET; break; } } } return status; }
Whether the connection is enable or not
public static boolean isConnected ( ConnectivityManager manager ) { NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null ) { return false; } return info.isConnected(); }
Activity
public class NetworkActivity extends Activity { private static String TAG = "Network"; ConnectivityManager cm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); // connectivity connectionCheck(); connectionStatus(); } private void connectionCheck() { if ( NetworkConnection.isConnected(cm) ) { Log.i(TAG, "Connected"); } else { Log.i(TAG, "Disconnected"); } } private void connectionStatus() { switch ( NetworkConnection.getConnectedState(cm) ) { case MOBILE: Log.i(TAG, "Mobile"); break; case WIFI: Log.i(TAG, "Wifi"); break; case OFF: Log.i(TAG, "Off"); break; default: Log.i(TAG, "Other"); break; } } }
Real device is better to test.
Warning!
We need 2 permissions to use these programs
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
First one is for internet, Second one is to use NetowrkInfo.