Android Network Connection Tutorial

Advertisements


Android lets your application connect to the internet or any other local network and allows you to perform network operations.

A device can have various types of network connections. This chapter focuses on using either a Wi-Fi or a mobile network connection.

Checking Network Connection

Before you perform any netowrk operations, you must first check that are you connected to that network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below:

ConnectivityManager check = (ConnectivityManager) 
this.context.getSystemService(Context.CONNECTIVITY_SERVICE);  

Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to recieve it like this.

NetworkInfo[] info = check.getAllNetworkInfo();

The last thing you need to do is to check Connected State of the network. Its syntax is given below:

for (int i = 0; i<info.length; i++){
   if (info[i].getState() == NetworkInfo.State.CONNECTED){
      Toast.makeText(context, "Internet is connected
      Toast.LENGTH_SHORT).show();
   }
}

Apart from this connected states, there are other states a network can achieve. They are listed below:

Sr.NoState
1Connecting
2Disconnected
3Disconnecting
4Suspended
5Unknown

Performing Network Operations

After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url.

Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows:

String link = "http://www.google.com";
URL url = new URL(link);   

After that you need to call openConnection method of url class and recieve it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();			   

And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below:

InputStream is = conn.getInputStream();
BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";
while ((data = reader.readLine()) != null){
   webPage += data + "\n";
}

Apart from this connect method, there are other methods availaible in HttpURLConnection class. They are listed below:

Sr.NoMethod & description
1disconnect()
This method releases this connection so that its resources may be either reused or closed
2getRequestMethod()
This method returns the request method which will be used to make the request to the remote HTTP server
3getResponseCode()
This method returns response code returned by the remote HTTP server
4setRequestMethod(String method)
This method Sets the request command which will be sent to the remote HTTP server
5usingProxy()
This method cReturns whether this connection uses a proxy server or not

Example

The below example demonstrates the use of HttpURLConnection class. It crates a basic application that allows you to download HTML from a given webpage.

To experiment with this example , you need to run this on an actual device on which wifi internet is connected .

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as NetworkConnection under a package com.example.networkconnection. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add Activity code.
3Create src/DownloadWebPage.java file to add NetworkConnection code.
4Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5Modify res/values/string.xml file and add necessary string components.
6Modify AndroidManifest.xml to add necessary permissions.
7Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/com.example.networkconnection/MainActivity.java.

package com.example.networkconnection;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

   private EditText urlField;
   private TextView data;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      urlField = (EditText)findViewById(R.id.editText1);
      data = (TextView)findViewById(R.id.textView2);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

   public void download(View view){

      String url = urlField.getText().toString();
      new DownloadWebPage(this,data).execute(url);
   }

}

Here is the content of src/com.example.networkconnection/DownloadWebPage.java.

package com.example.networkconnection;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadWebPage extends AsyncTask{

   private TextView dataField;
   private Context context;
   public DownloadWebPage(Context context,TextView dataField) {
      this.context = context;
      this.dataField = dataField;
   }


   //check Internet conenction.
   private void checkInternetConenction(){
      ConnectivityManager check = (ConnectivityManager) this.context.
      getSystemService(Context.CONNECTIVITY_SERVICE);
      if (check != null) 
      {
         NetworkInfo[] info = check.getAllNetworkInfo();
         if (info != null) 
            for (int i = 0; i <info.length; i++) 
            if (info[i].getState() == NetworkInfo.State.CONNECTED)
            {
               Toast.makeText(context, "Internet is connected",
               Toast.LENGTH_SHORT).show();
            }

      }
      else{
         Toast.makeText(context, "not conencted to internet",
         Toast.LENGTH_SHORT).show();
          }
   }
   protected void onPreExecute(){
      checkInternetConenction();
   }
   @Override
   protected String doInBackground(String... arg0) {
      try{
         String link = (String)arg0[0];
         URL url = new URL(link);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setReadTimeout(10000);
         conn.setConnectTimeout(15000);
         conn.setRequestMethod("GET");
         conn.setDoInput(true);
         conn.connect();
         InputStream is = conn.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader
         (is, "UTF-8") );
         String data = null;
         String webPage = "";
         while ((data = reader.readLine()) != null){
            webPage += data + "\n";
         }
         return webPage;
      }catch(Exception e){
         return new String("Exception: " + e.getMessage());
      }
   }
   @Override
   protected void onPostExecute(String result){
      this.dataField.setText(result);
   }
}

Here is the content of 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" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="30dp"
      android:text="@string/url"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/textView1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="18dp"
      android:ems="10" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/editText1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="69dp"
      android:onClick="download"
      android:text="@string/click" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editText1"
      android:layout_below="@+id/button1"
      android:layout_marginTop="56dp"
      android:text="@string/google"
      android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

Here is the content of Strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">NetworkConnection</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="url">URL here</string>
   <string name="click">Download WebPage</string>
   <string name="google">http://www.tutorialspoint.com</string>
</resources>

Here is the content of AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.networkconnection"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.networkconnection.MainActivity"
         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>

Let's try to run your NetworkConnection application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid Network Connection Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen:

Anroid Network Connection Tutorial

Now just type in your website whose HTML you want to fetch. In my case i am typing tutorialspoint.com. It is shown in the figure:

Anroid Network Connection Tutorial

Now press the Download WebPage button and wait a few seconds and HTML will be downloaded and will be shown to you. It is shown in the figure below:

Anroid Network Connection Tutorial

Advertisements
Advertisements