Search This Blog

Monday, March 31, 2014

Android Network Connection Check


Add below code in AndroidManifest.xml

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


Reference :
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.Activity;
import android.content.Context;

Function:

public  boolean isNetworkConnected(Activity  activity  ) {
ConnectivityManager connMgr = (ConnectivityManager)activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connMgr.getActiveNetworkInfo();

if (ni == null) {
  Toast.makeText(Ac,"No internet connection can be found.", Toast.LENGTH_LONG).show();
return false;
} else
return true;
}
Note: For normal activeity isNetworkConnected(this)

public static final boolean isNetworkConnected(Context  con) {
ConnectivityManager connMgr = (ConnectivityManager)con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connMgr.getActiveNetworkInfo();

if (ni == null) {
Toast.makeText(con,"No internet connection can be found.", Toast.LENGTH_LONG).show();
return false;
} else
return true;
}
Note: For Context isNetworkConnected(context)  .i.e. inside OnClickListener

No comments:

Post a Comment