Wednesday, November 21, 2012

Check Internet Connection

In this tutorial we learn about how to check whether internet connection is available or not in android.


for this first of all you need to give to permission in your manifest file.

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

Now show below example for more detail.

Your main activity xml file look like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content
        android:layout_height="wrap_content"
        android:text="Check Internet" />

</LinearLayout>

In your Activity JAVA file first of check internet connection using ConnectivityManager class.

ConnectivityManager connectivity = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

Your java file looks like this.


public class abcd extends Activity {

 private Button checkinternet;
 boolean isInternetPresent;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  checkinternet = (Button) findViewById(R.id.button1);
  checkinternet.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    isInternetPresent = checkInternet();

    if (isInternetPresent) {

     showAlertDialog("Internet Connection", "You have internet connection", true);
    }
    else {
     showAlertDialog("Internet Connection", "You have no internet connection", false);
    }
   }
  });
 }

 public boolean checkInternet() {

  ConnectivityManager connectivity = (ConnectivityManager) this.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;
 }

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

  alertDialog.setTitle(title);

  alertDialog.setMessage(message);

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

  alertDialog.show();
 }
}

Hope this post is helpful for you...


No comments:

Post a Comment