Networking with Android

Make connections to your world

Android, a rich platform for application development, offers an attractive set of user interface elements and data management capabilities. It also has a healthy array of networking options for developing applications that connect to the physical world. What would you want to connect to? Perhaps you want to tell the world everything you're doing using Twitter. Or maybe you want to be notified of your turn at the local laundromat or deli counter. If you have an interest in connecting Android to the world about you, read on.

Frank Ableson, Software designer

Frank Ableson is an entrepreneur and software developer in northern New Jersey, specializing in mobile and embedded application software. He is currently authoring a book about Android application development for Manning Publications. His professional interests are embedded systems, wireless communications, and automotive electronics. His biggest fans are his wife, Nikki, and their children.



09 June 2009

Also available in Russian Japanese

Introduction

This article, which builds on the foundation described in "Develop Android applications with Eclipse," explores the networking capabilities of Android. Learn how to leverage Android's array of networking options for fun and useful purposes. The Android platform is ideal for Java™ developers: They can use existing skills to bring network connectivity to a mobile, or "embedded," platform.

In this article, learn some networking options available for Android applications and about basic Android networking skills. Explore a real-world application that requires networking when used with an environmental monitoring system. Why would such a system be important? Here's one reason: A friend went out of town for a few weeks. While he was away, he called and asked me to pick something up at his house to mail it to him. When at his house, I realized the heat had shut off and the pipes had burst — not a pretty picture. If a temperature monitoring system had been in place, the damage could have been averted. This article examines the roles Android can play in such a monitoring system.


Android networking capabilities

Android is based on the Linux® kernel and contains a healthy array of networking capabilities. If you have not installed the Android SDK, you might want to download it so you can follow along with the examples.

Table 1 shows some networking-related packages in the Android SDK.

Table 1. Android SDK networking packages
PackageDescription
java.netProvides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. This is the multipurpose networking resource. Experienced Java developers can create applications right away with this familiar package.
java.ioThough not explicitly networking, it's very important. Classes in this package are used by sockets and connections provided in other Java packages. They're also used for interacting with local files (a frequent occurrence when interacting with the network).
java.nioContains classes that represent buffers of specific data types. Handy for network communications between two Java language-based end points.
org.apache.*Represents a number of packages that provide fine control and functions for HTTP communications. You might recognize Apache as the popular open source Web server.
android.netContains additional network access sockets beyond the core java.net.* classes. This package includes the URI class, which is used frequently in Android application development beyond traditional networking.
android.net.httpContains classes for manipulating SSL certificates.
android.net.wifiContains classes for managing all aspects of WiFi (802.11 wireless Ethernet) on the Android platform. Not all devices are equipped with WiFi capability, particularly as Android makes headway in the "flip-phone" strata of cell phones from manufacturers like Motorola and LG.
android.telephony.gsmContains classes required for managing and sending SMS (text) messages. Over time, an additional package will likely be introduced to provide similar functions on non-GSM networks, such as CDMA, or something like android.telephony.cdma.

The list above is not exhaustive, but is meant to give you a high-level awareness of what the platform is capable of. The next section explores a few simple networking examples.


Simple networking example

To demonstrate just how easy it is to connect Android to a network, the example will show how to pull text from a Web page. Download the source code for the example. Figure 1 demonstrates the application in action.

Figure 1. Fetching text from a Web page
Fetching text from a Web page

This section provides the code necessary to build the example application. We'll first look at the UI aspects, then cover networking-related code.

