Lab creating a First Android Project



Download 119.6 Kb.
Date20.06.2017
Size119.6 Kb.
#21148
LAB Creating a First Android Project

In this lab, you will create a first Android project to display the same Hello World message that you displayed before. Before completing this lab, you must have Eclipse and the Android SDKs installed. This software is installed in the COBA labs.


Abstract


In this lab, you will perform the following tasks:

  • Review the XML language as it is used to implement nearly all layout and other configuration files

  • Understand Android SDK versioning

  • Create a first Android application with a single activity

  • Explore the files that make up an Android application

  • Compile the application

  • Configure and run an Android emulator

  • Run the Android application

Key Terms


  • An activity represents a thing that the user can do. Conceptually, think of an activity as a Visual Basic form, and its code behind (VB) file. An activity has a Java code file and one or more layout files that defines the visual interface for the activity.


  • The eXtensible Markup Language (XML) is used to describe data. It is used extensively by Android configuration, resource, and layout files.


  • A layout depicts the visual interface for an activity. An activity might have many layouts to support different screen resolutions, sizes, or orientations.


  • One purpose of an intent is to start activities. An intent is a messaging object used start activities, service, or deliver broadcasts. Data is also passed from one activity to another via an intent.


  • A resource describes data that is used by an applications. Resources include strings and other data. Resources are stored as XML files.


  • If it’s visible on the screen, it’s a view. Each of an activity’s layouts is a view. Widgets are views. Dialogs are also views. A view is a rectangular area on the screen. It has a visible part and is responsible for drawing. A view also responds to events. Layouts, buttons, text boxes, check boxes and other widgets are all views.


  • A Widget has roughly the same as it does for a Visual Basic control. That is, it has a visual interface, and supports a code behind file (Java), and can handle events.

An XML Review


In this section, the eXtensible Markup Language (XML) and key XML concepts are summarized. However, this is not a complete discussion of XML and related standards. XML does not pertain to just to Android. XML is supported and used by many programming languages and development environments including .NET.

XML is an acronym for the eXtensible Markup Language. Its purpose is to represent, store, and provide a way to transfer data. The following list describes the rules of XML:



  • Start tags are enclosed in angle brackets <>.


  • End tags are enclosed in angle brackets the (/) preceding the tag name.


  • Tags must be properly nested.


  • Every document (or document fragment) must have exactly one and only one root element.


  • XML documents are represented as a tree structure and operate similar to the HTML DOM.

Following is a simple XML document:





Zaphod
Beeblebrox




  • In the above, the first line indicates that the document is an XML document. The syntax is the same for all XML documents.



  • The root (outermost) node is named
    .


  • It contains a child node named .


  • The node contains two child nodes named and . These two nodes contain content. Content appears between the starting and ending node tags. The other elements do not have content.


  • Each opening tag has a corresponding closing tag.

Android elements can have 0, 1 or many attributes. Android attributes contain data about an attribute. XML attributes have the same syntax as HTML attributes.

  • Attributes appear inside the opening element tag.


  • Attributes appear as key / value pairs.


  • An equal sign separates each key / value pair.


  • Values appear in quotation marks.


  • Attribute key/value pairs can appear in any order.


  • A space separates each key value pair.

Android uses XML for several purposes as you will see throughout this course.

  • An XML document named android.manifest is used to identify the files that make up an Android Application project.


  • It is used to describe the user interface for each screen in the application. These files are known as layout resources.


  • It is used to describe the strings and other constants that make up the application. Strings are known as string resources.

Another feature of XML that you need to know is the notion of XML namespaces. XML namespaces are used to qualify an element name or an attribute name and to determine the XML vocabulary to which the element belongs. To understand the concept and syntax of an XML namespace look at the following Android code. This file will be explained in detail more later in this tutorial.

"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="com.example.helloandroid.MainActivity" >

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />


The above code introduces the notion of an XML namespace:



  • The prefix xmlns, is itself a namespace prefix. The (:) follows the xmlns prefix, followed by another name called a namespace prefix. The namespace value is a URL. Note that this URL is just a name. It does not necessarily point to a Web Site, physical, or logical file. An XML namespace typically defines a vocabulary. (the element names and the order in which the elements must be assembled.)




  • In the above declaration, the android namespace prefixes are android and tools.


  • The attribute named android:layout_width=”match_parent” is saying that the layout_width attribute belongs to the android namespace.


  • The attribute named tools:context is saying that the context attribute belongs to the tools namespace.


  • In addition, note that the root node is . It has a child node named . Both elements have several attributes, each referencing a particular namespace.

Creating a First Android Application


The first lab which discussed the installation of Eclipse and Android pointed out Android version numbers, names, and the corresponding SDKs. When you create an Android project, you give the project a name and a package to which the project belongs. The following three SDK versions are defined for an application:

  • Minimum Required SDK: This is the oldest Android version on which the application is designed to execute. For my demonstrations, the Minimum Required SDK version will be 5.0.1 or 5.1.1.


  • Target SDK: This is the latest Android version on which the application is designed to run. This version is usually the latest Android version.


  • Compile With SDK: This is the Android Version used to compile the application. It must be greater than or equal to the Target SDK. In my examples, this will be the current Android SDK version.


  • Theme: For now, suffice to say that the Theme describes the look of an application and you will select the default themes

HANDS-ON ACTIVITY – Creating a new Android Application Project

  1. Make sure that Eclipse is running and that the default workspace is open. Android uses the same notion of a Workspace as the Java programs that you created previously..


  2. On the Eclipse menu bar, click File, New, Android Application Project. If this option does not appear, click File, New, Project. In the dialog box that appears, select Android Application Project.



  3. Complete the information as shown in the following dialog box:

    Make sure to set the Application Name to HellloAndroid. When you do, the Project name and Package Name are completed automatically. As you can see as you work with the dialog, you can create the application to support any number of different Android versions. For the most part, we will use API Version 22: This is the version running on most phones. Set the SDK versions as shown in the above figure.

    You can ignore the warning error about using the package named “com.example”. When an application is deployed, it should be created in a unique package name. However, we will not worry about deploying packages yet.


  4. Click Next to display the following dialog box:

    There are a couple of important configuration options in this step. The check box titled Create custom launcher icon should be checked along with the check box titled Create activity. The first configures an icon for the application. The second causes a subsequent dialog box to be displayed that will allow you create the application’s default activity (first screen). Make sure that the options in the following figure are checked:






  5. Click Next to display the following dialog box. You will not change the default icon. However, realize that Android devices are designed to use one of many resolutions (and corresponding icons) shown. Depending on the device itself, one of the resolutions will be chosen by the Android system. Creating device-independent applications will be discussed further in subsequent tutorials.




  6. Click Next to display the following dialog box:

    Recall on the initial screen you told Eclipse to create a launch activity that will be run when the program starts. Here, you tell Eclipse what kind of activity to create. Activities will be discussed in much more detail later. However the default Blank Activity will create a screen that displays the all too familiar Hello World message, and the necessary code to display that screen (activity).






  7. Make sure that Blank Activity is selected.


  8. Click Next to display the following dialog box:




  9. An activity has two parts. The Activity Name is the name of the Java class containing the code for the activity. The default activity (class) name is MainActivity and is stored in the file MainActivity.java. The Layout Name contains the XML file that describes the layout (screen formatting). By default, the name of the layout file is activity_main.xml.


  10. Use the default options and click Finish to create the project. When you do, Eclipse creates many different files as shown in the Package Explorer.



The purpose and general content of these files is discussed in the next section:

Understanding the Structure of an Android Application


An Android application has a well-defined structure. That is, an application’s files are put in different folders based on the purpose of the file. In addition, certain configuration files and resource files always have the same name. Roughly speaking, Android application files are categorized as follows:

  • Applications contain one or mode code files. There is a code file for each activity and fragment, and other code file types.


  • Images, string constants, menus, layouts, and others are implemented as resources. Most resources are represented as XML files.

