Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
1 
 
# COMP5047 – Android Sessions (Week 2): 
 
# Lab 1: Eclipse and the Android Device Emulator: 
The main goal of Lab 1 is to familiarise yourself with the Eclipse IDE and use of the Android plug-in, including 
the Android Device Emulator (ADE). Instructions for this lab are as follows: 
 
Part 1: Creation of a new HelloWorld Android project and the running of the application in the emulator 
(based on the Android tutorial at: http://developer.android.com/training/basics/firstapp/index.html). 
1. Load up Eclipse: 
 From the Windows task bar, click “Eclipse v3.7 Indigo”. You should see Eclipse loading up. 
 Select a workspace. 
o As all personal data on C:\ is deleted upon logging out of the computer, you should 
make certain that you select a directory on your home drive, such as: 
 U:\eclipse\workspace. 
 Set up the location of the Android SDK: 
o Click Window > Preferences > Android, and fill in the SDK location (you can browse to 
the directory, which should be the following): 
 C:\android-sdk-windows.  
o Click Apply and then OK. 
Note: This setting is remembered by Eclipse each time you log back into one of the 
University computers. Also note that an Android Virtual Device (AVD) has already 
been created for your use. AVDs represent the emulators that you will use when 
running your Android applications. 
 
2. Create a New Android Project: 
 From Eclipse, select File > New > Project. 
 Select “Android/Android Application Project” and click Next. 
 Fill in the project details with the following values: 
o Application Name: My First App 
This is the human-readable title for your application, and the name that will appear for 
the application on the Android device. 
o Project Name: MyFirstApp 
This is the Eclipse Project name, i.e. the name of the directory that will contain the 
project files. 
o Package Name: au.edu.sydney.myfirstapp 
This is the package namespace (following the same rules as for packages in the Java 
programming language) that you want all your source code to reside under. 
o Build SDK: The "Build SDK" is the platform version that your application will be compiled 
against. Select Android 2.2 (API 8) from the available options. 
o Minimum Required SDK: API 8: Android 2.2 (Froyo). 
This value specifies the minimum API Level required by your application. With each new 
version of the Android system image and Android SDK, there have been additions or 
changes made to the APIs. When this occurs, a new API Level is assigned to the system 
image to regulate which applications are allowed to be run. If an application requires an 
API Level that is higher than the level supported by the device, the application will not 
be installed. 
o Other fields: The checkbox for "Create Project in Workspace" allows you to change the 
location on disk where the project's files will be generated and stored. 
 
2 
 
Notice that the selected "Build SDK" uses the Android 2.2 platform. This means that your 
application will be compiled against the Android 2.2 platform library. Android 
applications are forward-compatible, so an application built against the 2.2 platform 
library will run normally on the 2.2 platform and above. The reverse is however not true. 
 
 
o Click Next. 
 Configure a Launcher icon: This screen provides tools to help you create a launcher icon for your 
app. You can customize an icon in several ways and the tool generates an icon for all screen 
densities. 
o Click Next. 
 Create an Activity: Now you can select an activity template from which to begin building your 
app. This will be a subclass of Android's Activity class. An Activity is simply a class that can run 
and do work. As the checkbox suggests, this is optional, but an Activity is almost always used as 
the basis for an application. 
o Select BlankActivity and then click Next. 
o Leave the details as they are and click Finish: 
 Activity Name: MainActivity 
 Layout Name: activity_main 
 Navigation Type: None 
 Title: MainActivity 
 
 Your Android project is now ready. It should be visible in the Package Explorer on the left (you 
may need to close the Eclipse “welcome” page first if you have not already done so). Open the 
MainActivity.java file, located inside MyFirstApp/src/au.edu.sydney.myfirstapp). 
 
Notice that the class is based on the Activity class. An Activity is a single application entity that is 
used to perform actions. An application may have many separate activities, but the user 
interacts with them one at a time. The onCreate() method will be called by the Android system 
when your Activity starts — it is where you should perform all initialization and UI setup. An 
activity is not required to have a user interface, but usually will. 
3 
 
 
3. Run the Application: 
The Eclipse plug-in makes it very easy to run your applications: 
 Right click the MyFirstApp project in the Package Explorer and Select “Run As” > "Android 
Application” and then wait till the AVD begins to load. 
 
The Eclipse ADT will automatically create a new run configuration for your project and the 
Android Emulator will automatically launch. Once the emulator has loaded, unlock the emulator 
by sliding the lock icon to the right, and then wait till your application appears. You should now 
see something like this: 
 
 
The text that you see in the grey bar ("MainActivity") is the activity name. The Eclipse plug-in creates 
this automatically (the string is defined in the res/values/strings.xml file and referenced by your 
AndroidManifest.xml file). The text “Hello world!” is another string resource that is referenced 
within a TextView object inside the activity_main.xml file. 
 
Note: It is best not to turn off the emulator; this will save time when it comes to recompiling and 
running your applications.  
 
