Getting Started With Android - Author: Matthew Davis Date: 07 ...

fansbutterflyMobile - Wireless

Jul 19, 2012 (5 years and 3 months ago)

305 views

Getting Started With Android
Author: Matthew Davis
Date: 07/25/2010
Environment:
Ubuntu 10.04 Lucid Lynx
Eclipse 3.5.2
Android Development Tools(ADT) 0.9.7
HTC Incredible (Android 2.1)
Preface
This guide is intended to introduce you, the reader, to the basic API of the Android OS. This
manual is by no means exhaustive and provides a “macro” view of the Android components in most
cases. This guide is an offering of what tools and options are available to you as a programmer, as well
as an example of several of the concepts and tools presented here. I highly suggest visiting Lars Vogel's
tutorial at
Voquella
and the Google's own tutorials at
Google Tutorials
.
I. Getting Started
To get started with Android using Eclipse and the ADT, you will need to download the Android
SDK(2.2), the Eclipse IDE(3.5.2), and the ADT plugin(0.9.7). All version numbers are current as of
this writing. The installation procedures mentioned are current for Ubuntu 10.04. For other OS
implementations, I have included some additional instructions. However, please see the Google
Android Development Site at the
Android Homepage
.
System Requirements:
Supported Operating Systems
• Windows XP (32-bit) or Vista (32- or 64-bit)
• Mac OS X 10.5.8 or later (x86 only)
• Linux (tested on Linux Ubuntu Hardy Heron)
• 64-bit distributions must be capable of running 32-bit applications. For information
about how to add support for 32-bit applications, see the
Ubuntu Linux installation
notes
.
Supported Development Environments
Eclipse IDE
• Eclipse 3.4 (Ganymede) or 3.5 (Galileo)
Caution: There are known issues with the ADT plugin running with Eclipse 3.6. Please stay on
3.5 until further notice.
• Eclipse
JDT
plugin (included in most Eclipse IDE packages)
• If you need to install or update Eclipse, you can download it from
http://www.eclipse.org/downloads/
.
Several types of Eclipse packages are available for each platform. For developing Android
applications, we recommend that you install one of these packages:
• Eclipse IDE for Java EE Developers
• Eclipse IDE for Java Developers
• Eclipse for RCP/Plug-in Developers
• Eclipse Classic (versions 3.5.1 and higher)

JDK 5 or JDK 6
(JRE alone is not sufficient)

Android Development Tools plugin
(optional) REQUIREMENT FOR THIS MANUAL
• Not compatible with Gnu Compiler for Java (gcj)
Other development environments or IDEs

JDK 5 or JDK 6
(JRE alone is not sufficient)

Apache Ant
1.6.5 or later for Linux and Mac, 1.7 or later for Windows
• Not compatible with Gnu Compiler for Java (gcj)
Note: If JDK is already installed on your development computer, please take a moment to make sure
that it meets the version requirements listed above. In particular, note that some Linux distributions
may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android
development.
Hardware requirements
The Android SDK requires disk storage for all of the components that you choose to install. The table
below provides a rough idea of the disk-space requirements to expect, based on the components that
you plan to use.
Component type Approximate size Comments
SDK Tools 50 MB Required.
Android platform (each) 150 MB At least one platform is required.
SDK Add-on (each) 100 MB Optional.
USB Driver for Windows 10 MB Optional. For Windows only.
Samples (per platform) 10M Optional.
Offline documentation 250 MB Optional.
Note that the disk-space requirements above are in addition to those of the Eclipse IDE, JDK, or other
prerequisite tools that you may need to install on your development computer.
Eclipse:
Eclipse
Android SDK 2.2:
SDK Download
After downloading, unpack the Android SDK archive to a safe location on your machine. By
default, the SDK files are unpacked into a directory named android-sdk-<machine-
platform>. Make a note of the name and location of the unpacked SDK directory on your system —
you will need to refer to the SDK directory later, when setting up the ADT plugin or when using the
SDK tools.
Android Development Tools
1.Start Eclipse, then select Help > Install New Software.
2.In the Available Software dialog, click Add....
3.In the Add Site dialog that appears, enter a name for the remote site (for example, "Android
Plugin") in the "Name" field.
In the "Location" field, enter this URL:
https://dl-ssl.google.com/android/eclipse/
Note: If you have trouble acquiring the plugin, you can try using "http" in the URL, instead of
"https" (https is preferred for security reasons).
Click OK.
4.Back in the Available Software view, you should now see "Developer Tools" added to the list.
Select the checkbox next to Developer Tools, which will automatically select the nested tools
Android DDMS and Android Development Tools. Click Next.
5.In the resulting Install Details dialog, the Android DDMS and Android Development Tools
features are listed. Click Next to read and accept the license agreement and install any
dependencies, then click Finish.
6.Restart Eclipse.
Updating the ADT (when necessary)
1.Select Help > Check For Updates
2.In the resulting Available Updates dialog, locate the Android DDMS and Android Development
Tools features in the list and ensure that the checkboxes next to them are selected. Click Next.
If the Available Updates dialog does not list Android DDMS and Android Development tools,
make sure that you have set up a remote update site for them, as described in
Installing the ADT
Plugin
.
3.In the Update Details dialog, click Next.
4.Read and accept the license agreement and then click Finish. This will download and install the
latest version of Android DDMS and Android Development Tools.
5.Restart Eclipse.
Install a Platform
You need to install at least one Android platform in your SDK environment. If you have not already
performed this step, you need to do it now.
To install a platform in Eclipse:
1.In the Android SDK and AVD Manager, choose Available Packages in the left panel. This is the
button in the top left tool bar with a little Android on it.
2.Click the repository site checkbox to display the components available for installation.
3.Select at least one platform to install, and click Install Selected. If you aren't sure which
platform to install, use the latest version.
Continuing Setup
Ok, you still with me? Good. You now have a complete environment with which to develop
Android applications. There are still a few items we need to address, the AVD and Developing on a
Device. The Android SDK allows for the creation of AVDs or Android Virtual Machines. You may, of
course, decide to develop on a actual device, but the AVD allows for flexibility of screen size, phone
options, release version, GPS, etc. It is important to not only develop and test on your platform, but
also to develop and test on different platforms through the AVD to ensure product compatibility. Lets
look at setting up our AVD.
Android Virtual Device
To learn more about how to use AVDs and the options available to you, refer to the
Android Virtual
Devices
document.
In this tutorial, you will run your application in the Android Emulator. Before you can launch the
emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and
device settings used by the emulator.
To create an AVD:
1.In Eclipse, choose Window > Android SDK and AVD Manager.
2.Select Virtual Devices in the left panel.
3.Click New.
The Create New AVD dialog appears.
4.Type the name of the AVD, such as "my_avd".
5.Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.1)
you want to run on the emulator.
You can ignore the rest of the fields for now.
6.Click Create AVD.
This will create an Android Virtual Device for you to test your applications upon.
II. Your First Application
At this point, I would recommend following the excellent Hello World tutorial located at the
Android Homepage
. This will give you your first look at creating a new Eclipse Android Project, show
you how to introduce your first UI both programmatically and through XML, and using an AVD. You
should note that the preferred method of implementing a UI in Android is through XML rather than the
Java source code. Pay close attention to how the UI is implemented in this fashion. After completing
this tutorial we'll start looking at some of the components of the Android API.
Basic Widgets
From the Hello World tutorial you will have seen how a UI is constructed utilizing XML. I have
compiled a list of the basic widgets available for use in the Android UI. All of these widgets have a
number of attributes that can be applied to them, such as textStyle, textColor, typeface, etc. You can
also name each these items for use elsewhere as you saw in the Hello World tutorial.
• TextView: the basic text label
• EditView: an editable box for user input
• Button: as it says, a button that can be clicked. Allows use of the ever popular
OnClickListener!
• ImageView: displays the selected picture
• ImageButton: displays an image which acts also as a button
• CheckBox: just what it says, a check box that can listen for changes
• RadioGroup/RadioButton: A radio button group that allows one item to be selected. The
RadioGroup can contain multiple RadioButtons
Here is an example taken from
Vogella's Tutorial
using some of the items mentioned here. Don't worry
about LinearLayout tags, we'll be there in a second. The wrap_content and fill_parent tags you see here
are merely formatting and are very common for each of these items. They mean exactly what they say,
with wrap_content allocating just enough space for its contents and fill_parent filling the parent
container (LinearLayout, TableLayout, etc as we will see).
<?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:text="@+id/EditText01"
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<RadioGroup android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton android:text="@+id/RadioButton01"
android:id="@+id/RadioButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
<RadioButton
android:text="@+id/RadioButton02"
android:id="@+id/RadioButton02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
</RadioGroup>
<Button android:text="@+id/Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>