By default, every application, no matter how simple, will contain the following folders:

  • The folder named src contains the application’s source code (Java Code files). The application’s source code will be discussed later in this document.


  • When a program is compiled, Android generates a few files that are used by your program code. These files appear in the folder named gen. (generated)


  • res is short for resources. In this folder, there are sub-folders that store images, and the XML code used to describe the application’s screens and other constant data.


  • The folders named bin and libs contain binary files and other libraries needed by the application.

Other folders are discussed later, and in more detail.

The AndroidManifest.xml File


The purpose and structure of the AndroidManifest.xml file is fully documented at: http://developer.android.com/guide/topics/manifest/manifest-intro.html

Every Android application has a file named AndroidManifest.xml (again, an XML document) appearing in the application’s root folder. It contains the information necessary to compile and run the application. The following code segment shows the AndroidManifest.xml file for this Hello World application:



"1.0" encoding="utf-8"?>

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

package="com.example.helloandroid"

android:versionCode="1"

android:versionName="1.0" >


android:minSdkVersion="19"

android:targetSdkVersion="23" />

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

android:name=".MainActivity"

android:label="@string/app_name" >



"android.intent.action.MAIN" />
"android.intent.category.LAUNCHER" />






It uses the following android XML namespace as most Android configuration files do.

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

Every Android application belongs to a package. The package attribute appears as follows.

package="com.example.helloandroid"

For most applications in this class, you will use the default package name. However, applications that you deploy should have package names for registered domains. The element has a child element named . The element tells the Android system versions for which the application is compatible.



  • The attribute android:minSdkVersion=”value” depicts the minimum API level on which the application will install and run.


  • android:targetSdkVersion=”value” contains the version for which the application is designed to run.


  • android:maxSdkVersion=”value” contains the maximum Android version for this the application is designed to run. If this value is not specified, the current Android version is implied.

The element has a child element named used to declare the application’s components. In the above code segment, the following attributes appear:



  • Android supports a backup and restore infrastructure. The attribute android:allowBackup defines whether the application will participate in this infrastructure.


  • android:icon depicts the application’s icon. The attribute’s value is set to @drawable/ic_launcher. The fragment @drawable tells the compiler where to look for the icon named ic_launcher. Referencing resources will be discussed later in this lab.


  • Think of android:label as containing the application’s title. The value "@string/app_name" tells the compiler to look for the resource named app_name.


  • Android applications have a theme. For now, think of a theme as CSS file for an application. It is used to set the application’s default appearance. The attribute named android:theme defines the application’s theme. For most of this class, you will use Android-provided themes.

The element has a child element named . An activity is roughly equivalent to a Visual Basic or C# form. They have both a user interface (XML), and a code behind (Java). There should be one element for each in the application. In this example there is one activity with the following two attributes:

  • The attribute named android:name=”.MainActivity” contains the name of a class that implements the Activity class or one of its subclasses. In this example, the class is named MainActivity. This is the name that you chose for the activity when you created the project. Note that the value begins with a leading dot (.), indicating that MainActivity is a class.


  • The android:label=”@string/app_name” attribute defines the activity’s title. If this attribute is not defined, the application’s label is used. Again, the attributes value points to the resource named app_name.

The element has a child element named . In .NET, you create forms and display them with a method such as Form.Show(). In Android, activities are started and rendered using intents. And an intent filter tells Android the name of the action to perform. An intent filter, in turn, as two child elements named and .

  • The element’s android:name attribute should contain the name of the activity to start.


  • Android describes what are referred to as “standard actions”. The action “android.intent.action.MAIN” is one of those standard actions. It causes the action to be the startup action and therefore the program’s entry point. Thus, in this example, MainActivity is configured as the startup action and will run automatically when the application starts.


  • Intents also have a . The standard value android.intent.category.LAUNCHER works with the to tell the system that this is the initial activity and should be listed in the system’s application launcher. Other Android categories will be discussed when they are used.

In summary, the manifest file tells the system everything it needs to compile and run the application including viable android versions, the application’s components, and the startup (default) activity.

HANDS-ON ACTIVITY – Viewing the Application’s Manifest

