Checking Internet Connection Availability in Android

Using ConnectivityManager class we can detect Internet connection availability in Android.

Code:

ConnectionDetector.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
  
public class ConnectionDetector {
  
    private Context _context;
  
    public ConnectionDetector(Context context){
        this._context = context;
    }
  
    /**
     * Checking for all possible internet providers
     * **/
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
  
          }
          return false;
    }
}


MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.view.View;

public class MainActivity extends Activity {
 // Connection detector class
 ConnectionDetector cd;
 // flag for Internet connection status
 Boolean isInternetPresent = false;
 // Alert Dialog Manager
 ShowAlert alert = new ShowAlert();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  cd = new ConnectionDetector(getApplicationContext());
 }

 public void checkavailability(View v) {
  // Check if Internet present
  isInternetPresent = cd.isConnectingToInternet();
  if (!isInternetPresent) {
   // Internet Connection is not present
   alert.showAlertDialog(MainActivity.this,
     "Fail",
     "Internet Connection is NOT Available", false); 
   // stop executing code by return
   return;
  } else {
   // Internet Connection is not present
   alert.showAlertDialog(MainActivity.this,
     "Success",
     "Internet Connection is Available", true);
   // stop executing code by return
   return;
  }
 }
}


ShowAlert.java

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
 
public class ShowAlert {
    /** 
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
 public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
//        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // Setting Dialog Title
        builder.setTitle(title);
 
        // Setting Dialog Message
        builder.setMessage(message);
 
        if(status != null)
            // Setting alert dialog icon
         builder.setIcon((status) ? R.drawable.success : R.drawable.fail);
 
        // Setting OK Button
        builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
 
        // Showing Alert Message
        builder.show();
    }
}

And your
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:onClick="checkavailability"
        android:text="Check Internet Availability" />

</RelativeLayout>
And don't forget to add these permissions in your Manifest file.
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />


Screen Shots


I hope this post is useful. kindly share your feedback as comment here.


Thank You



Popular posts from this blog

Spinner with multiple selection in Android

Simple Timer Example in android

Simple recyclerview example with checkbox in Android