How to make sure the network is available in android?

By | October 5, 2010

Get all the available network connections

public boolean isNetworkAvailable()
{
	Context context = getApplicationContext();
	ConnectivityManager connectivity = (ConnectivityManager)
	context.getSystemService(Context.CONNECTIVITY_SERVICE);
	if (connectivity == null)
	{

		Toast.makeText(this, "No conectivity", Toast.LENGTH_LONG).show();
	}
	else
	{
		NetworkInfo[] info = connectivity.getAllNetworkInfo();
		if (info != null)
		{
			for (int i = 0; i < info.length; i++)
			{
				if (info[i].getState() == NetworkInfo.State.CONNECTED)
				{
					Toast.makeText(this, ""+info[i].getTypeName(), Toast.LENGTH_LONG).show();
					return true;
				}
			}
		}
	}
	return false;
}

One important thing is that don’t forget to add the following lines in the manifest file

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

Leave a Reply

Your email address will not be published.