Friday, January 24, 2014

Android Tutorial on Checking Internet Connection

Android Tutorial on Checking Internet Connection - Hallo sahabat Google Android Developer Tutorial, Pada Artikel yang anda baca kali ini dengan judul Android Tutorial on Checking Internet Connection, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel Android checking Internet Connection, Artikel Connectivity Manager, Artikel HttpConnection, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Android Tutorial on Checking Internet Connection
link : Android Tutorial on Checking Internet Connection

Baca juga


Android Tutorial on Checking Internet Connection

Android Tutorial on Checking  Internet Connection
                        Many Android applications needs to connect to internet to complete the task.It is better to check internet connectivity status before making any HTTP Requests in your program to avoid http exceptions.Some of the most common uses for repeating alarms and background services is to schedule regular updates of application data from Internet resources, cache data, or execute long running downloads. But if you aren't connected to the Internet, or the connection is too slow to complete your download, why both waking the device to schedule the update at all?
Connectivity Manager
                           ConnectivityManager to is used to check that you're actually connected to the Internet, and if so, what type of connection is in place.Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. Get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE).
The primary responsibilities of this class are to:
  • Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
  • Send broadcast intents when network connectivity changes
  • Attempt to "fail over" to another network when connectivity to a network is lost
  • Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
HttpURLConnection 
   HttpURLConnection which is also available in standard Java, is a general-purpose, lightweight HTTP client suitable for most applications.In the latest version HttpURLConnection supports the transparent response compression (via the header Accept-Encoding: gzip, Server Name Indication (extension of SSL and TLS) and a response cache.
Handler class
The Handler class can be used to register to a thread and provides a simple channel to send data to this thread.A Handler object registers itself with the thread in which it is created. For example, if you create a new instance of the Handler class in the onCreate() method of your activity, the resulting Handler object can be used to post data to the main thread.The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.
This Demonstrative project is used to test whether network connectivity and internet connection are available.
1.Create  Android project with details as listed in the table below.
Property name
Property value
Project name
SRM_InternetConnectionCheck
Package name
in.ac.srmuniv.internetcheck
Activity name
InternetConnectionActivity
Layout xml name
main
2.Copy the code  to the file main.xml in res/layout folder 
<?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" >
 </LinearLayout>

3.Copy the code in ConnectionDetector.java
packagein.ac.srmuniv.internetcheck;

import java.io.IOException;
importjava.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

importandroid.content.Context;
importandroid.net.ConnectivityManager;
importandroid.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class ConnectionDetector {

    private Context _context;
    List<String> connections;

    public ConnectionDetector(Context context) {
        this._context = context;
        connections=newArrayList<String>();
    }

    public booleanisConnectingToInternet() {
        boolean internetState=false;
        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)
                    {
                        connections.add(info[i].getTypeName());
                        internetState=true;
                       
                    }

        }
        return internetState;
    }
    List<String> getConnections()
    {
         return connections;   
    }

    public booleanhasActiveInternetConnection() {
        new Thread() {
            public void run() {
                Message msg = Message.obtain();

                try {
                    HttpURLConnection urlc = (HttpURLConnection) (new URL(
                            "http://www.google.com").openConnection());
                    urlc.setRequestProperty("User-Agent", "Test");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(1500);
                    urlc.connect();
                    boolean status = urlc.getResponseCode() == 200;
                    Bundle b = new Bundle();
                    b.putBoolean("status", status);
                    msg.setData(b);
                } catch (IOException e) {

                }
                messageHandler.sendMessage(msg);
            }

        }.start();

        return status;
    }

    private static Handler messageHandler = new Handler() {

        public voidhandleMessage(Message msg) {
            super.handleMessage(msg);
            status = msg.getData().getBoolean("status");

        }
    };
     static boolean status;

}

4.Copy the code in InternetConnectionActivity.java. Activity. 
packagein.ac.srmuniv.internetcheck;

import java.util.ArrayList;

importin.ac.srmuniv.internetcheck.R;
importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.content.Context;
importandroid.content.DialogInterface;
import android.os.Bundle;