In this set of steps, you will examine the Application’s manifest, and the Eclipse tools used to manage it.



  1. In the Package Explorer, make sure that the HelloAndroid project is expanded. Double-click on the AndroidManifest.xml file to open the editor shown in the following figure. Click the AndroidManifest.xml tab, if necessary.

    The XML shown in the above figure is the same as the AndroidManifest.xml file just discussed. Its content can be edited directly.




  2. Click the Manifest tab to display the editor shown in the following window:

    The Manifest tab, shown in the above figure, contains a WYSIWYG editor that writes the XML for you.




  3. Click the Application tab to display the following window:

    The Application tab contains another WYSIWYG editor that writes the XML pertaining to application resources. As you can see, the resource names are the same as those in the XML files. Note that, Permissions and Instrumentation are not discussed in this section.


The res Folder


The folder named res contains the application’s resources. Most of these files are XML files although a few contain images. This folder contains several important sub-folders as shown in the following figure:


The res/drawable Folders


The folders beginning with the word drawable contains the application’s images. The folder suffixes depict the resolution of the images in the folder. When and Android application runs, the runtime will choose the best image resolution based on the device’s screen size and resolution: The following list describes the commonly used resolutions:

Name

Resolution

hdpi

240 dpi

ldpi

120 dpi

xhdpi

320 dpi

xxhdpi

490 dpi

Note that the drawable folder names in the res folder are significant. If the folders are not named correctly, the images will not be located by the compiler and runtime.

The following figure shows (roughly) how the sizes are mapped based on the size and resolution of the device:




The res/layout Folder


The folder named layout, as the name implies, contains the layout(s) for each activity in the package. Think of a layout as the screen design for a Visual Basic form. A layout describes the kind of layout and the controls (widgets) appearing on the layouts, their position, and other formatting properties. Layouts are considered resources, and are therefore XML files. In this example, there is one activity named activity_main.xml. Most applications have multiple activities and at least one layout per activity. As you will see in subsequent labs, it is possible for one activity to have several layouts that will be used based on the device size and resolution.




HANDS-ON ACTIVITY – Viewing the Main Layout

In these steps, you will look at the XML for the layout named Activity_Main.xml, and the accompanying Eclipse Layout Editor.



  1. In the Package Explorer, expand the layout folder and double-click the file named activity_main.xml. If necessary, double-click the ativity_main.xml tab.

    As you can see, the file is an XML file. The outermost element is named , which renders the widgets relative to each other or the layout window itself. Layouts will be discussed in much more detail later The element is a child of the . It displays a prompt much like the Visual Basic Label control. The various attributes describes the application’s resources and positioning innnformation.




  2. Click the Graphical Layout tab to display the window shown in the following figure:

    Note that the first time the graphical editor is loaded, it might take a minute or two. As you can see, the visual editor works like most visual editors. It contains a Palette containing the controls (widgets) supported by Android. It contains a visual surface where you can see what the Layout will look like.


The res/Menu folder


The menu folder contains the application’s menu(s) if one exists. Again, this file is an XML file and just another resource.

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

xmlns:tools="http://schemas.android.com/tools"

tools:context="com.example.helloandroid.MainActivity" >

android:id="@+id/action_settings"

android:orderInCategory="100"

android:showAsAction="never"

android:title="@string/action_settings"/>

The

element contains menu items. The element must be a root node. Its children can be of type or . Again, the element uses the android and tools namespaces. The element creates a menu item. The element is a container for elements. It is used as a way to share properties across the group. Each has the following attributes:



  • The android:id attribute gives the item a unique id value. As you will see later, this value is used to connect the menu item, to an event (callback). The value of the id element will be discussed in a moment.


  • The android:title attribute contains a string resource. The value of this resource appears as the menu item text. The resource is declared in the string.xml file and contained in the resource.

The @+id and @string syntax is very significant and understanding it is fundamental to connecting the widgets you create in XML to the Java code you will write.

The statement fragment:

@+id/

tells the compiler to create the resource having the specified identifier name. So @+id/action_settings creates a unique identifier named action_settings. The process is akin to declaring a variable in the XML file as you will see later in this tutorial.



The statement fragment

@string


