Hello World, Android Style

With our development set up, we can now create our first Android project in Eclipse. The ADT plug-in installed several wizards that make creating new Android projects very 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 then selecting New images Project… from the pop-up menu. In the new dialog, select Android Project under the Android category. As you can see, there are many other options for project creation in that dialog. This is the standard way to create a new project of any type in Eclipse. After you confirm 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 decisions.

  1. First, you must define the project name. The usual convention is to keep the name 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 3.1 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 available only in version 3.1. In this case, you'd need to detect the supported SDK version during runtime and access only the 3.1 features when you're sure that the Android version on the device supports this version. 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 (for example, Hello World), the name of the Java package in which all your source files will be located eventually (such as com.helloworld), and an activity name. An activity is similar to a window or dialog on a desktop operating system. Let's just name the activity HelloWorldActivity.
  4. The Min SDK Version field allows you to specify the 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 call only 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 be run only 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 the appropriate minimum SDK version will be displayed.

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 comprise your application, what minimum and target Android version your application runs on (hypothetically), and what permissions it needs (for example, access to the SD card or networking).
  • default.properties holds various settings for the build system. We won't touch upon 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 modify them as, in some cases, they get regenerated automatically.
  • assets/ is where you store file your application needs (such as configuration files, 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, the resources 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 ready for deployment to a device or emulator. As with the gen/ folder, we usually don't care what happens in this folder.

images

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 in which we want to put the new resources 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.

The source code file starts with the standard Java package declaration and several 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 UIs, with the constraint that the Activity always fills the complete screen (except for the notification bar at the top of the Android UI). Additionally, we let the Activity implement the interface OnClickListener. If you have experience with other UI toolkits, you'll probably see what's coming next. More on that in a second.

public class HelloWorldActivity extends Activity
                                implementsView.OnClickListener {

We let our Activity have two members: a Button and an integer that counts how often the Button is 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(), which 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 of 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 this method, 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");
   }

Thus, 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 compile anything manually. 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 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset