Hello World Android Style

With our development set up, we can now finally create our first Android project in Eclipse. The ADT plug-in installed a couple of wizards for us to make the creation of new Android projects really easy.

Creating the Project

There are two ways to create a new Android project. The first one works by right-clicking in the Package Explorer view (see Figure 2-4) and selecting New > Project... from the pop-up menu. In the new dialog, select Android Project under the Android category. As you can see, there are a lot of other options for project creation in that dialog. This is the standard way to create a new project of any type in Eclipse. After confirming the dialog, the Android project wizard will open.

The second way is a lot easier: just click the button responsible for creating a new Android project (shown earlier in Figure 2-4).

Once you are in the Android project wizard dialog, you have to make a few choices.

1. First, you must define the project name. A usual convention is to keep it all lowercase. For this example, name the project "hello world."

2. Next, you have to specify the build target. For now, simply select the Android 1.5 build target, since this is the lowest common denominator and you don't need any fancy features like multitouch yet.

NOTE: In Chapter 1 you saw that each new release of Android adds new classes to the Android framework API. The build target specifies which version of this API you want to use in your application. For example, if you choose the Android 2.3 build target, you get access to the latest and greatest API features. This comes at a risk, though: if your application is run on a device that uses a lower API version (say, a device running Android version 1.5), then your application will crash if you access API features that are only available in version 2.3. In this case, you'd need to detect the supported SDK version during runtime and only access the 2.3 features when you're sure that the Android version on the device supports it. This may sound pretty nasty, but as you'll see in Chapter 5, given a good application architecture you can easily enable and disable certain version-specific features without running the risk of crashing.

3. Next, you have to specify the name of your application (e.g., Hello World), the name of the Java package in which all your source files will eventually be located (e.g., com.helloworld), and an activity name. An activity is similar to a window or dialog on a desktop operating system. Let's just name it HelloWorldActivity.

4. The Min SDK Version field allows you to specify what minimum Android version your application requires to run. This parameter is not required, but it's good practice to specify it. SDK versions are numbered starting from 1 (1.0) and increase with each release. Since 1.5 is the third release, specify 3 here. Remember that you had to specify a build target previously, which might be newer than the minimum SDK version. This allows you to work with a higher API level, but also deploy to older versions of Android (making sure that you only call the supported API methods for that version, of course).

5. Click Finish to create your first Android project.

NOTE: Setting the minimum SDK version has some implications. The application can only be run on devices with an Android version equal to or greater than the minimum SDK version you specify. When a user browses the Android Market via the Market application, only applications with a fitting minimum SDK version will be shown to her.

Exploring the Project

In the Package Explorer, you should now see a project called "hello world." If you expand it and all its children, you'll see something like Figure 2-6. This is the general structure of most Android projects. Let's explore it a little bit.

AndroidManifest.xml describes your application. It defines what activities and services it is composed of, what minimum and target Android version it is supposed to run on, and what permissions it needs (e.g., access to the SD card or networking).

■ default.properties holds various settings for the build system. We won't touch this, as the ADT plug-in will take care of modifying it when necessary.

■ src/ contains all your Java source files. Notice that the package has the same name as the one you specified in the Android project wizard.

■ gen/ contains Java source files generated by the Android build system. You shouldn't mess with them, as they get regenerated automatically in some cases.

■ assets/ is where you store file our application needs (e.g., configuration files or audio files and the like). These files get packaged with your Android application.

■ res/ holds resources your application needs, such as icons, strings for internationalization, and UI layouts defined via XML. Like assets, they also get packaged with your application.

■ Android 1.5 tells us that we are building against an Android version 1.5 target. This is actually a dependency in the form of a standard JAR file that holds the classes of the Android 1.5 API.

The Package Explorer view hides another directory, called bin/, which holds the compiled code that is ready for deployment to a device or emulator. As with the gen/ folder, we usually don't care what happens in this folder.

Package Explorer

IS 2l H elloWorldActivity. ¡ava gen [Generated Java Files:] S-{0 corn, hello world ffl-g) R.java Android 1.5