tells the compiler to reference an existing resource. In this case, a string resource is being referenced. The string resource is named action_settings. @string/action_settings

Next, you will see how resources are declared and how the resource references work.



HANDS-ON ACTIVITY – Viewing the Menu Editor

Eclipse provides and editor with which you and edit the XML for the menu.



  1. Expand the res/menu folder and double-click the menu named menu.xml.

    As you can see, the main.xml tab allows you to edit the menu directly. The Layout tab supplies a visual editor.


The res/values Folder


The res/values folder contains a set of files. These files, in turn, contain resource declarations such as constant string and numeric values, and colors. These simple values (resources) are used elsewhere in the application as constant values. The process is similar to declaring constants in the .NET environment. The values resource files exist to simplify the process of localizing applications. You can use any file names that you want for these resources, but best practices suggest you use the following file names:

  • arrays.xml contains the data for typed arrays.


  • colors.xml contains color values used elsewhere in the application.


  • dimens.xml contains a dimension value. A dimension value is a number followed by a unit of measure. Its resources are used to apply standard sizes to an application’s visual objects.


  • strings.xml contains literal string values and string arrays. String resources should be used in favor of literal values in program code or other resources.


  • A style resource defines the appearance for a user interface. Styles appear in the resource file styles.xml.

Only the resources dimens.xml and strings.xml will be discussed here.

All of the above resource files have an outermost element named . When the program is compiled, all of these resources are combined together. The node has the following children:



  • name”>value declares a string resource.


  • name”>value declares a dimensional resource.

When using resources, the value of the name attribute becomes the unique identifier for the resource. The element’s value contains the value of the resource. As you have seen, these resources are used in other files, such as the activity’s layout file. These resources can also be referenced programmatically using Java code.

The Strings.xml file and Resources


The string.xml resource file contains elements inside of a element. The attribute has a name attribute containing the key, which is the unique identifier used elsewhere. The element’s content contains the value of the resource. The following file declares resources named app_name, hello_world, and action_settings.

"1.0" encoding="utf-8"?>


"app_name">HelloAndroid

"hello_world">Hello world!

"action_settings">Settings

To illustrate the purpose of the string resources, look at the following code from the activity_main.xml file



android:text="@string/hello_world" />





  • The element declares a text prompt that operates similar to a Visual Basic Label control.


  • The android:text attribute contains the text displayed in the element’s visible region.


  • Its value is “@string/hello_world”, which tells the system to look for the resource named “hello_world”. Remember that @string tells the system to reference a string resource name. This resource is declared in the strings.xml file.


  • The value is the text Hello World! So this text will appear in the visible region of the text box.

    "hello_world">Hello world!

The other string resources are not discussed in this section.

HANDS-ON ACTIVITY – Viewing String Resource Editor

In this exercise, you will look at the string resource editor and the strings declared.



  1. In the Package Explorer, double-click on the file named layout/string.xml. Open the layout folder, as necessary. Click the string.xml tab to view the following XML.

    These are the same string resources just discussed.




  2. Click the Resources tab to view the editor as follows.




  3. The Add button creates a new resource. Click the appName (String) resource to select it. The following View appears allowing you to edit the resource’s name and value.



  4. Close the View.

The dimen.xml File and Resources


The resource is used, by convention, to define default screen margins and other display attributes. The following dimen.xml file defines two dimensions:



"activity_horizontal_margin">16dp

"activity_vertical_margin">16dp



  • The activity_horizontal_margin dimension is set to 16dp. (device independent pixels).


  • The activity_vertical_margin dimension also set to 16dp.

The following layout resource shows how these resources are used:

"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="com.example.helloandroid.MainActivity" >



  • Layouts will be discussed in much more detail later. For now, just know that a causes the elements on a screen to be arranged such that their position is relative to the parent window, or another window.


  • The paddingBottom attribute defines the padding along the bottom of the child elements. Padding has the same meaning here as it does with CSS. Its value is the resource named @dimen/activity_vertical_margin, which is 16dp. So the resource named activity_vertical_margin is being referenced.


  • The paddingLeft attribute defines the padding along the left of the child elements. The value of the resource is 16dp. So the resource named activity_horizontal_margin is being referenced