Layouts
Layouts are the containers that hold your widgets. Containers may be nested within each other, such as
as a TableLayout inside of a LinearLayout. Here are the layout available to you in your UI. As
mentioned before, you can use fill_parent and wrap_content to display your widgets or you may define
a custom width and height in pixels. NOTE: LinearLayout REQUIRES the layout_width and
layout_height attributes in the widgets inside of it, as well as the ORIENTATION attribute for
the linear container.
• Widgets may also have weight, gravity, and padding attributes to alter their appearance.
• LinearLayout: Just as it says, a linear layout with all items justified top and to the left.
• RelativeLayout: This layout places widgets in relation to the other widgets and requires specific
attributes for each widget to determine their position.
• TableLayout: Just as it says, this layout allows to place widgets in rows and columns(cells) with
attributes specific to this layout.
• ScrollView: This layout usually nests another interior layout and allows the contents to be
scrolled.

Selection Widgets
In addition to the basic widgets mentioned previously, there are several fun types of selection
widgets that allow the use of spinning wheels, lists, and grids to display your UI. Here is a brief
rundown of the most popular.
• ListView: Instead of having a TextView in your XML file for a long list of Strings, you can
define one TextView as a placeholder/template and display a defined String array using that
template. We'll see this in the main project demo later.
• Spinner: This is the equivalent of the drop down menu box so common in Java and webpages.
• GridView: similar to the ListView, but displays the UI in a user-defined grid on the screen.
These widget allow for greater flexibility in displaying your UI, as well as consolidating large
quantities of data into the smaller canvas of the mobile phone screen. Viewing area on mobile phones is
at a premium, so ensuring the most important portions of your UI are available on one screen (without
having to scroll) is very important.
Android Manifest
You may have noticed in your Eclipse file tree an entry for the Android Manifest. The Manifest
is the overall structure of your program. It contains details such as the permissions required for your
program to operate, the icon that should appear in the app drawer for your program, the name of your
program, which activity is the Main activity, etc. It is important to note that any program that requires
access to the user's personal data(location, contacts, etc.) will require you to enter those permissions
into the Manifest. The user will then be asked upon app start if they would like to allow the program to
access these elements.
As mentioned in the preface, the Eclipse Android Interface allows you to edit the Manifest
through an abstraction layer rather than the raw XML. In this case, I highly recommend using it to edit
the Manifest. The Manifest is much more complex than any layouts or data XML files you might have
created earlier and the abstraction layer allows for easier and faster editing of these items.
Intents and Activities
Activities are the discrete components of your Android application. They are very similar to the
object-oriented programming methods you've already learned. For example, say you have a activity
that allows for a few options, saw “View Calendar” or “Calculate Data”. So what happens when your
user selects one of those options? It should perform the specified action, right? But how do we get
there? Intents are the answer.
Say your user selects “View Calendar”. Your activity should contain code to create and intent
and package up any relevant data to send to that activity. Wait, you might say, I don't have a calendar
coded! Thats ok, Android has its own calendar app and can respond to your intents just as any activity
you coded personally. Through intents, you can access many of the built-in apps that come packaged
with Android OS. We'll see this soon in the example project.
So say they select “Calculate Data” from your UI. And let's say you have another activity that
takes the user input and graphs a point on a grid you designed yourself. You can (and should) create a
new activity that processes this data and displays the appropriate point. You can send this data and start
your activity through an Intent.
Suffice it to say that large apps that contain several different functionalities should be devolved into
separate activities that communicate with one another through Intents. This is a method of streamlining
your program and utilizing OO best practices.
Example Project
The Monuments program. This program displays a ListView with several wonders of the world
listed on the UI. Upon selection of one of the wonders, the user will see a briefly displayed name as
well as be taken to the Maps application where they can view the wonder. I have places several
comments in each file to show you exactly whats going on and how it all works.
Monuments.java
package
monuments.davisworks.com;
import
android.app.Activity
;
import
android.app.ListActivity;
import
android.content.Intent;
import
android.net.Uri;
import
android.os.Bundle;
import
android.widget.ArrayAdapter;
import
android.widget.ListView;
import
android.widget.TextView;
import
android.widget.Toast;
import
android.view.View;
public

