Tuesday, 4 December 2012

Android Detect Internet Connection Status

Android Detect Internet Connection Status

     In most of the application running in android needs internet.So it is very important in every application to check whether the internet is available or not.


1.Create a new  Android Project.
2.After creating the project,add the required permissions in your             
    AndroidManifest.xml file.

  • To access the internet we need internet permission.
  • To detect network status we need ACCESS_NETWORK_STATE permission.
Copy paste the bellow code.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
  android:label="@string/app_name" >
  android:label="@string/app_name" >
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  • To add the permission manually.Take AndroidManifest.xml
  • Then take Permissions-->Add-->Uses Permissions-->Select the required permissions from the combo box provided.

3.Create a class file named as ConnectionDetector.java and apply the
   following code.

package com.example.detectinternetconnection;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;}}

4.Whenever user needs to check the internet connection,we use the function 
called isConnectingToInternet()

ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false

5.In this tutorial,i am placing a button to show the internet status by a click.

6.Open the main.xml file and copy the bellow code. 
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com
/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Detect Internet Status" /> <Button android:id="@+id/btn_check" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Check Internet Status" android:layout_centerInParent="true"/> <RelativeLayout>

7.Finally paste the given bellow code to your MainActivity.class file

package com.roney.detectinternetconnection; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; public class AndroidDetectInternetConnectionActivity 
extends Activity { // flag for Internet connection status Boolean isInternetPresent = false; // Connection detector class ConnectionDetector cd; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnStatus = (Button) findViewById(R.id.btn_check); // creating connection detector class instance cd = new ConnectionDetector(getApplicationContext()); /** *Check Internet status button click event * */ btnStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // get Internet status isInternetPresent = cd.isConnectingToInternet(); // check for Internet status if (isInternetPresent) 
{ // Internet Connection is Present // make HTTP requests showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection", "You have internet connection", true); } else { // Internet connection is not present // Ask user to connect to Internet showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection", "You don't have internet connection.", false); } } }); } /** * 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) * */ 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) { } }); // Showing Alert Message alertDialog.show(); } }

8.Output is shown bellow.

If you need to run this application in the android smartphone

Hope you understand how it works.

" Ask your doubts and comments please "


Anonymous said...

Thanks alot

After a long search i found ur blog