HANDS-ON ACTIVITY – Viewing String Resource Editor

For this activity, will look at the xx Editor. It operates the same way as the string editor.



  1. Again in the layout folder, double-click on the Dimens.xml file. The following Editor appears.




  2. Select a dimension. Again, you can edit the key value pairs.



The values-v11, values-v14, values-w820dp folders contain styles for older Android versions and screen resolutions and are not discussed here.


The R File


When you compile a program, Eclipse generates what is called the “R” file. The “R” file is significant because it provides the linkage between the resource and layout files and the Java code.

To begin, take a look at this first part of the “R” file for this program.

First, note that the class is named “R” for resource.

public final class R {

Because the class is declared with the public access modifier, the other classes in the Android (Java) program can reference its public members. The final keyword indicates that the class cannot be inherited.

Inside of this class block is a class named string corresponding to the resource.

It contains static final variables having the same name as the resource name. All of these resources are integers. The value contains a logical memory address. Thus, these variables (fields) are really reference types.



public static final class string {

public static final int action_settings=0x7f050002;

public static final int app_name=0x7f050000;

public static final int hello_world=0x7f050001;
}

corresponding to the resource that was just declared.



"1.0" encoding="utf-8"?>



"app_name">HelloMVE

"hello_world">Hello world!

"action_settings">Settings

To illustrate a second example, recall that some resources were declared with unique identifiers +@id/. These declarations are built into the “R” file. Recall that one id attribute was declared as follows:



android:id="@+id/action_settings"

Again, this declaration means to create an element with a unique identifier named action_settings. This declaration is translated to the “R” file as follows.

public static final class id {

public static final int action_settings=0x7f080000;

}

A variable named action_settings is declared in a class named id. Again, the value is just a memory address. (A pointer to an object)



As you will see in a moment, it is through these id’s that you can reference these resources as programmatic objects. You will also look at the R file later in this tutorial because the program has not been compiled so the R file has not yet been generated..

Do not ever edit the R file. It is created by the compiler when the project is built.

Occasionally, the R files gets out of sync with the program itself. If / when that happens, clean the project and remove the R file. Then rebuild the project.

Basics of the Layout File


Compare the layout file to a Visual Basic form. However, it’s written in XML. The following code segment shows the layout file for the main activity:

"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="com.example.hellomve.MainActivity" >

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />





  • The layout file for an activity is just another XML resource file. In this example, the root node is . It uses the android and tools namespaces. As you will see later, Android supports several different layouts.


  • The attributes android:layout_width, and android:layout_height define with width and height of the window (view). The constant value match_parent indicates that the size of the view should be the same size as the parent window. In this case, the parent window is the device screen itself.


  • Note that the padding attributes references various resources using the @dimen syntax. The contains a control (widget). The control is a , which operates similar to a Visual Basic Label control. The size of the control is defined by the android:layout_width and android:layout_height properties. The value wrap_content is a predefined constant value that causes the size of the widget to match its contents.


  • The control references the resource named hello_world. Again, @string says to reference the resource. The text attribute defines the text that will appear in the widget’s visible region. In other words, the statement sets the visible to text to the value of the hello_world resource, which is “Hello World”;

HANDS-ON ACTIVITY – Viewing the Layout Editor

In this step, you will look at the XML for a layout and view the editor.



  1. In the Package Explorer, expand the folder res/layout. Double-click the Activity_Main.xml file to open the Editor.


  2. View the Activity_Main.xml file.