4. Constructing the User Interface using an XML Layout: 
The general structure of an Android XML layout file is simple: it's a tree of XML elements based on 
the View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields 
and ViewGroup objects are invisible view containers that define how the child views are laid out, 
such as in a grid or a vertical list. This structure makes it very easy to quickly build up UIs, using a 
simpler structure and syntax than you would use in a programmatic layout. This model is inspired by 
the web development model, wherein you can separate the presentation of your application (i.e. its 
UI) from the application logic used to fetch and fill in data. You should almost always define your 
layout in an XML file instead of in your code. 
 
4 
 
XML layout files belong in the MyFirstApp/res/layout/ directory of your project. The "res" is short for 
"resources" and the directory contains the non-code assets that your application requires. In 
addition to layout files, resources also include assets such as images, sounds, and localized strings. 
 
The BlankActivity template that you used to start this project creates the activity_main.xml file with 
a RelativeLayout root view and a TextView child view. 
 
 In the Eclipse Package Explorer, expand the /res/layout/ folder and open activity_main.xml. In 
Eclipse, when you open a layout file, you are first shown the Graphical Layout editor. This is an 
editor that helps you build layouts using WYSIWYG tools. For this task, you’re going to work 
directly with the XML, so click the "activity_main.xml" tab at the bottom of the window to see 
the XML source. Change the RelativeLayout to a LinearLayout, as shown below: 
 
 
 
 
 
 
In the above example, there are two elements: LinearLayout and TextView. A LinearLayout is a view 
group that lays out child views in either a vertical or horizontal orientation. Here is a summary of 
what the attributes mean: 
o xmlns:android: This is an XML namespace declaration that tells the Android tools that 
you are going to refer to common attributes defined in the Android namespace. The 
outermost tag in every Android layout file must have this attribute. 
o xmlns:tools: This is another XML namespace declaration that can be used to configure 
the lint tool for static code analysis. 
o android:orientation: This attribute defines which direction the contained elements 
should be organised in. Possible values include “vertical” and “horizontal”. 
o android:layout_width: This attribute defines how much of the available width on the 
screen this View should consume. The value “match_parent” (renamed from 
“fill_parent” in API 8) means that the widget should expand its width or height to match 
the width or height of the parent view. An alternative, “wrap_content” means that the 
widget should size itself to the dimensions required by its content. 
o android:layout_height: This is just like android:layout_width, except that it refers to the 
available screen height. 
o android:text: This sets the text that the TextView should display. In this example, you 
use a string resource instead of a hard-coded string value. The “hello_world” string is 
defined in the res/values/strings.xml file. This is the recommended practice for inserting 
strings into your application, because it makes the localization of your application to 
other languages simpler, without needing to hard-code changes to the layout file. 
 
 Inside the res/values/ folder, open strings.xml and click the “strings.xml” tab. This is where you 
can save all default text strings for your user interface. When using Eclipse, the ADT will have 
started you with several strings, including “app_name” and “hello_world”. The contents should 
look as follows: 
 
 
 
5 
 
    My First App 
    Hello World! 
    Settings 
    MainActivity 
 
 
 Revise the “hello_world” attribute value to something else. Perhaps "Hello Android. I am a string 
resource!" Save the file and then re-run your application. Because a launch configuration has 
now been created for your app, all you need to do is click the green arrow icon and select the 
MyFirstApp option to run. 
 
 
5. The AndroidManifest: 
AndroidManifest.xml is the foundation of any Android application. It is in this file that you declare 
what is inside your application - the activities, the services, and so on. You also indicate how these 
pieces attach themselves to the overall Android system; for example, you indicate which activity (or 
activities) should appear on the device's main menu (a.k.a., launcher).   
 
 In the Eclipse Package Explorer, open AndroidManifest.xml. The contents should look as follows. 
Note that the intent-filter element is used to indicate that the MyFirstApp activity is the main 
activity and the one to be launched when an application starts up. 
 
 
 
     
     
         
             
                 
                 
             
         
     
 
 
6. The R class: 
 In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder).  A project's 
R.java file is an automatically created index to all of the resources defined in the file. This class is 
used by the Android SDK as a short-hand way to refer to resources you've included in your 
project. This is particularly powerful with the code-completion features of IDEs like Eclipse 
because it lets you quickly and interactively locate the specific reference you are looking for. 
 
For now, notice the inner class named "layout", and its member field "activity_main". The Eclipse 
plug-in noticed the XML layout file named activity_main.xml and generated a class for it here. As you 
add other resources to your project (such as strings in the res/values/string.xml file or drawables 
inside the res/drawable/ directory) you'll see R.java change to keep up. 
 
You should never edit this file by hand. 
6 
 
 
7. Debugging your project: 
 The Android Plug-in for Eclipse also has excellent integration with the Eclipse debugger. To 