class
Monuments
extends
ListActivity {

/** Called when the activity is first created. */

@Override

public

void
onCreate(Bundle savedInstanceState) {

super
.onCreate(savedInstanceState);


//set the String array from the XML array
String[] monuments_name =
getResources().getStringArray(R.array.
monument_array
);



//set the array to the ListAdapter
setListAdapter(
new
ArrayAdapter<String>(
this
, R.layout.
list_item
,
monuments_name));


//create the ListView
ListView mView = getListView();
mView.setTextFilterEnabled(
true
);

}


//create the code to perform an action when one of the buttons is pressed


public

void
onListItemClick(ListView parent, View v,
int
position,
long
id) {

//create a short visible message (Toast) upon selection
Toast.makeText(getApplicationContext(), ((TextView) v).getText(),
Toast.
LENGTH_SHORT
).show();


//create the URI to hold the data needed by the Map application
Uri uri =
null
;


//get the name of the item selected
String _text = (String) (((TextView) v).getText());


//load the XML array into a String array for comparison purposes
String[] latlon = getResources().getStringArray(R.array.
latlon_array
);


if
(_text.equals(
"Pyramid of Giza"
)) {
uri=Uri.parse(
"geo:"
+latlon[0]);
}
else

if
(_text.equals(
"Stonehenge"
)) {
uri=Uri.parse(
"geo:"
+latlon[1]);
}
else

if
(_text.equals(
"Taj Mahal"
)) {
uri=Uri.parse(
"geo:"
+latlon[2]);
}
else

if
(_text.equals(
"Eiffel Tower"
)) {
uri=Uri.parse(
"geo:"
+latlon[3]);
}
else

if
(_text.equals(
"Big Ben"
)) {
uri=Uri.parse(
"geo:"
+latlon[4]);
}
else

if
(_text.equals(
"Statue of Liberty"
)) {
uri=Uri.parse(
"geo:"
+latlon[5]);
}
else

if
(_text.equals(
"Christ the Redeemer"
)) {
uri=Uri.parse(
"geo:"
+latlon[6]);
}
else

if
(_text.equals(
"Empire State Building"
)) {
uri=Uri.parse(
"geo:"
+latlon[7]);
}


//now start the Activity with the data generated
startActivity(
new
Intent(Intent.
ACTION_VIEW
, uri));
}}
Ok, here we go. The activity is created (onCreate), we create the String array populated with the data in
the XML file (shown next), we set the list adapter with this data and create the list. We then create the
event handler onListItemClick and show the code to be executed upon selection. As you can see we
create a brief popup box (a Toast) to appear for a short time with the name of the text selected, then
reference an array of values with which it is to be compared. Upon the comparion we set the URI
(uniform resource) with the “geo:” prefix which is required by the maps application. We then send that
URI to the maps application (this is automatic, as Android can easily decipher which app this data must
be sent, plus we didn't specify so Android handles it). And voila! The maps application is given the
focus and the requested latitude and longitude appears on the screen.
strings.xml
<?
xml

version
=
"1.0"

encoding
=
"utf-8"
?>
<
resources
>

<
string

name
=
"app_name"
>
Monuments
</
string
>

<
string

name
=
"title"
>
Welcome to Monuments!
</
string
>
<
string-array

name
=
"monument_array"
>
<
item
>
Pyramid of Giza
</
item
>
<
item
>
Stonehenge
</
item
>
<
item
>
Taj
Mahal
</
item
>
<
item
>
Eiffel
Tower
</
item
>
<
item
>
Big Ben
</
item
>
<
item
>
Statue of Liberty
</
item
>
<
item
>
Christ
the Redeemer
</
item
>
<
item
>
Empire State Building
</
item
>
</
string-array
>
<
string-array

name
=
"latlon_array"
>
<
item
>
29.979175,31.134358
</
item
>
<
item
>
51.178844,-1.826189
</
item
>
<
item
>
27.174167,78.042222
</
item
>
<
item
>
48.8583,2.2945
</
item
>
<
item
>
51.500611,-0.124611
</
item
>
<
item
>
40.689167,-74.044444
</
item
>
<
item
>
-22.951667,-43.210833
</
item
>
<
item
>
40.748433,-73.985656
</
item
>
</
string-array
>
</
resources
>
This resource file contains all the data needed to populate the arrays in the code, as well as the app
name and title. You can see how the naming scheme allows you to populate coded arrays from XML
data. The latlon array contains the coordinates of each of the wonders in decimal format.
list_item.xml
<?
xml

version
=
"1.0"

encoding
=
"utf-8"
?>
<
TextView

xmlns:android
=
"http://schemas.android.com/apk/res/android"

android:layout_width
=
"fill_parent"

android:layout_height
=
"fill_parent"

android:padding
=
"10dp"

android:textSize
=
"16sp"

>
</
TextView
>
This is the template for the list. As you can see, each one of the array members in the list will be
populated into a TextView that fills the parent in both height and width, has 10dp in padding and has a
text size of 16sp.