B' & drawable

; icon.png

B & layout

[Xj rnain.xrnl

B"& values

[xj strings, xml

[Oj AndroidManifest.xrnI Qj default, properties

Figure 2-6. Hello World project structure

We can easily add new source files, folders, and other resources in the Package Explorer view by right-clicking the folder we want to put the new resources in, and selecting New plus the corresponding resource type we want to create. For now, though, we'll leave everything as is. Next, let's modify the source code a little.

Writing the Application Code

We still haven't written a single line of code, so let's change that. The Android project wizard created a template activity class for us called HelloWorldActivity, which will get displayed when we run the application on the emulator or a device. Open the source of the class by double-clicking the file in the Package Explorer view. We'll replace that template code with the code in Listing 2-1.

Listing 2-1. HelloWorldActivity.java package com.helloworld;

import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button;

public class HelloWorldActivity extends Activity implements View.OnClickListener {

Button button; int touchCount;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); button = new Button(this); button.setText( "Touch me!" ); button.setOnClickListener(this); setContentView(button);

public void onClick(View v) { touchCount++;

button.setText("Touched me " + touchCount + " time(s)");

Let's dissect Listing 2-1 so you can understand what it's doing. We'll leave the nitty-gritty details for later chapters. All we want is to get a sense of what's happening here.

The source code file starts off with the standard Java package declaration and a couple of imports. Most Android framework classes are located in the android package.

package com.helloworld;

import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button;

Next, we define our HelloWorldActivity and let it extend the base class Activity, which is provided by the Android framework API. An Activity is a lot like a window in classical desktop Uls, with the constraint that it always fills the complete screen (except for the notification bar at the top of the Android Ul). Additionally, we let it implement the interface OnClickListener. If you have experience with other Ul toolkits, you'll probably see what's coming next. More on that in a second.

public class HelloWorldActivity extends Activity implements View.OnClickListener {

We let our Activity have two members: a Button and an integer that counts how often the Button was clicked.

Button button; int touchCount;

Every Activity must implement the abstract method Activity.onCreate(), which gets called once by the Android system when the activity is first started. This replaces a constructor you'd normally expect to use to create an instance of a class. It is mandatory to call the base class onCreate() method as the first statement in the method body.

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

Next, we create a Button and set its initial text. Button is one of the many widgets that the Android framework API provides. Widgets are synonymous with so called Views on Android. Note that button is a member of our HelloWorldActivity class. We'll need a reference to it later on.

button = new Button(this); button.setText( "Touch me!" );

The next line in onCreate() sets the OnClickListener of the Button. OnClickListener is a callback interface with a single method, OnClickListener.onClick(), that gets called when the Button is clicked. We want to be notified of clicks, so we let our HelloWorldActivity implement that interface and register it as the OnClickListener of the Button.

button.setOnClickListener(this);

The last line in the onCreate() method sets the Button as the so-called content View of our Activity. Views can be nested, and the content View of the Activity is the root of this hierarchy. In our case, we simply set the Button as the View to be displayed by the Activity. For simplicity's sake, we won't get into details on how the Activity will be laid out given this content View.

setContentView(button);

The next step is simply the implementation of the OnClickListener.onClick() method, which the interface requires of our Activity. This method gets called each time the Button is clicked. In it we increase the touchCount counter and set the Button's text to a new string.

public void onClick(View v) { touchCount++;

button.setText("Touched me" + touchCount + "times");

So, to summarize our Hello World application, we construct an Activity with a Button. Each time the Button is clicked, we reflect this by setting its text accordingly. (This may not be the most exciting application on the planet, but it will do for further demonstration purposes.)

Note that we never had to manually compile anything. The ADT plug-in together with Eclipse will recompile the project every time we add, modify, or delete a source file or resource. The result of this compilation process is an APK file that is ready to be deployed to the emulator or an Android device. The APK file is located in the bin/ folder of the project.

You'll use this application in the following sections to learn how to run and debug Android applications on emulator instances as well as devices.

0 0

Post a comment