EditorNguyễn Đức Minh Khôinguyenducminhkhoi@gmail.comnguyenducminhkhoi.blogspot.comTrainingAndroid@HCMC University of TechnologySummer 2012
Page: 4 Training Android June 2012Introduction – What is Android?The Android operating system was developed byAndroid, Inc.,Was acquired by Google in July 2005.Developing Android apps is the openness of theplatformThe operating system is open source and free.
Page: 6 Training Android June 2012Introduction (cont.)Java: was a logical choice for the Android platform enables you to develop apps that will run on a variety of devices without any platform-specific code. is object oriented and has access to powerful class libraries that help you develop apps quickly.
Page: 7 Training Android June 2012Introduction (cont.)XML: enables you to better separate the presentation of your application from the code that controls its behavior. makes it easier to visualize the structure of your UI, so its easier to debug problems Is similar to HTML
Page: 8 Training Android June 2012Introduction (cont.)Multitouch screen:
Page: 10 Training Android June 2012Introduction (cont.)Types of android apps (go tohttps://play.google.com/store) for more detailsOther sites you can download apps:
Page: 11 Training Android June 2012Introduction (cont.)
Page: 12 Training Android June 2012How to set upSoftware and hardware system requirement: To develop Android apps you need a Windows®, Linux or Mac OS X system. Java SE 5 or higher Software Development Kit Eclipse 3.7 (Indigo) IDE for Java Developers Android SDK versions 2.2, 2.3.3 and 3.x ADT (Android Development Tools) Plugin for Eclipse
Page: 13 Training Android June 2012How to set up (cont.)Install JDK (Java Development Kit) 6: Go to www.oracle.com/technetwork/java/javase/index- 137561.htmlInstall Eclipse IDE Go to www.eclipse.org/downloads Choose Eclipse IDE for Java DevelopersInstall the Android SDK Go to www.developer.android.com/sdk/index.html Click and choose your suitable platformInstall ADT plugin for Eclipse Go to www.developer.android.com/sdk/eclipse-adt.html carefully follow the instructions for downloading and installing the ADT Plugin
Page: 14 Training Android June 2012How to set up (cont.)Install Android platform:
Page: 15 Training Android June 2012How to set up (cont.)
Page: 16 Training Android June 2012How to set up (cont.)Creating Android Virtual Device (AVD): The Android emulator, included in the Android SDK, allows you to run Android apps in a simulated environment on your computer rather than on an actual Android device.
Page: 17 Training Android June 2012How to set up (cont.)
Page: 18 Training Android June 2012Source for learningBest resource for learning and referencing:http://developer.android.com/index.html
Page: 19 Training Android June 2012Source for learning (cont.)
Page: 20 Training Android June 2012Source for learning (cont.)
Page: 22 Training Android June 2012Welcome apps (cont.)
Page: 23 Training Android June 2012Eclipse IDE
Page: 24Training Android June 2012 Eclipse IDE (cont.) Create new Project:
Page: 26 Training Android June 2012Developing GUI
Page: 27 Training Android June 2012Developing GUI (cont.)
Page: 28 Training Android June 2012Developing GUI (cont.)
Page: 29 Training Android June 2012Developing GUI (cont.)
Page: 30 Training Android June 2012Developing GUI (cont.)
Page: 31 Training Android June 2012Developing GUI (cont.)
Page: 32 Training Android June 2012Running the Welcome apps To run the app in an Android Virtual Device (AVD), right click the app’s root node in the Package Explorer window and select Run As > Android Application.
Page: 33 Training Android June 2012Building FeaturesEach app below will expand on one Class hourBy practicing these apps you will learn someinteresting featuresEach app will contain: Introductionsand objectives New Features Building GUI Adding functions Results
Page: 34 Training Android June 2012Building FeaturesEach app below will expand on one Class hourBy practicing these apps you will learn someinteresting featuresEach app will contain: Introductionsand objectives Technologies Overview Building GUI Adding functions Results
Page: 35 Training Android June 2012Building Features (cont.)1.Tip Calculator App2.Favorite Twitter Searches App3.Flag Quiz Game App4.Cannon Game App5.Spot on Game App6.Doodlz App7.Address Book App8.Slideshow App9.Enhanced Slideshow App10.Weather Viewer App
Page: 36 Training Android June 2012 Tips Calculator AppObjectives:Building an Android App withJavaDesign a GUI using aTableLayoutDirectly edit the XML of a GUIlayout to customize propertiesUse Android Activity’s subclassinteract with EditTexts, aTextView and a SeekBar.
Page: 37 Training Android June 2012Tips Calculator App (cont.)Introduction:“The Tip Calculator app calculates and displays tipsfor a restaurant bill. As the user enters a bill total,the app calculates and displays the tip amount andtotal bill for three common tipping percentages—10%, 15% and 20%. The user can also specify acustom tip percentage by moving the thumb of aSeekbar—this updates the percentage shown to theright of the Seekbar. The suggested tips and billtotals are updated in response to each userinteraction.”
Page: 38 Training Android June 2012 Tips Calculator App (cont.)Technologies Overview:TableLayout and TableRow introductionSee more at:•www.developer.android.com/reference/android/widget/TableLayout.html•www.developer.android.com/reference/android/widget/TableRow.html
Page: 39 Training Android June 2012Tips Calculator App (cont.)Building GUI:Create GUI with the following information
Page: 40 Training Android June 2012Tips Calculator App (cont.)main.xml describe GUI like figure aboveString.xml
Page: 41 Training Android June 2012Tips Calculator App (cont.)Adding Functions:Remember when you want to import some library, use justtype the name of the class (don’t need to complete) and press(Ctrl + Space), it will import immediatelyClass Activity of package android.app provides the basiclifecycle methods of an app—we’ll discuss these shortly.Class Bundle of package android.os represents an app’s stateinformation. An app can save its state when it’s sent to thebackground by the operating system—for example, when theuser launches another app or a phone call is received.
Page: 42 Training Android June 2012 Tips Calculator App (cont.)Android apps doesn’t have main methodfour types of components—activities, services, content providers andbroadcast receiversA separate activity is typically associated with each screen of an appThroughout its life an activity can be in one of several states—active (orrunning), paused or stopped. An active (or running) activity is visible on the screen and “has the focus” A paused activity is visible on the screen but doesn’t have the focus. can be killed when its memory is needed by the operating system A stopped activity is not visible on the screen and is likely to be killed by the system when its memory is needed.See more at:www.developer.android.com/reference/android/app/Activity.html
Page: 43 Training Android June 2012Tips Calculator App (cont.)Override method: onCreate: called by the system when an Activity is starting—that is, when its GUI is about to be displayed so that the user can interact with the Activity. onSaveInstanceState: called by the system when the configuration of the device changes during the app’s execution Remember: Each activity lifecycle method you overridemust call the superclass’s version of that method first;otherwise, an exception will be thrown when that method iscalled.
Page: 44 Training Android June 2012Tips Calculator App (cont.)R content class: Class drawable—contains constants for any drawable items, such as images, that you put in the various drawable folders in your app’s res folder Class id—contains constants for the GUI components in your XML layout files Class layout—contains constants that represent each layout file in your project (such as, main.xml) Class string—contains constants for each String in the strings.xml file
Page: 45 Training Android June 2012Tips Calculator App (cont.) Results:
Page: 46 Training Android June 2012Favorite Twitter Searches App Objectives: SharedPreferences, Buttons, Nested Layouts, Intents, AlertDialogs, Inflating XML Layouts and the Manifest File Use a ScrollView to display objects that do not fit on the screen. Programmatically open a website in a web browser by using an Intent. Programmatically hide the soft keyboard.
Page: 47 Training Android June 2012Favorite Twitter Searches App (cont.) Introduction: “The Favorite Twitter Searches app allows users to save their favorite (possibly lengthy) Twitter search strings with easy-to-remember, user-chosen, short tag names. Users can then conveniently follow the tweets on their favorite topics. Twitter search queries can be finely tuned using Twitter’s search operators (dev.twitter.com/docs/using-search)—but more complex queries are lengthy, time consuming and error prone to type on a mobile device. The user’s favorite searches are saved on the device, so they’re immediately available each time the app launches.”
Page: 48 Training Android June 2012Favorite Twitter Searches App (cont.)
Page: 49 Training Android June 2012Favorite Twitter Searches App (cont.) Technologies Overview: ScrollView: is a ViewGroup that can contain other Views (like a layout) and that lets users scroll through content too large to display on the screen. To read the key/value pairs from this file we’ll use SharedPreferences objects (package android.content). To modify the file’s contents, we’ll use SharedPreferences.Editor objects (package android.content). The keys in the file must be Strings, and the values can be Strings or primitive-type values Intents are typically used to launch activities—they indicate an action to be performed and the data on which that action is to be performed. We load the URL into a web browser by creating a new Intent for viewing a URL, then passing that Intent to the startActivity method, which our Activity inherits indirectly from class Context
Page: 50 Training Android June 2012Favorite Twitter Searches App (cont.) New Features: LayoutInflater programmatically creates these GUI components from a predefined XML layout. The LayoutInflater inflates an XML layout file, thus creating the components specified in the XML. You can display messages and confirmations like these with an AlertDialog. We specify the settings for the dialog with an AlertDialog.Builder object, then use it to create the AlertDialog. The AndroidManifest.xml file is created for you when you create an app using the ADT Plugin in Eclipse. This file specifies settings such as the app’s name, the package name, the target and minimum SDKs, the app’s Activity name(s) and more
Page: 51 Training Android June 2012Favorite Twitter Searches App (cont.) Building the GUI:
Page: 52 Training Android June 2012Favorite Twitter Searches App (cont.) Adding functions: Package android.widget contains the widgets (i.e., GUI components) and layouts that are used in Android GUIs. Class Button of package android.widget represents a simple push button that the user touches to get the app to perform a specific action. You implement interface View.OnClickListener of package android.view to specify the code that should execute when the user touches a Button Overridden Method OnCreate of Class Activity, called by system when: when the app loads if the app’s process was killed by the operating system while the app was in the background, and the app is then restored each time the configuration changes, such as when the user rotates the device or opens/closes a physical keyboard.
Page: 53 Training Android June 2012Favorite Twitter Searches App (cont.) Adding functions: Method getSharedPreferences to get a SharedPreferences object that can read tag/query pairs stored previously (if any) from the "searches" file. The first argument indicates the name of the file that contains the data. The second argument specifies the accessibility of the file and can be set to one of the following options: MODE_PRIVATE— The file is accessible only to this app. In most cases, you’ll use this constant as the second argument to getSharedPreferences. MODE_WORLD_READABLE— Any app on the device can read from the file. MODE_WORLD_WRITABLE— Any app on the device can write to the file.
Page: 54 Training Android June 2012Favorite Twitter Searches App (cont.) AndroidManifest.xml For complete information, refer to this page: www.developer.android.com/guide/topics/manifest/manif est-intro.html
Page: 55 Training Android June 2012Favorite Twitter Searches App (cont.)
Page: 56 Training Android June 2012 Flag Quiz Game AppObjectives:Assets, AssetManager, Tweened Animations, Handler, Menusand Logging Error Messages.Use an AssetManager to get a list of all assets in an app.Use random-number generation to vary flag choices.Use a Drawable to display a flag image in an ImageView.Use a Handler to schedule a future action.Use an ArrayList to hold collections of items and aHashMap to hold name–value pairs.Override Activity’s onCreateOptionsMenu method to create aMenu and MenuItems that enable the user to configure theapp’s options.Use Android’s logging mechanism to log error messages.
Page: 57 Training Android June 2012 Flag Quiz Game App (cont.) Introduction:“The Flag Quiz Game app tests the user’s ability to correctlyidentify country flags. Initially, the app presents the user with aflag image and three possible answers—one matches the flagand the others are randomly selected, nonduplicated incorrectanswers. The app displays the user’s progress throughout thequiz, showing the question number (out of 10) in a TextViewabove the current flag image.”
Page: 58 Training Android June 2012Flag Quiz Game App (cont.)
Page: 59 Training Android June 2012 Flag Quiz Game App (cont.)Technologies Overview:Using the App’s assets Folder: the assets folder may contain files of anytype that can be organized in subfolders—we maintain the flag images foreach region in a separate subfolder. Files in the assets folders are accessedvia an AssetManager (package android.content.res), which can provide alist of all of the file names in a specified subfolder of assets and can beused to access each asset.Using a Menu to Provide App Options: override Activity’sonCreateOptionsMenu method and add the options to the Menu that themethod receives as an argument. Activity methodonOptionsItemSelected is called to respond to the selection.Using a Handler to Execute a Runnable in the Future: . Handler methodpostDelayed receives as arguments a Runnable to execute and a delay inmilliseconds.
Page: 60 Training Android June 2012 Flag Quiz Game App (cont.)Technologies Overview (cont.):Animating the Flag When an Incorrect Choice Is Touched:AnimationUtils static method loadAnimation to load the animation froman XML file that specifies the animation’s options. We also specify thenumber of times the animation should repeat with Animation methodsetRepeatCount and perform the animation by calling View methodstartAnimation (with the Animation as an argument) on the ImageView.Logging Exception Messages with Log.e: When exceptions occur, youcan log them for debugging purposes with Android’s built-in loggingmechanism, which uses a circular buffer to store the messages for a shorttime. Android provides class Log (package android.util) with several staticmethods that represent messages of varying detail.Java Data Structures: ArrayList<String>, Map<String, Boolean>,Set<String>
Page: 61 Training Android June 2012 Flag Quiz Game App (cont.)Building the App GUI:Main.xml Linear Layout
Page: 62 Training Android June 2012 Flag Quiz Game App (cont.)colors.xml & dimen.xml:
Page: 63 Training Android June 2012 Flag Quiz Game App (cont.)string.xml:
Page: 64 Training Android June 2012Flag Quiz Game App (cont.)
Page: 65 Training Android June 2012 Flag Quiz Game App (cont.)Study more:View animations to create a shake effect that consists of threeanimations in an animation set a collection of animations which make upa larger animation. Animation sets may contain any combination oftweened animations— alpha (transparency), scale (resize), translate(move) and rotate.android:fromXDelta attribute is the View’s offset when the animationstarts and the android:toXDelta attribute is the View’s offset when theanimation ends. These attributes can have absolute values (in pixels) a percentage of the animated View’s size a percentage of the animated View’s parent’s sizeThe android:duration attribute specifies how long the animation lasts inmilliseconds.android:startOffset attribute to specify the number of milliseconds intothe future at which an animation should begin.
Page: 66 Training Android June 2012 Flag Quiz Game App (cont.)Building the AppAndroidManifest.xml:
Page: 67 Training Android June 2012 Cannon Game AppObjectives:Create a simple game app that’s easy to code and fun to play.Create a custom SurfaceView subclass and use it to display thegame’s graphics from a separate thread of execution.Draw graphics using Paints and a Canvas.Override Activity’s onTouchEvent to process touch events whenthe user touches the screen or drags a finger on the screen.Use a GestureDetector to recognize more sophisticated usertouch motions, such as double taps.Perform simple collision detection.Add sound to your app using a SoundPool and theAudioManager.Override three additional Activity lifecycle methods.
Page: 68 Training Android June 2012 Cannon Game App (cont.) Introduction:“The Cannon Game app challenges you to destroy a seven-piece target before a ten-second time limit expires. The gameconsists of four visual components—a cannon that you control,a cannonball, the target and a blocker that defends the target.You aim the cannon by touching the screen—the cannon thenaims at the touched point. The cannon fires a cannonball whenyou double-tap the screen. At the end of the game, the appdisplays an AlertDialog indicating whether you won or lost, andshowing the number of shots fired and the elapsed time”
Page: 69 Training Android June 2012Cannon Game App (cont.)
Page: 70 Training Android June 2012Cannon Game App (cont.)
Page: 71 Training Android June 2012 Cannon Game App (cont.)Technologies OverviewDefining String Formatting Resources in strings.xmlAttaching a Custom View to a LayoutUsing the Resource Folder rawActivity Lifecycle Methods onPause and onDestroy: Method onPause is called for the current Activity when another activity receives the focus, which sends the current activity to the background. We use onPause to suspend game play so that the game does not continue executing when the user cannot interact with it. When an Activity is shut down, its onDestroy method is called. We use this method to release the app’s sound resources.Overriding Activity Method onTouchEvent
Page: 72 Training Android June 2012 Cannon Game App (cont.)Technologies Overview (cont.)GestureDetector and SimpleOnGestureListener: A GestureDetector allows an app to react to more sophisticated user interactions such as flings, double-taps, long presses and scrolls. Your apps can respond to such events by implementing the methods of the GestureDetector. GestureDetector.SimpleOnGestureListener is an adapter class that implements all the methods of these two interfaces, so you can extend this class and override just the method(s) you need from these interfaces.Adding Sound with SoundPool and AudioManagerFrame-by-Frame Animation with Threads, SurfaceView andSurfaceHolderSimple Collision DetectionDrawing Graphics Using Paint and Canvas
Page: 73 Training Android June 2012 Cannon Game App (cont.)Building App’s GUI and resource files:
Page: 74 Training Android June 2012 Cannon Game App (cont.)Building App’s GUI and resource files (cont.):
Page: 75 Training Android June 2012 Cannon Game App (cont.)Building App’s GUI and resource files (cont.):The notation 1$ in %1$.1f (line 5) indicates that the first argument afterthe format String should replace the format specifier %1$d. Similarly,%2$.1f indicates that the second argument after the format String shouldreplace the format specifier %2$.1f.Adding functions (regarding to instructors)
A particular slide catching your eye?
Clipping is a handy way to collect important slides you want to go back to later.