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.

Android Check Internet Connection Tutorial - The Crazy Programmer

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>

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();   
    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
      {return true;}  
    else 
      {return false;}
}


Step 3: we can now call above function in onClick listener of any component of android.

// Check for Internet Connection
if (isOnline() )
{
   Toast.makeText(getApplicationContext(), 
"Internet Connected", Toast.LENGTH_SHORT).show();
}
else 
{  Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}


Comments

  1. It was really helpful!!
    A good tutorial for building base in android. Thank u!!

    ReplyDelete
  2. Very well explained... Indeed a good guideline for beginners!

    ReplyDelete
  3. Great initiative ma'am....... Will b looking forward for more such interesting tutorials

    ReplyDelete
  4. Good job, well explained

    ReplyDelete
  5. Great effort mam, well explained tutorial

    ReplyDelete
  6. Nice info mam.
    Very well explain

    ReplyDelete
  7. Nice..!!! Very helpful tutorial for beginners..!!! Keep it up..!!!

    ReplyDelete
  8. Very well explained,It was really helpful

    ReplyDelete

Post a Comment

Popular posts from this blog

Create an android app that demonstrates Activity Lifecycle and Instance State.

Program using Light Sensitive Sensors on Tinkercad