Sunday, 28 December 2014

Check android network connectivity (wi-fi / data plan)

How to determine android device connection.

In android device, so easy to determine android device connection type. This will help to improve application performance. for example if application


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 /**
  * <a>This method check Internet connection status.
  * If Internet connection not available return 0.
  * 1 for wi-fi connection,
  * 2 for mobile data plan.
  * @param activity
  * @return connection status, 1-wifi,2-data plan, 0- no internet connection
  */
 public static int checkNetworkStatus(final Activity activity) {
  int flag=0;
  // Get connect mangaer
  final ConnectivityManager connMgr = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
  // check for wifi
  final android.net.NetworkInfo wifi =  connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

  // check for mobile data
  final android.net.NetworkInfo mobile =  connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

  /**
   * wifi connection
   */
  if( wifi.isAvailable() ){
   flag=1;
  }  
  /**
   * mobile dataplan
   */
  else if( mobile.isAvailable() ){
   flag=2;
  }  
  return flag;
 }  

You have to add permission in manifest file.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

No comments:

Post a Comment