Sunday, January 13, 2013

Android checking Internet Connection Availability

Sometimes it is good practise to know about the connection availability before the use. for this purpose make a class with name AppStatus



package jitesh.example.earthquake;

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;
    }

    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;
    }
}


and use it on your need with following code


ConnectionDetector cd;
  Boolean isInternetPresent = false;

inside the onCreate of main activity write the code
 cd = new ConnectionDetector(getApplicationContext());

finally check after a button click



isInternetPresent = cd.isConnectingToInternet();
       
            // check for Internet status
            if (isInternetPresent) {
                // Internet Connection is Present
                // make HTTP requests
                showAlertDialog(Earthquake.this, "Internet Connection",
                        "You have internet connection", true);
            } else {
                // Internet connection is not present
                // Ask user to connect to Internet
                showAlertDialog(Earthquake.this, "No Internet Connection",
                        "You don't have internet connection.", false);
            }


the showAlertDialog method is given below


    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
       // alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });



No comments:

Post a Comment