There are three UI elements:

  • EditText lets the user enter a Web page (http://developer.android.com is shown in Figure 1 and Listing 2).
  • A button is used to tell the program to fetch the Web page text.
  • Once the data is received, it is shown in a TextView.

Listing 1 shows the file main.xml, which is the complete UI layout for this application.

Listing 1. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<EditText 
android:layout_height="wrap_content"
android:id="@+id/address"
android:layout_width="fill_parent"
android:text="http://google.com"
>
</EditText>
<Button
 android:id="@+id/ButtonGo" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"
 android:text="go!"
 >
</Button>
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#ffffff"
    android:textColor="#000000"
	android:id="@+id/pagetext"
    />
</LinearLayout>

Listing 2 shows the Java code used by this example.

Listing 2. GetWebPage.java
package com.msi.getwebpage;

import android.app.Activity;
import android.os.Bundle;
// used for interacting with user interface
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
// used for passing data 
import android.os.Handler;
import android.os.Message;
// used for connectivity
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class GetWebPage extends Activity {
    /** Called when the activity is first created. */

    Handler h;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final EditText eText = (EditText) findViewById(R.id.address);
        final TextView tView = (TextView) findViewById(R.id.pagetext);
        
        this.h = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // process incoming messages here
                switch (msg.what) {
                    case 0:
                    	tView.append((String) msg.obj);
                    	break;
                }
                super.handleMessage(msg);
            }
        };
        final Button button = (Button) findViewById(R.id.ButtonGo);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
            	try	{
            		tView.setText("");
                // Perform action on click
                	URL url = new URL(eText.getText().toString());
                    URLConnection conn = url.openConnection();
                    // Get the response
                    BufferedReader rd = new BufferedReader(new 
InputStreamReader(conn.getInputStream()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                		Message lmsg;
                        lmsg = new Message();
                        lmsg.obj = line;
                        lmsg.what = 0;
                        GetWebPage.this.h.sendMessage(lmsg);
                    }
            	}
            	catch (Exception e)	{
            	}
            }
        });        
    }
}

The code can be broken down into a few general areas. There are several important (required) import statements to properly reference the UI, data passing, and networking-related classes in use in the application. All of the networking-related code takes place within the OnClick method of the OnClickListener. It is invoked when the button, labeled go! in Figure 1, is selected.

The URL and URLConnection classes team up to provide the actual connectivity to a Web site of the user's choosing. An instance of a BufferedReader takes care of reading data coming in from the Web-site connection. As each line is read, the text is appended to a TextView. The data is not simply assigned to the TextView directly (though it could be in this example). We've introduced the design pattern of creating a message object and passing that object to an instance of a handler. This is the preferred means of updating a UI, particularly in a real application where multiple threads may be running concurrently.

In the example, the Android application is communicating with an HTTP Web server, such as Apache or Internet Information Server (IIS on a Microsoft® server). If the application was talking directly to a TCP socket, instead of HTTP, you would implement the application differently. Listing 3 is a code snippet showing another means of interacting with a remote server. The listing is implemented as a separate thread.

Listing 3. Daytime client
    public class Requester extends Thread {
        Socket requestSocket;
        String message;
        StringBuilder returnStringBuffer = new StringBuilder();
        Message lmsg;
        int ch;
        @Override
        public void run() {
            try {
                this.requestSocket = new Socket("remote.servername.com", 13);
                InputStreamReader isr = new InputStreamReader(this.requestSocket.
getInputStream(), "ISO-8859-1");
                while ((this.ch = isr.read()) != -1) {
                    this.returnStringBuffer.append((char) this.ch);
                }
                this.message = this.returnStringBuffer.toString();
                this.lmsg = new Message();
                this.lmsg.obj = this.message;
                this.lmsg.what = 0;
                h.sendMessage(this.lmsg);
                this.requestSocket.close();
            } catch (Exception ee) {
                Log.d("sample application", "failed to read data" + ee.getMessage());
            }
        }
    }

Like the previous example, the code above uses the message and handler approach to send data back to the caller updating the UI and subsequent processing. Unlike the code in Listing 1, this example is not communicating with an HTTP server, so you don't employ the URLConnection class. Instead, using the lower-level Socket class opens a stream-based socket connection to a remote server at port 13. Port 13 is the classic "Daytime Server" application.

The Daytime Server accepts an incoming socket connection and sends the date and time in a textual format back to the calling socket. Once the data has been sent, the socket is closed by the server. The example also demonstrates use of an InputStreamReader and a specific character encoding.

Sending a text message is another task you might want to do with Android. Listing 4 shows an example.

Listing 4. Send a text message
void sendMessage(String recipient,String myMessage) {
 SmsManager sm = SmsManager.getDefault();
 sm.sendTextMessage("destination number",null,"hello there",null,null);
}

Sending a text message is straightforward. First, obtain a reference to the SmsManager using the static method getDefault(). Then invoke the sendTextMessage method. The arguments:

Recipient cell-phone number
Include area code.
Service center phone number
Using null means that you are satisfied with using the default service center for processing the message. In all but the most novel of applications, use null for this parameter.
Your payload
Keep the message length fewer than 160 bytes, unless you are OK with the data being split up across multiple messages.
Pending intent
An optional intent to be started when the message is sent or an error occurs. It's OK to pass a value of null for this parameter if this notification is not needed. (See Resources for more information about intents and Android fundamentals.)
Delivery intent
An optional Intent to be started when delivery confirmation is received. It's OK to pass a value of null for this parameter if delivery notification is not important.

Whether connecting to a Web page or a custom TCP application, the Android platform is ready and able to assist. As shown in Listing 4, sending a text message is easy. By using the optional intent parameters, you can even take action once the message has been sent and then subsequently delivered. This is a powerful feature not available on all mobile platforms.

The next section takes a quick look at a real-world application design.


Survey of the environmental monitoring system

For this scenario, let's assume you're the property manager for several office condos where your business resides. Managing property is not much different from managing a data center — long stretches of boredom interrupted by acute opportunities for excitement. Just the other day, you had to oversee a clean-up operation after a 10-year-old water heater leaked all over a storage closet full of old PCs and training manuals. Fortunately, you were in town. If you had been traveling, the situation would have been really ugly. This mishap, and others like it, inspired the idea to explore using Android to assist in monitoring the condition of the property. Figure 2 is a high-level block diagram of such a system.

Figure 2. High-level block diagram of monitoring system
High-level block diagram of monitoring system

The architecture is a traditional approach using a microcontroller to interact with some simple sensors to collect data. Data is then sent to a controller with a serial communications protocol, such as RS232 or RS485. The controller would likely be a PC or similar machine. This data can then be accessed over the Internet through a firewall. The protocol used between the Android phone (such as a TMobile G1) could be either HTTP or a proprietary scheme.

The data sent between the controller and the Android-equipped device would be basic bytes representing:

  • The presence of water
  • The current temperature
  • How much power is being consumed
  • Perhaps some general-purpose analog and digital values

Why would you care about power consumed? One reason might simply be that someone left the lights on and it's raising the electric bill. A second reason could be a bit more problematic: Let's say you have a large freezer and the power has gone out. That could be a messy and costly situation to cope with. Or, perhaps the circuit breaker on your air conditioning unit has tripped and your computer room is no longer cooling.

The basic design looks workable. In terms of using Android, you could replace Android in Figure 2 with just about any mobile platform. But what if you replace the microcontroller with an Android-equipped appliance? The next section discusses extending the application and what features are enabled by bringing Android more prominently into the picture.


Extending the application

The first architecture in this article centered around a microcontroller. Microcontrollers come in all shapes and sizes, from 6 pin "10F" parts from Microchip up to 32-bit monsters with loads of peripherals, pins, and code space. What if you put Android into the appliance instead of a traditional microcontroller? For some applications, this might be a nonstarter due to cost, but entertain the possibilities of this approach as you contemplate Figure 3.

Figure 3. Possible architecture of Android in an appliance
Possible architecture of Android in an appliance

Deploying Android to the embedded side of the picture lets you work with a richer programming environment. You can continue to monitor the same moisture, temperature, and power-consumption characteristics, but now you could also look at recording audio, video, and vibration. You could have a mini-alarm, access-control system, and an environmental monitoring tool. Because Android is so network-ready, you can do without the controller personal computer and talk directly to the network.

This approach also provides additional benefits for updating the software in the field. Assume you want to add a new feature to the monitoring software (or even fix a bug). With the traditional microcontroller approach, that task can be cumbersome at best and downright expensive or impossible at worst. With Android, you have a cleaner deployment model with much more flexibility.

Android is running primarily on mobile phones today, but it has been ported to NetBooks and other platforms. Hopefully this article has given you some food for thought. I've got to go and get my system running. You never know when another water heater is going to leak.


Summary

In this article, you learned about Android networking in general. You walked through a few samples of applications you could create, including interacting with a Web server and sending a text message. You saw how Android could be connected to a real-world environmental monitoring system. With code examples, you learned about opportunities for extending Android into some atypical applications, such as an embedded controller.

Stay tuned for my next article, which will explore how to build a baby monitoring system using an Android-based phone.


Download

DescriptionNameSize
GetWebPage source codeos-android-networking_GetWebPage.zip14KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=394157
ArticleTitle=Networking with Android
publish-date=06092009