Check Internet connectivity in android
Many applications connect to Internet to perform certain tasks, so in this tutorial we will see how to create a java class to check the internet connection of mobile. So lets begin.

Step 1- we need to provide permission in manifest file.
<manifest>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 1- we need to provide permission in manifest file.
<manifest>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application...
...............
</activity>
</manifest>
...............
</activity>
</manifest>
Step 2- create below function after onCreate() method to check Internet connection.
protected boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
ConnectivityManager cm = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{return true;}
else
{return false;}
}
{return false;}
}
Step 3: we can now call above function in onClick listener of any component of android.
// Check for Internet Connection
if (isOnline() )
if (isOnline() )
{
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
}
else
{ Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
It was really helpful!!
ReplyDeleteA good tutorial for building base in android. Thank u!!
thank you @abhishek.
DeleteVery well explained... Indeed a good guideline for beginners!
ReplyDeletethank you
DeleteNicely explained...keep it up!
ReplyDeleteGreat initiative ma'am....... Will b looking forward for more such interesting tutorials
ReplyDeleteGood job, well explained
ReplyDeleteGreat effort mam, well explained tutorial
ReplyDeleteThank you
DeleteNice info mam.
ReplyDeleteVery well explain
Very well explain mam
ReplyDeleteNice..!!! Very helpful tutorial for beginners..!!! Keep it up..!!!
ReplyDeleteVery well explained,It was really helpful
ReplyDeleteVery helpful 👍
ReplyDeleteVery helpful
ReplyDelete👍
ReplyDelete