demonstrate this, introduce a bug into your code; change your MainActivity.java source code to 
look like this: 
 
package au.edu.sydney.myfirstapp; 
  
import android.os.Bundle; 
import android.app.Activity; 
 
public class MainActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        Object o = null; 
        o.toString(); 
        setContentView(R.layout.activity_main); 
    } 
} 
 
 This change simply introduces a NullPointerException into your code. Run your application again. 
You should now see an error message in the emulator: 
Press "Force Close" to terminate the application in the emulator window. 
 
 To find out more about the error, set a breakpoint in your source code on the line Object o = null; 
(double-click on the marker bar next to the source code line). Then select Run > Debug History > 
MyFirstApp from the menu to enter debug mode. Your app will restart in the emulator, but this 
time it will suspend when it reaches the breakpoint you set. You can then step through the code 
in Eclipse's Debug Perspective, just as you would in any other IDE. 
 
 Notice also the yellow warning that is generated in the Java perspective’s “Problems” tab: 
Warning: “Null pointer access: The variable o can only be null at this location”. 
 
Part 2: Familiarisation with the Eclipse IDE. Make sure that you have familiarised yourself with the following: 
 In the Java Perspective (i.e. located at the top right in Eclipse): 
o The Package Explorer Window, which shows the project’s structure. Also explore the 
project directories to see what was automatically created upon creating the project. 
o The Problems tab, which shows Errors and Warning for all open projects. 
o CTRL+F11: Loads up the last loaded application (compilation is automatic). 
o CTRL+H: Shortcut to file searching. 
o F5: Refreshes the content of the selected element with the local file system. When 
launched from no specific selection, this command refreshes all projects. 
 In the DDMS perspective (note: you may need to click the “Open Perspective” icon in the top 
right tab to get to the DDMS perspective): 
o The LogCat tab, which shows debugging information that has been coded into an 
application, e.g. Log.d(“The class name”, “The debugging message.”); 
 The following Eclipse settings may also come in handy: 
o Setting project launch configurations. This allows one to change the Run configurations: 
 Right click a project > Run As > Run Configurations. 
o Fixing project properties. This is sometimes needed when importing a project: 
 Right click a project > Android Tools > Fix Project Properties. 
o Reset perspective (e.g. Java, DDMS, Debug): 
7 
 
 Window > Reset Perspective. 
 
Part 3: Familiarisation with the Android Device Emulator (ADE). Make sure that you are familiar with the 
following: 
 The Applications tab. 
 The Menu button. 
 The Back button. 
 Also feel free to try out the applications on the emulator and look at the different settings that 
one can make. 
 
NB: Once the emulator has loaded up, don’t close it down, i.e. only exit the application not the 
emulator. This will save you time when re-running a project. 
 
Part 4: Importing the sample property project into Eclipse, in preparation for the next lab’s GUI design and 
Activity & Intent coding exercises. 
 Using your web browser and Windows Explorer, download and unzip the 
“COMP5047_Property_Application.zip” file to your Eclipse workspace. 
o URL: http://sydney.edu.au/it/~wasinger/teaching/comp5047/ 
 In Eclipse, click File > Import… 
o Select “General > Existing Projects into Workspace”. 
o Select root directory: Browse to the directory that you copied the project directory to, 
e.g. U:\eclipse\workspace\COMP5047 Property Application. 
o Make sure the Project is listed and selected in the “Projects” list. 
o Click Finish. 
 Right-click the project, and click “Properties” to check: 
o Android: To familiarise yourself with the listed Project Build Target. 
 Right-click the project, and click “Run As” > “Run Configurations” to familiarise yourself with 
creating customised Launch Configurations: 
o Click the New Launch Configuration button (top left). 
o Give it a Name (e.g. “COMP5047 PropertyApp”) and then select “Browse …” to open the 
project that the launch configuration refers to. 
o Under the Target tab, select the comp5047_android2.2 AVD. 
o Select Apply, and then Run.  
Note: You should see a white screen with the application title “COMP5047 Property 
Application”. It will be your job (as part of next week’s lab and as homework) to finish the 
Property Application so that it resembles something like the screen shots shown during the 
lecture.  
 
Part 5: Try out some of the code samples that come with the Android SDK. 
 Within Windows Explorer, create a directory on your home drive called U:\eclipse\sampleapps\, 
and copy across a number of the Android samples from the appropriate samples directory for 
the installed AVD, i.e.: 
o C:\android-sdk-windows\samples\android-8\ (e.g. consider the samples LunarLander, 
JetBoy, and Snake). 
 In Eclipse, click File > New > Project. 
 Select Android > Android Project from Existing Code. 
 Select the location, e.g. "U:\eclipse\sampleapps\ LunarLander". 
 To set to the Project Build Target, right-click the open project, click Properties > Android, and 
select Android 2.2 API Level 8. 
 Run as normal, by right-clicking the open project, and selecting “Run As” > “Android Application”.