  3. View the Layout Editor tab using the tabs at the bottom of the View.

The src Folder


The folder named src contains the application’s Java code files. These are not resources. In this case, the code file is named MainActivity.java. The file contains a class named MainActivity, a callback method named onCreate, and two callback methods named onCreateOptionsMenu, and onOptionsItemSelected.


The Main Activity File


This section discusses the code generated by the template, which causes the activity to be displayed.

The Android activity’s .java file is just Java code. It is not syntactically different from the Java code you have written so far.

Like all Java program files, they belong to a package. This is the same package name you specified when you created the Android project.

package com.example.helloandroid;

They import various other namespaces.



import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

In the above, four android namespaces are imported. These namespaces and classes will be discussed in more detail in subsequent tutorials.

Android applications operate in a prescribed way. That is, when a program starts, a startup activity is run as discussed already. An Activity usually overrides the onCreate methods, which executes when the activity first starts. The code in this activity is discussed next.

First, notice that the class is named MainActivity and is derived from the Activity class.



public class MainActivity extends Activity {

The onCreate method is called by the runtime when the activity is first created. The activity is created when the program starts because it was designated as the launcher activity in the AndroidManifest.xml file.

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}


  • The @Override attribute indicates that the onCreate method overrides the method of the base Activity class. The method is called implicitly when the run time creates the class instance. Think of this method as a callback method, that is implicitly called by the Android runtime.


  • The Bundle argument


  • The first statement in the method calls the onCreate method of the base class.


  • The next statement calls a method named setContentView. This statement tells the runtime which layout to display. While this program has only one layout, it could have several. Thus, it’s important to tell Android which layout to display. Recall that the main activity resource was named activity_main. The compiler translates this resource declaration into the following class in the “R” file.

public static final class layout {

public static final int activity_main=0x7f030000;

}

The remaining code to create the menu and handle the menu events is not discussed in this section.



From the menu bar, click Project. Build Project From the menu bar, click Project Clean.

Compiling an Application


Like a Java application, an Android application must be compiled before it can be run. The following list describes the possible keystrokes to compile an application:

  • In the Package Explorer, right-click on the Android Project and select Build Project from the context menu.


  • Select the project in the Package Explorer. From the menu, click Project, Build Project.

Note that the compilation results appear in the Console View

HANDS-ON ACTIVITY – To Compile an Android application

The following steps to compile an Android application are about the same as the steps to compile the Java applications that you have already created.



  1. If necessary, open the Console View by clicking Window, Show View, Console.


  2. Make sure that the project is selected in the Package Explorer.


  3. Click Project, Build Project. You should see the following compilation messages appear in the Console View as follows:



Running the Application


In this set of steps, you will test the Hello World application that you just wrote. These steps are a bit tricky as the Android emulators can be a bit fragile. Note also that there are several different ways to run an Android Project.

  1. Make sure that the Android project is selected in the Package Explorer.


  2. Click Window, Android Virtual Device Manager to display the following dialog box.

    Depending on your computer’s configuration, you might need to create a new virtual device. You might also see different virtual devices than those shown in the above figure. If the correct virtual device does not appear, create a virtual device that is compatible with the Android version compatible with the project you just created.




  3. Select the AVD and click Start to begin running the device. The following dialog box appears:




  4. Click the Launch button.

    Another dialog appears indicating that the virtual device is starting. The Android Virtual Device starts. This process takes a while. As much as 3-5 minutes. The Android message will appear in the virtual device window. When the device has started, you will see a familiar Android home screen as follows:








  5. In Eclipse, right-click on the project, and then click Run As. Select Android Application from the Context menu. Click in the emulator. Your program should run as shown in the following figure:



| Page


Directory: faculty -> ekedahl -> IS389
faculty -> Curriculum vitae wei chen professor
faculty -> Digital image warping
faculty -> Samples of Elements Exam Question III contains All Prior Exam Qs III except
faculty -> 【Education&Working Experience】
faculty -> References Abe, M., A. Kitoh and T. Yasunari, 2003: An evolution of the Asian summer monsoon associated with mountain uplift —Simulation with the mri atmosphere-ocean coupled gcm. J. Meteor. Soc. Japan, 81
faculty -> Ralph R. Ferraro Chief, Satellite Climate Studies Branch, noaa/nesdis
faculty -> Unit IV text: Types of Oil, Types of Prices Grammar: that/those of, with revision
IS389 -> Installing java, eclipse, and android sdks to setup an android development environment
IS389 -> Is 389 android fragment lab ekedahl
IS389 -> Please download a current copy. I have modified it since the initial upload

Download 119.6 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2022
send message

    Main page