public classInternetConnectionActivity extends Activity {
    // flag for Internet connection status
    private Boolean isInternetPresent = false;
    private Boolean isConnectionPresent = false;
    // Connection detector class
    private ConnectionDetector cd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // creating connection detector class instance
        cd = newConnectionDetector(getApplicationContext());

        // get Internet status
        isConnectionPresent = cd.isConnectingToInternet();
        isInternetPresent = cd.hasActiveInternetConnection();
        ArrayList<String> conn=(ArrayList<String>)cd.getConnections();
        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            showAlertDialog(InternetConnectionActivity.this,
                    "Internet Connection", "You have internet connection:"+conn+" Available", true);
        } else if (isConnectionPresent) {
            // Internet connection is not present
            // Ask user to connect to Internet
           
           
            showAlertDialog(InternetConnectionActivity.this,
                    "No Internet Connection",
                    "You have "+conn+" Available", false);
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            showAlertDialog(
                    InternetConnectionActivity.this,
                    "No Internet Connection",
                    "You don't have internet connection check for Mobile Data or WiFi is on.",
                    false);

        }
    }

    public voidshowAlertDialog(Context context, String title, String message,
            Boolean status) {
        final Boolean stat = 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", newDialogInterface.OnClickListener() {
            public voidonClick(DialogInterface dialog, int which) {
                if (!stat)
                    finish();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }

}
5.Modify the Androidmanifest.xml 
<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.ac.srmuniv.internetcheck"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10"/>
    <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".InternetConnectionActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>


</manifest>

6.Run the application in the emulator

 Figure 1 Shows Dialog box showing Internet Connection    Figure 2 Shows Dialog Box showing device with no  internet connection WiFi or Mobile data is off
Figure 3 Shows Dialog Box showing device with no  internet connection but WiFi or Mobile data is on
CODE EXPLANATION         
                              This  Demonstative application checks internet connection.When  Activity is loaded it checks for two things, wheather Connectivity is available  and what type of connectivity is available (WiFi or mobile) ,then it also checks if Active internet connection is available by pinging  google.com website.
The following code in ConnectingToInternet() method tests the connectivity status and returns boolean value true if connectivity is available.NetworkInfo class helps to fetch what type of connection(WiFi or mobile) is activated.getConnections() method returns list of connections.
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;
                    }
        }
The following code in hasActiveInternetConnection() method tests the internet connection status and returns boolean value true if internet connectivity is available.
HttpURLConnection urlc = (HttpURLConnection) (new URL(
                            "http://www.google.com").openConnection());
                    urlc.setRequestProperty("User-Agent""Test");
                    urlc.setRequestProperty("Connection""close");
                    urlc.setConnectTimeout(1500);
                    urlc.connect();
                    boolean status = urlc.getResponseCode() == 200;
         HttpURLConnection takes URL google.com to open connection and neccessary headers are set User-Agent is set to Test indicates it is a test connection.Connection header is set to close not keep-alive since we are oing to test for internet connectivity only and time out to 1500 ms.We take the status through response code 200 which ensures the mobile has active internet connection.
  This demostative App also shows the usage of simple Thread and message Handler.HttpURLConnection should not be run in main thread.if the Thread doing backround task wants to send message value during its process it uses Message to send the values the message is packed in Bundle.The Handler class has callback method handleMessage(Message msg) which will be called when message is send.Here the status of internet connection is send through Handler to be used my main thread.
           Message msg = Message.obtain();
            Bundle b = new Bundle();
             .....
             .....
           b.putBoolean("status", status);
                    msg.setData(b);
           messageHandler.sendMessage(msg);
           .....
           .....
    private static Handler messageHandler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            status = msg.getData().getBoolean("status");

        }
    };


Demikianlah Artikel Android Tutorial on Checking Internet Connection

Sekianlah artikel Android Tutorial on Checking Internet Connection kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Android Tutorial on Checking Internet Connection dengan alamat link https://googleandroiddevelopertutorial.blogspot.com/2014/01/android-tutorial-on-checking-internet.html

Artikel Terkait

Android Tutorial on Checking Internet Connection
4/ 5
Oleh

Berlangganan

Suka dengan artikel di atas? Silakan berlangganan gratis via email