Top Banner
Android Programming Student Workbook Evaluation Copy
84

Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Oct 06, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

AndroidProgramming

Student Workbook

Evaluation Copy

Page 2: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Page ii Rev 2.1.1 © 2012 ITCourseware, LLC

Android Programming

Android ProgrammingJamie Romero and Rob Roselius

Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Editor: Ginny Jaranowski

Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of thisworkbook, and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2012 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.(303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.

Evaluation Copy

Page 3: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

© 2012 ITCourseware, LLC Rev 2.1.1 Page iii

android Programming

Contents

Chapter 1 - Course Introduction ........................................................................................................... 11

Course Objectives .......................................................................................................................... 12Course Overview ........................................................................................................................... 14Using the Workbook ...................................................................................................................... 15Suggested References ..................................................................................................................... 16

Chapter 2 - Getting Started ................................................................................................................... 19

Android Overview .......................................................................................................................... 20Android Architecture ...................................................................................................................... 22The Dalvik VM .............................................................................................................................. 24Android Components ..................................................................................................................... 26Android Development Environment ................................................................................................. 28A Simple Android Application ......................................................................................................... 30The Android Emulator ..................................................................................................................... 32User Interface Layouts .................................................................................................................... 34Android Event Handlers .................................................................................................................. 36LogCat ........................................................................................................................................... 38Labs ............................................................................................................................................... 40

Chapter 3 - Activities ............................................................................................................................ 43

Activities ........................................................................................................................................ 44Creating an Activity ......................................................................................................................... 46Activity Lifecycle ............................................................................................................................ 48Callback Methods .......................................................................................................................... 50Resource Conservation ................................................................................................................... 52Intents ............................................................................................................................................ 54AndroidManifest.xml ...................................................................................................................... 56Packaging ....................................................................................................................................... 58Labs ............................................................................................................................................... 60

Evaluation Copy

Page 4: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Page iv Rev 2.1.1 © 2012 ITCourseware, LLC

Android Programming

Chapter 4 - Resources .......................................................................................................................... 63

Resources ...................................................................................................................................... 64Alternative Resources ..................................................................................................................... 66R.java ............................................................................................................................................ 68String Resources ............................................................................................................................. 70String Arrays .................................................................................................................................. 72Boolean and Integer Resources ....................................................................................................... 74Color and Dimension Resources ..................................................................................................... 76Style Resources .............................................................................................................................. 78Image Resources ............................................................................................................................ 80System Resources .......................................................................................................................... 82Localization .................................................................................................................................... 84Format Strings ................................................................................................................................ 86Labs ............................................................................................................................................... 88

Chapter 5 - Views and Event Handlers .................................................................................................. 91

Views and ViewGroups .................................................................................................................. 92Common Properties ........................................................................................................................ 94Text View ....................................................................................................................................... 96Edit Text ......................................................................................................................................... 98TextChanged Events ..................................................................................................................... 100Button .......................................................................................................................................... 102Check Box and Toggle Button ...................................................................................................... 104Radio Group and Radio Buttons ................................................................................................... 106DatePicker ................................................................................................................................... 108ProgressBar and RatingBar ........................................................................................................... 110Threads and Handlers ................................................................................................................... 112AsyncTask ................................................................................................................................... 114Labs ............................................................................................................................................. 116

Chapter 6 - Layouts ........................................................................................................................... 119

Layouts ........................................................................................................................................ 120LinearLayout ................................................................................................................................ 122FrameLayout ................................................................................................................................ 124RelativeLayout .............................................................................................................................. 126TableLayout ................................................................................................................................. 128Combining Layouts ....................................................................................................................... 130

Evaluation Copy

Page 5: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

© 2012 ITCourseware, LLC Rev 2.1.1 Page v

android Programming

Scrolling ....................................................................................................................................... 132Screen Orientation Changes .......................................................................................................... 134Graphical Layout Tool .................................................................................................................. 136Labs ............................................................................................................................................. 138

Chapter 7 - Dialogs ............................................................................................................................ 141

Toast ............................................................................................................................................ 142Custom Toast ............................................................................................................................... 144Dialogs ......................................................................................................................................... 146Dismissing a Dialog ....................................................................................................................... 148AlertDialog ................................................................................................................................... 150AlertDialog Buttons ...................................................................................................................... 152AlertDialog Items .......................................................................................................................... 154Custom Dialogs ............................................................................................................................ 156ProgressDialog ............................................................................................................................. 158DatePickerDialog ......................................................................................................................... 160Labs ............................................................................................................................................. 162

Chapter 8 - Menus ............................................................................................................................. 165

Menus and Menu Items ................................................................................................................ 166OptionsMenu ............................................................................................................................... 168Reacting to Menu Item Selections ................................................................................................. 170ContextMenu ............................................................................................................................... 172Submenus ..................................................................................................................................... 174CheckBoxes and Radio Buttons in Menu Items ............................................................................. 176Labs ............................................................................................................................................. 178

Chapter 9 - Intents and Broadcast Receivers ....................................................................................... 181

Android Components ................................................................................................................... 182Explicit Intents .............................................................................................................................. 184Passing Extra Data to an Intent ...................................................................................................... 186Activities with Results ................................................................................................................... 188Implicit Intents .............................................................................................................................. 190Implicit Intents (cont'd) ................................................................................................................ 192Intent Filters ................................................................................................................................. 194Intent Filter Actions and Categories ............................................................................................... 196Intent Filter Data ........................................................................................................................... 198

Evaluation Copy

Page 6: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Page vi Rev 2.1.1 © 2012 ITCourseware, LLC

Android Programming

Broadcast Receivers ..................................................................................................................... 200Registering Broadcast Receivers Programmatically ........................................................................ 202Registering Broadcast Receivers via the Manifest ........................................................................... 204Broadcasting Intents ..................................................................................................................... 206Labs ............................................................................................................................................. 208

Chapter 10 - Services ......................................................................................................................... 211

What is a Service? ........................................................................................................................ 212Defining a Service: Extend IntentService ........................................................................................ 214Defining a Service: Extend Service ................................................................................................ 216Registering and Starting a Service .................................................................................................. 218Stopping a Service ........................................................................................................................ 220Creating a Bound Service ............................................................................................................. 222Binding to a Service ...................................................................................................................... 224Remote Bound Services ................................................................................................................ 226Call a Remote Service .................................................................................................................. 228Service Lifecycle .......................................................................................................................... 230Labs ............................................................................................................................................. 232

Chapter 11 - Notifications ................................................................................................................... 235

Notifications ................................................................................................................................. 236Notification ................................................................................................................................... 238Pending Intents ............................................................................................................................. 240NotificationManager ..................................................................................................................... 242Updating a Notification ................................................................................................................. 244Notification Fields ......................................................................................................................... 246Labs ............................................................................................................................................. 248

Chapter 12 - Data Storage: Preferences and Files ............................................................................... 251

The Android File System............................................................................................................... 252Preferences .................................................................................................................................. 254Creating Preferences ..................................................................................................................... 256Reading Preferences ..................................................................................................................... 258Updating and Deleting Preferences ................................................................................................ 260Using PreferenceScreen ................................................................................................................ 262Manage Preferences with PreferenceActivity ................................................................................. 264Working with Files ........................................................................................................................ 266

Evaluation Copy

Page 7: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

© 2012 ITCourseware, LLC Rev 2.1.1 Page vii

android Programming

openFileInput() and openFileOutput() ........................................................................................... 268The cache Directory ..................................................................................................................... 270External Storage ........................................................................................................................... 272Raw Resource Files ...................................................................................................................... 274Labs ............................................................................................................................................. 276

Chapter 13 - Data Storage: SQLite Database ..................................................................................... 281

SQLite ......................................................................................................................................... 282Android SQLite Classes ............................................................................................................... 284Executing SQL Statements ............................................................................................................ 286The rawQuery() and query() Methods ........................................................................................... 288Cursors ........................................................................................................................................ 290Managed Cursors ......................................................................................................................... 292Encapsulate Data Access with an Adapter ..................................................................................... 294Using SQLiteOpenHelper ............................................................................................................. 296Managing Database Upgrades ...................................................................................................... 298Inserting and Updating Data .......................................................................................................... 300Deleting Data ................................................................................................................................ 302Transactions ................................................................................................................................. 304Labs ............................................................................................................................................. 306

Chapter 14 - Data Adapter Widgets .................................................................................................... 309

Data-Driven Adapter Controls ...................................................................................................... 310Adapters ...................................................................................................................................... 312ArrayAdapter ............................................................................................................................... 314CursorAdapter ............................................................................................................................. 316SimpleCursorAdapter ................................................................................................................... 318ListView ....................................................................................................................................... 320ListActivity ................................................................................................................................... 322AdapterView Events ..................................................................................................................... 324Gallery and GridView ................................................................................................................... 326Spinner ......................................................................................................................................... 328AutoCompleteTextView................................................................................................................ 330The ViewHolder Pattern ............................................................................................................... 332Labs ............................................................................................................................................. 334

Evaluation Copy

Page 8: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Page viii Rev 2.1.1 © 2012 ITCourseware, LLC

Android Programming

Chapter 15 - Sharing Data with Content Providers .............................................................................. 337

Content Providers ......................................................................................................................... 338Content URIs ............................................................................................................................... 340Built-In Content Providers ............................................................................................................ 342Contacts ....................................................................................................................................... 344Sharing Your App's Data ............................................................................................................... 346Registering Your Content Provider ................................................................................................. 348Labs ............................................................................................................................................. 350

Chapter 16 - Location-Based Services ............................................................................................... 353

Location-Based Services .............................................................................................................. 354LocationManager and LocationListener ......................................................................................... 356Registering a LocationListener ....................................................................................................... 358Location ....................................................................................................................................... 360Permissions .................................................................................................................................. 362Determining Distance and Bearing ................................................................................................. 364Geocoding and Reverse Geocoding .............................................................................................. 366Proximity Alerts ............................................................................................................................ 368Using Google's Map Service ......................................................................................................... 370Displaying a Google Map with MapView ...................................................................................... 372MapController and GeoPoint ........................................................................................................ 374Overlays ....................................................................................................................................... 376Adding Overlays on a Map ........................................................................................................... 378Labs ............................................................................................................................................. 380

Chapter 17 - Publishing an Application ................................................................................................ 383

Publishing ..................................................................................................................................... 384Packaging and Signing .................................................................................................................. 386Distribution ................................................................................................................................... 388Updates ....................................................................................................................................... 390

Index .................................................................................................................................................. 393

Evaluation Copy

Page 9: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

© 2012 ITCourseware, LLC Rev 2.1.1 Page ix

android Programming

Evaluation Copy

Page 10: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Page x Rev 2.1.1 © 2012 ITCourseware, LLC

Android Programming

Evaluation Copy

Page 11: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 19

Chapter 2 - Getting Started

Objectives

Describe the Android architecture andapplication development model

Develop and deploy a simple Androidapplication.

Evaluation Copy

Page 12: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 20 Rev 2.1.1 © 2012 ITCourseware, LLC

Android is an open-source mobile operating system that is maintained by theOpen Handset Alliance (OHA).

The OHA consortium is led by Google and is made up of membercorporations from industries such as handset manufacturers, chip makers, and mobile carriers

Android is licensed under the Apache v2 Software License, so there is nocost to use the platform or to develop software for it.

In addition to the base operating system, Android provides middleware andapplications to support core mobile functionality such as camera, phone, andmessaging.

Your Android application can interact and integrate with these coreapplications as well as third-party applications to provide a morecomplete solution to the user, but keep your code more focused.

You can, for example, provide a share button in your application,that when clicked, gives the user the choice of whether to share theinformation via social media, email, messaging, or something else.

You simply specify that you intend to share the message and thechosen application does the rest.

This loose coupling is fundamental to Android applicationdevelopment.

Each major Android update is named after a dessert whose first letter incrementswith each release.

Your application should support the earliest version possible to becompatible with devices that have yet to upgrade to a more recent release.

This course is focused on Android 2.3 – Gingerbread.

Android Overview

Evaluation Copy

Page 13: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 21

Visit the Open Handset Alliance website at http://www.openhandsetalliance.com

Access the Android source code at http://source.android.com

Android version history:

noisreV leveLIPA emaNnoisreV esaeleRetaD

0.1 1 8002/32/9

1.1 2 9002/9/2

5.1 3 ekacpuC 9002/03/4

6.1 4 tunoD 9002/51/9

0.2 5 rialcE 9002/62/01

1.0.2 6 9002/3/21

x.1.2 7 0102/21/1

x.2.2 8 oyorF 0102/02/5

2.3.2,1.3.2,3.2 9 daerbregniG 0102/6/21

+3.3.2 01 1102/9/2

0.3 11 bmocyenoH 1102/22/2

1.3 21 1102/01/5

x.2.3 31 1102/02/9

2.0.4,1.0.4,0.4 41 hciwdnaSmaerCecI 1102/91/01

4.0.4,3.0.4 51 2102/92/3

1.4 61 naeBylleJ 2102/72/6

Evaluation Copy

Page 14: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 22 Rev 2.1.1 © 2012 ITCourseware, LLC

The Android architecture is made up of five layers.

Applications, written in Java, form the highest layer.

This layer contains both the core applications, such as the calendar,as well as applications you add to your device.

The Application Framework consists of services that allow applicationsto interact with the Android environment.

Your applications can access the same framework services that thecore applications use.

Use the Notification Manager, for example, to add messages to thestatus bar.

The Android Runtime is made up of the Core Libraries as well as theDalvik Virtual Machine (VM).

The Core Libraries contain a subset of the Java API libraries plusAndroid specific packages.

Run your Android applications on the Dalvik VM which has beendesigned for embedded use.

The Libraries provide foundational capabilities such as support for audio,video, and graphics.

The Linux 2.6 Kernel provides system services like memory and processmanagement as well as drivers to interact with the underlying hardware.

Android Architecture

Evaluation Copy

Page 15: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 23

Adapted from Android Developers Dev Guide, "What is Android", http://developer.android.com/guide/basics/what-is-android.html (accessedJune 4, 2012)

The Core Libraries include a subset of the Java SE libraries. Notably missing are the AWT, Swing, andRMI packages. Android also supplements the remaining Java SE libraries with dozens of Android specificpackages.

Applications

Home

Application Framework

Contacts Phone Browser ...

Project Manager TelephonyManager

ResourceManager

LocationManager

NotificationManager

Activity Manager WindowManager

ContentManager View System

Android Runtime

Core Libraries

Dalvik VirtualMachine

Surface Manager MediaFramework SQLite

OpenGL ES FreeType WebKit

Libraries

SQL SSL libc

Display Driver

Linux Kernel

Camera Driver Flash MemoryDriver

Binder (IPC)Driver

Keypad Driver WiFi Driver Audio Driver PowerManagement

Evaluation Copy

Page 16: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 24 Rev 2.1.1 © 2012 ITCourseware, LLC

You write your Android applications in the Java language and execute themwithin the Dalvik Virtual Machine.

Dalvik does not read Java .class files, but rather .dex (Dalvik Executable)files.

Use the dx tool that comes with the Android SDK to translate Javabyte code into optimized .dex files.

Dalvik is designed so that multiple instances of the VM can efficiently runsimultaneously.

A Just In Time (JIT) compiler was added to the Dalvik VM in theFroyo release to further enhance performance.

Dalvik relies on the underlying kernel to handle memory management,process isolation, and threading.

By default, each of your Android applications runs within its own process with aunique user and group ID, providing a secure sandbox.

Each process runs its own VM to isolate one application from another.

The permissions of an application’s files are set so that only the processitself can access them.

You can configure an application to request permission to accessadditional data such as the camera or the user’s contacts.

The Dalvik VM

Evaluation Copy

Page 17: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 25

Dalvik was written by Dan Bornstein who named it after the Dalvik, Iceland where his ancestors once lived.

An Android application can choose to share data with other applications with a service or a contentprovider.

Each Android application can describe what permissions it requires in order to execute by adding zero ormore <uses-permissions> entries to the application’s manifest file. When a user installs an application theywill be prompted as to whether they allow the application to access the resources listed within the <uses-permissions> tags.Evaluation Copy

Page 18: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 26 Rev 2.1.1 © 2012 ITCourseware, LLC

Android defines four components that serve as building blocks for applicationdevelopment.

An activity is a screen displaying user interface widgets and/or graphicalcontent.

Most applications are made up of multiple independent activities.

A service handles long-running background tasks, without displaying auser interface.

Services can be either started and run until completion, or bound toan activity to take part in inter-process communications.

Broadcast receivers are notified of system events such as battery low orkeyboard extended.

You can also create a broadcast receiver to listen for your owncustom events.

A content provider manages data that other applications can query andupdate.

The data is typically stored in the file system or in a SQLitedatabase.

Android Components

Evaluation Copy

Page 19: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 27

While most Android applications use only one or two of the four components, there may be scenarioswhere you can make use of all four. For example, if you were creating a weather application, you may usethe following components:

Activity – You can use an activity to create a screen that displays current weather data for a particular cityand another screen to allow the user to select the city to display weather data for.

Service – You can create a service as a background task that downloads weather information from a serveron the Internet.

Broadcast Receiver – You can use a broadcast receiver to react to temperature change events and updatethe status bar with the current temperature. Perhaps the service could broadcast the event in the first place.

Content Provider – You can create a content provider to expose historical weather data to otherapplications

Evaluation Copy

Page 20: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 28 Rev 2.1.1 © 2012 ITCourseware, LLC

In order to develop Android applications you should install both the AndroidSDK as well as the Android Developer Tools (ADT) Eclipse Plugin.

These tools assume a Java Software Development Kit version 6 as well asEclipse 3.6+.

You can install Eclipse Classic, Eclipse IDE for Java Developers, orEclipse IDE for Java EE Developers.

The Android SDK provides the tools necessary to develop Androidapplications.

The SDK Starter Package that you can download fromdeveloper.android.com is incomplete and must be supplemented with theAndroid SDK Platform-tools and at least one version of the Androidplatform.

This makes installing the SDK a multi-step process:

Download and install the SDK Starter Package.

Run the Android SDK Manager by executing "SDK Manager.exe."

Within the Android SDK Manager, choose to download and installthe Android SDK Platform-tools as well as the appropriate Androidplatform based on the API that you wish to develop software for.

The ADT Eclipse Plugin makes it easy for you to create, compile, debug, anddeploy Android applications within the Eclipse IDE.

Install the ADT Plugin with the Eclipse Update Manager under the EclipseHelp | Install New Software... menu item.

Don’t forget to point the ADT at your Android SDK within Window |Preferences | Android.

Android Development Environment

Evaluation Copy

Page 21: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 29

The Android SDK and ADT Eclipse Plugin should have already been installed on your system, but thefollowing steps are provided for your reference. Please note that these steps assume that both the JavaDevelopment Kit and Eclipse are already installed.

1. Download the most recent Android SDK executable file (for example: installer_r20-windows.exe)from http://developer.android.com/sdk/index.html.

2. Run the executable to install the SDK.3. Run SDK Manager.exe. Select the following three checkboxes: Android SDK Platform-tools

beneath Tools, SDK Platform beneath Android 2.3.3 (API 10), and Android Support Libraryunder Extras. Uncheck any other checkboxes.

4. Click the Install 3 packages... button.5. Click the Install button on the Choose Packages to Install window.6. When the installation completes, dismiss any open windows.7. Start Eclipse.8. Select Help | Install New Software...9. Click the Add... button in the upper right hand corner of the Available Software window.10. In the Add Repository window, type "ADT Plugin" for the Name and "https://dl-ssl.google.com/

android/eclipse/" for the Location and click OK.11. Back in the Available Software window, select the checkbox next to Developer Tools and click

Next.12. Click Next on the Install Details page.13. On the Review Licenses page, accept the license agreement and click Finish.14. The Installing Software window will display the installation progress. If you get a security warning,

click OK.15. Upon completion of the installation, restart Eclipse.16. When Eclipse restarts, go to Window | Preferences | Android.17. Set the SDK Location to the location in which you installed the SDK in step 2.18. Choose OK.

For more about the Android SDK including detailed setup instructions, see:http://developer.android.com/sdk/index.html

Hands On:Import the supporting files for this class into Eclipse by following the steps below.

1. Start Eclipse. Your instructor will tell you where to find Eclipse and what workspace to use.

2. In Eclipse, choose File | Import... | General | Existing Projects into Workspace and click Next.

3. Choose Select archive file and browse to the location of the student zip file. Your instructor will tellyou where to find the student zip file.

4. Click Finish.

Evaluation Copy

Page 22: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 30 Rev 2.1.1 © 2012 ITCourseware, LLC

The ADT plugin makes it easy to create a new Android application by using theNew Android Project wizard within the Eclipse IDE.

As part of the wizard, you can generate a simple activity within a specifiedpackage.

Each Android application is made up of multiple files and directories within anEclipse project.

Add the Java source code for your application to packages embeddedwithin the src directory.

Place resources you plan to use in your code, such as images and strings,within the res directory.

Place an XML layout file for each of your activities within the res/layout directory

Include any string resources your application depends on within theres/values directory.

Configure your application within AndroidManifest.xml.

Eclipse and the SDK also generate extra files to support your application:

The SDK creates the gen directory and the embedded R.java filethat Android relies on to resolve resource references.

The bin directory contains the generated classes.dex file as well asan Application Package (.apk) file which contains a zipped upversion of your application that can be distributed to an Androiddevice.

The project.properties file identifies the target API level that yourapplication supports.

A Simple Android Application

Evaluation Copy

Page 23: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 31

Hands On:Create a new Android project within Eclipse by following the steps below.

1. In Eclipse choose File | New | Project...

2. Choose Android | Android Application Project and click Next

3. On the New Android Application screen:a. Application Name: HelloAndroidb. Project Name: HelloAndroidc. Package Name: com.example.hellod. Build SDK: Android 2.3.3 (API 10)e. Minimum Required SDK: API 8: Android 2.2 (Froyo)f. Uncheck Create custom launcher icong. Click Next

4. On the Create Activity screen:a. Choose Blank Activityb. Click Next

5. On the New Blank Activity screen:a. Activity Name: HelloAndroidActivityb. Layout Name: mainc. Title: HelloAndroidActivityd. Click Finish

6. Click on the various directories and files that were created to get an idea of what a simple Androidproject look like. Your instructor will go into much greater detail about each of these files/directorieslater in the class. At a minimum, do the following:

a. Open src/com.example.hello/HelloAndroidActivity.java to view a simple activity.

b. Open res/layout/main.xml to view the layout file for the above activity. Click the main.xml tab atthe bottom of the editor to switch from the Graphical Layout view to an XML editor.

c. Open res/values/strings.xml to view the strings resource file for this application. Click thestrings.xml tab at the bottom of the editor to switch from the Resources view to an XML editor.

i. Modify the string entry named hello_world to contain the value Hello Android World!

d. Open AndroidManifest.xml to view the configuration for this application. Click theAndroidManifest.xml tab at the bottom of the editor to switch from the Manifest view to an XMLeditor.

Evaluation Copy

Page 24: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 32 Rev 2.1.1 © 2012 ITCourseware, LLC

The Android Emulator

The most useful tool included in the SDK is an Android emulator that you canuse to test your applications without having to deploy to an actual hardwaredevice.

The emulator provides most of the functionality that you would have witha physical device including the ability to click on navigation and controlkeys.

You can configure multiple different emulators using Android VirtualDevice (AVD) configurations.

AVDs allow you to test on both Android 2.2 and 2.3, for example.

Configure and start an emulator using the ADT provided Window | AVDManager menu within Eclipse.

Click the New... button to create an AVD giving it a name and target APIlevel.

You can also specify the size of a virtual SD Card.

Click the Start... button to launch an AVD from Eclipse.

Starting a new AVD may take a long time depending upon yourcomputer’s hardware specifications.

Once the AVD starts, pull the lock icon to the right to unlock thescreen.

To run an Android application within the emulator, simply click on the Run |Run Eclipse menu and choose to run the application as an Android Application.

If an AVD is already running, your application will be deployed to it,otherwise one will be launched for you.

Evaluation Copy

Page 25: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 33

Hands On:

Create a new AVD configuration and run the Hello Android application by following the steps below:

1. In Eclipse choose Window | AVD Manager

2. Click the New... button to configure a new AVD.

a. Name: MyAVD

b. Target: Android 2.3.3 – API Level 10

c. SD Card Size: 10 MiB

d. Click the Create AVD button.

3. Choose the new AVD in the list and click the Start... button.

a. Click the Launch button.

b. After waiting for some time, the emulator should launch.

c. If the screen is locked, click and drag the lock icon to the right.

4. Run the Hello Android application by choosing the project name in the Package Explorer andclicking on the Run | Run Eclipse menu option.

a. Choose Android Application within the Run As dialog.

b. Click OK

Evaluation Copy

Page 26: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 34 Rev 2.1.1 © 2012 ITCourseware, LLC

User Interface Layouts

A typical Android activity contains both user interface components that displaystatic text as well as dynamic components that allow for user interaction.

Use a TextView component for non-editable text and an EditText foreditable content.

Use a Button to trigger event handling code when the button is pressed.

Define components within the layout XML file specifying at least three attributes.

Define the android:id attribute to provide an identifier that you can use toreference the component in code or elsewhere in the layout file.

Set the android:layout_width and android:layout_height to providesizing information for the component.

Use the value match_parent to stretch the component to fill thesame space that the parent component consumes.

Use the value wrap_content to squeeze the component to only fillas much space as it needs to display its contents.

Each component also has more specific attributes that you can use to refine itslook and feel.

Add the android:hint attribute to an EditText component to display ahint to the user as to what they should type into the text box.

Add the android:text attribute to any component that can display text todefine its text content.

You can specify a string literal as the value of the attribute or add areference to a predefined string in res/values/strings.xml.

Evaluation Copy

Page 27: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 35

Hands On:

Modify res/layout/main.xml to match the content below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" >

<EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:hint="Please enter your name" />

<Button android:id="@+id/sayHello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/name" android:text="Say Hello" />

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/hello" android:layout_below="@+id/sayHello" />

</RelativeLayout>

Click on the Graphical Layout tab below the editor to see how your components will display when you runthe application within the emulator.

You can use either the Graphical Layout view or the XML editor to modify user interface layouts.

Place the EditText box inthe upper left corner of the

screen.

Place the Button belowthe EditText box.

Place the TextViewbelow the Button.

Evaluation Copy

Page 28: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 36 Rev 2.1.1 © 2012 ITCourseware, LLC

Android activities use listeners, typically defined as inner classes, for their eventhandling code.

A Button, for example, will trigger an onClick event that can be handledby any class that implements the View.OnClickListener interface.

class MyListener implements View.OnClickListener() {public void onClick(View v) {

// Add your code here}

}

Retrieve a reference to the Button object, or any UI component, bycalling the findViewById() method.

Button myButton = (Button) findViewById(R.id.myButton);

Pass in the identifier you specified in the XML layout file using thegenerated R class to access it.

Call the setOnClickListener() method on the Button passing in thelistener object to associate the Button and the event listener.

myButton.setOnClickListener(new MyListener());

Android Event Handlers

Evaluation Copy

Page 29: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 37

Hands On:

Modify src/com.example.hello/HelloAndroidActivity.java to match the content below:

package com.example.hello;

import android.os.Bundle;import android.app.Activity;import android.view.View;import android.widget.*;

public class HelloAndroidActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

// Lookup the button and add a listener for button clicks Button sayHelloButton = (Button) findViewById(R.id.sayHello); sayHelloButton.setOnClickListener(new MyButtonListener()); }

class MyButtonListener implements View.OnClickListener { public void onClick(View v) { // Lookup the gui controls EditText nameEditText = (EditText) findViewById(R.id.name); TextView helloTextView = (TextView)findViewById(R.id.hello);

// Retrieve the name from the EditText box String name = nameEditText.getText().toString(); // Say 'Hello' in the TextView helloTextView.setText("Hello " + name + "!"); } }}

Click the Run | Run menu item in Eclipse to redeploy the application to the emulator. Enter your name inthe EditText box and click the Button to see the application say "Hello" to you.

Evaluation Copy

Page 30: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 38 Rev 2.1.1 © 2012 ITCourseware, LLC

Write messages to the Android logging system using the android.util.Log class.

Call the Log.v(), Log.d(), Log.i(), Log.w(), or Log.e() methods forverbose, debug, information, warning, or error messages, respectively.

Each of these methods takes two String arguments..

Use the first String as a tag that identifies which class or activityinvoked the log call.

Use the second String to pass the actual message to be logged.

Alternatively, you can call the Log.println() method passing a priorityconstant as the first parameter and then the two Strings.

The priority can be (from lowest to highest): VERBOSE,DEBUG, INFO, WARN, ERROR, or ASSERT

.You can add a TAG constant to your class to store the String to pass asthe first parameter to the Log methods.

private static final String TAG = "HelloActivity";

You can view the log messages using the LogCat tool.

Add LogCat to your Eclipse perspective by clicking on Window | ShowView | Other... | Android | LogCat

You can filter the log messages that LogCat displays by priority, tag, andmore.

LogCat

Evaluation Copy

Page 31: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 39

Hands On:

Modify src/com.example.hello/HelloAndroidActivity.java to include the three bold lines below:

package com.example.hello;

import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.*;

public class HelloAndroidActivity extends Activity { private static String TAG = "HelloAndroidActivity";

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

// Lookup the button and add a listener for button clicks Button sayHelloButton = (Button) findViewById(R.id.sayHello); sayHelloButton.setOnClickListener(new MyButtonListener()); }

class MyButtonListener implements View.OnClickListener { public void onClick(View v) { // Lookup the gui controls EditText nameEditText = (EditText) findViewById(R.id.name); TextView helloTextView = (TextView)findViewById(R.id.hello);

// Retrieve the name from the EditText box String name = nameEditText.getText().toString(); // Say 'Hello' in the TextView helloTextView.setText("Hello " + name + "!");

// Log the name Log.v(TAG, "name = " + name); } }}

Click Window | Show View | Other... | Android | LogCat in Eclipse to enable the LogCat view.Redeploy the application to the emulator. Enter your name in the EditText box and click the Button.Check the LogCat window to see your output.

Use Log.v() to logverbose messages.

Evaluation Copy

Page 32: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 40 Rev 2.1.1 © 2012 ITCourseware, LLC

Labs

Solution code for labs and is available in the HelloAndroid2 project.

Change the HelloAndroid application that you created during the lecture to use different text for theButton label and the EditText hint.

Change the application again so that the greeting says "Hi" rather than "Hello" before your name.

Solution code for labs and is available within the Converter project.

Create an Android project that converts between degrees fahrenheit and degrees celsius. Have theuser type the fahrenheit temperature in an EditText box. When the user clicks on a Button, have alistener update a TextView to display the converted value.

(Optional) Add a button to convert from celsius to fahrenheit, as well.

Evaluation Copy

Page 33: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 2 Getting Started

© 2012 ITCourseware, LLC Rev 2.1.1 Page 41

Fahrenheit = (9.0/5.0) * (Celsius + 32)

Celsius = (5.0/9.0) * (Fahrenheit -32)

Evaluation Copy

Page 34: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 42 Rev 2.1.1 © 2012 ITCourseware, LLC

Evaluation Copy

Page 35: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 251

Chapter 12 - Data Storage: Preferences andFiles

Objectives

Store and retreive application data fromprivate and shared preferences.

Store and retrieve application data frominternal and external files.

Read raw data from resource files.

Evaluation Copy

Page 36: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 252 Rev 2.1.1 © 2012 ITCourseware, LLC

¨

Each app has a home directory in the internal Android filesystem that is privateto the application.

This location is associated with your app’s Context; you never need tospecify the full pathname (which is /data/data/packagename/ by default,but conceivably could differ on vendors' Android platforms.)

Your app can create files and store data in various forms under this location.

Preferences - a collection of simple key-value pairs

Files - arbitrary text or binary data

Activity.getPreferences(), Context.getSharedPreferences(), andPreferenceManager.getDefaultSharedPreferences() return references topreference repositories - files under the app’s internal storage location.

These files are in /data/data/packagename/shared_prefs/.

Context.openFileOutput() and Context.openFileInput() create and accessfiles under this location.

Context.getFilesDir() returns the path to the subdirectory for these files,normally /data/data/packagename/files/.

Context.getCacheDir() returns the path to your app’s cache directory.

If an external media (SD) card is installed, your app can create directories andfiles on that as well.

If your app has permissions to use external storage, it can create its ownarbitrary directory on the SD card.

It can also access a standard directory like /Music/, /Pictures/,/Download/, etc.

Your app can also use the external storage for cache files.

The Android File System

Evaluation Copy

Page 37: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 253

Default locations for application-specific internal storage and for an external storage device like an SD cardcould conceivably vary between Android device vendors.

* Use getFilesDir() to retrieve a reference to the private internal file location used by openFileOutput()etc.* Use getCacheDir() to retrieve a reference to the private internal cache file location.* Use getExternalFilesDir() to get the path to the external storage device, and usegetExternalStorageState() to make sure it’s mounted and available before trying to access it.* Use getExternalCacheDir() to cache files on external storage.* Use Environment.getExternalStoragePublicDirectory() for standard public external storagedirectories like /Music/, /Pictures/, /Download/, etc., and pass which directory you need, such asEnvironment.DIRECTORY_MUSIC, Environment.DIRECTORY_PICTURES, orEnvironment.DIRECTORY_DOWNLOADS.

Evaluation Copy

Page 38: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 254 Rev 2.1.1 © 2012 ITCourseware, LLC

Preferences are key-value pairs stored under your package’s internal storagedirectory’s shared_prefs subdirectory.

As the name suggests, preferences are suitable for storing simple,unstructured data items like application preferences and settings.

Preferences are easy to create, access, and manage.

SharedPreferences can be:

Private to a specific Activity, with the preference file name matching theActivity’s name.

SharedPreferences prefs= getPreferences(MODE_PRIVATE);

Accessible by your entire app; the preference file has a programmer-assigned name.

SharedPreferences prefs= getSharedPreferences("MyPrefs", MODE_PRIVATE);

Accessible by your entire app, in a package default preference file.

SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(ctx);

This form is recommended for most apps.

A SharedPreferences.Editor object provides the programmatice interface formodifying preference values.

SharedPreferences prefs = getPreferences(MODE_PRIVATE);SharedPreferences.Editor ed = prefs.edit();ed.putString("Username","dobbs");ed.putFloat("PI", 3.1415926535F);

Preferences

Evaluation Copy

Page 39: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 255

You can use onSaveInstanceState() to preserve important application state over the course of your app’slifecycle. In onSaveInstanceState() you add key-value pairs to a Bundle. If the system needs to kill youractivity, it will preserve the Bundle and pass it back to your activity’s onCreate() when the activity is re-launched.

Preferences allow you to persist application state in the filesystem for use every time you app is launched,including after system reboots.Evaluation Copy

Page 40: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 256 Rev 2.1.1 © 2012 ITCourseware, LLC

Context.getSharedPreferences() takes a file name and an operating mode.

prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);

The operating mode determines if other apps can access it.

Use MODE_PRIVATE unless you specifically want to allow other appsto read (MODE_WORLD_READABLE) or modify(MODE_WORLD_WRITABLE) your app’s preferences.

Activity.getPreferences() takes an operating mode, and callsContext.getSharedPreferences() using the activity name as the file name.

prefs = getPreferences(MODE_PRIVATE);

SharedPreferences.Editor provides methods for adding key-value pairs.

SharedPreferences.Editor ed = prefs.edit();

putBoolean(String key, boolean value); putFloat(String key, float value); putInt(String key, int value); putLong(String key, long value); putString(String key, String value); putStringSet(String key, Set<String> value);

Call SharedPreferences.Editor’s apply() or commit() method to write yoursettings to the preferences file.

ed.putString("Username","dobbs");ed.putFloat("PI", 3.1415926536F);ed.commit();

commit() writes your current editor’s contents to the disk synchronouslyand returns true if it succeeds.

apply() begins writing your editor’s contents to the disk asynchronouslyand immediately returns void.

Creating Preferences

Evaluation Copy

Page 41: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 257

Android stores preferences as an XML file, under /data/data/packagename/shared_prefs/:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><float name="PI" value="3.1415927" /><string name="Username">dobbs</string></map>

You don’t need to know the format of the file, or write any XML-parsing code to open it, in order to accessthe data in it. However you can easily examine these files during development and debugging.

The putType() methods return a reference to the editor, allowing one-line preference setting and committing:

prefs.edit().putString(NAME_PREF_KEY, eventName).commit();

or even:

PreferenceManager.getDefaultSharedPreferences(this).edit().putString(NAME_PREF_KEY, eventName).commit();

Evaluation Copy

Page 42: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 258 Rev 2.1.1 © 2012 ITCourseware, LLC

Reading Preferences

Accessors for preferences mirror the various put() methods, taking a defaultvalue to return if the key is not found:

getBoolean(String key, boolean defaultValue);getFloat(String key, float defaultValue);getInt(String key, int defaultValue);getLong(String key, long defaultValue);getString(String key, String defaultValue);getStringSet(String key, Set<String> defaultValue);

These methods will throw ClassCastException if they find a valuefor this key that’s not of the correct type.

The getAll() method returns a Map object representing all the key-value pairs inthe preferences file.

SharedPreferences.contains(key) tests for the presence of a key in apreferences store.

To read another app’s preferences:

Make sure the other app created its preferences withMODE_WORLD_READABLE or MODE_WORLD_WRITABLE.

Get a reference to the other app’s Context.

Context otherCtx = createPackageContext("com.otherapp",CONTEXT_IGNORE_SECURITY);

Use the Context to retrieve a reference to the app’s SharedPreferences.

SharedPreferences theirPrefs= otherCtx.getSharedPreferences("TheirPrefs",

MODE_WORLD_READABLE); theirPrefs.getString("favoriteColor", "green");

Evaluation Copy

Page 43: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 259

Resource IDs are generated dynamically. When saving app resources as preferences, save the resourceentry name; after getting the name from your preferences, use the name to retrieve the resource id.

Countdown3/src/com/example/countdown/CountdownActivity.javaprivate String eventName = "Christmas";private Calendar eventCalendar = Calendar.getInstance();private SharedPreferences prefs;private static final String DATE_PREF_KEY = "EVENT_TIME";private static final String NAME_PREF_KEY = "EVENT_NAME";private static final String BG_PREF_KEY = "BG_COLOR";private static final String FG_PREF_KEY = "FG_COLOR";@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); prefs = PreferenceManager.getDefaultSharedPreferences(this); // default to this year's Christmas int thisYear = Calendar.getInstance().get(Calendar.YEAR); eventCalendar = new GregorianCalendar(thisYear, Calendar.DECEMBER, 25); long timeVal = eventCalendar.getTimeInMillis(); timeVal = prefs.getLong(DATE_PREF_KEY, timeVal); eventCalendar.setTimeInMillis(timeVal); eventName = prefs.getString(NAME_PREF_KEY, eventName); setText(); String resName = prefs.getString(FG_PREF_KEY, "fg_color_white"); int resId = getResources().getIdentifier(resName,"id",getPackageName()); changeFGColor(resId); resName = prefs.getString(BG_PREF_KEY, "bg_color_black"); resId = getResources().getIdentifier(resName, "id", getPackageName()); changeBGColor(resId);}... case R.id.bg_color_black: case R.id.bg_color_gray: case R.id.bg_color_blue: case R.id.bg_color_white: item.setChecked(true); changeBGColor(id); prefs.edit().putString(BG_PREF_KEY,getResources().getResourceEntryName(id)).commit(); break; case R.id.fg_color_black: case R.id.fg_color_gray: case R.id.fg_color_blue: case R.id.fg_color_white: item.setChecked(true); changeFGColor(id); prefs.edit().putString(FG_PREF_KEY,getResources().getResourceEntryName(id)).commit(); break; default:...

Save the resource nameas a String preference.

Use the resource name toretrieve the resource id.

Evaluation Copy

Page 44: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 260 Rev 2.1.1 © 2012 ITCourseware, LLC

Updating and Deleting Preferences

To change a preference value use the Editor to put a new value for thepreference key.

Editor.remove() removes a single key-value pair completely.

Editor.clear() clears ALL values from the preferences file..

Don’t forget to commit() (or apply()) after removing or clearingpreferences.

Preferences are simple files with no locking; if two processes edit the samepreferences at the same time, whichever one commits last will overwrite theother’s work.

Create an OnSharedPreferenceChangeListener if your app needs to takeimmediate action when a preference is changed.

Define an instance variable so the listener persists.

private SharedPreferences .OnSharedPreferenceChangeListener prefListener;

Instantiate it, defining its onSharedPreferenceChanged() method.

prefListener = newSharedPreferences.OnSharedPreferenceChangeListener(){

@Overridepublic void onSharedPreferenceChanged(

SharedPreferences SharedPreferences, String key) {setLabelsFromPreferences(context); }

};

Register it to listen for preference changes.

PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(prefListener);

Evaluation Copy

Page 45: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 261

When defining an OnSharedPreferenceChangedListener, use a member variable to retain a reference tothe listener object. If you use an anonymous inner class:

PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener( new

SharedPreferences.OnSharedPreferenceChangeListener(){

public void onSharedPreferenceChanged(...)}

); // don’t do this

... the listener object will be subject to garbage collection when the reference goes out of scope.

Evaluation Copy

Page 46: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 262 Rev 2.1.1 © 2012 ITCourseware, LLC

Using PreferenceScreen

Rather than create your own GUI elements for setting your app’s preferences,you can use PreferenceScreen to present a consistent preferences interface.

android.preference provides pre-built interface classes for editing preferences.

CheckBoxPreferenceEditTextPreferenceDialogPreferenceListPreferenceMultiSelectListPreference

You can organize preferences with PreferenceCategory.

Under res/xml/ (not res/layout/), create a preferences.xml defining aPreferenceScreen containing your preference-setting items.

You can use string or array resources to define options.

You can also implement your own custom Preference subclass.

public class DatePreference extends DialogPreference implements DatePicker.OnDateChangedListener {

private DatePicker datePicker; ... protected void onSetInitialValue(boolean restore, Object defaultValue) { // Load current value from preferences into widget } @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

// Capture new values } @Override protected void onDialogClosed(boolean positiveResult) { // If positiveResult is true, save new value to file

SharedPreferences.Editor editor = getEditor(); editor.putLong(CountdownActivity.DATE_PREF_KEY,

cal.getTimeInMillis()).commit(); }}

Evaluation Copy

Page 47: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 263

Countdown4/res/xml/preferences.xml<?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="Event" android:key="event_info"> <com.example.countdown.DatePreference android:key="EVENT_TIME" android:title="Event Date" android:summary="Count Down To Event Date" /> <EditTextPreference android:key="EVENT_NAME" android:title="Event Name" android:summary="Name of Event" android:defaultValue="" /> </PreferenceCategory> <PreferenceCategory android:title="Color Preferences" android:key="color_prefs"> <ListPreference android:entries="@array/bg_color" android:title="Background Color" android:key="BG_COLOR" android:entryValues="@array/bg_color" android:summary="Color of background" android:defaultValue="bg_color_black" /> <ListPreference android:entries="@array/fg_color" android:title="Foreground Color" android:key="FG_COLOR" android:entryValues="@array/fg_color" android:summary="Color of text" android:defaultValue="fg_color_white" /> </PreferenceCategory></PreferenceScreen>

Countdown4/src/com/example/countdown/CountdownPreferenceActivity.javapackage com.example.countdown;import com.example.countdown.R;import android.os.Bundle;import android.preference.PreferenceActivity;

public class CountdownPreferenceActivity extends PreferenceActivity {@Overridepublic void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.preferences);

}}

Evaluation Copy

Page 48: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 264 Rev 2.1.1 © 2012 ITCourseware, LLC

Manage Preferences with PreferenceActivity

The android.preferences package provides a preferences-managementframework, so you don’t have to build your own GUI just to support yourapp’s preferences.

You can easily create a preference-management interface consistent withother apps and with Android itself.

Launch your PreferenceActivity subclass from your app via a menuoption, button, or whatever.

As with any activity, register it in your Android manifest.

Your PreferenceActivity subclass automatically updates the default preferencesfile for your app when the user interacts with its interface components.

PreferenceManager.getDefaultSharedPreferences() returns areference to the preferences file.

Define the interface components in a preferences.xml file.

PreferenceActivity.addPreferencesFromXml() inflates the interfaceitems.

Any OnSharedPreferenceChangeListeners will be notified when changes aremade.

Evaluation Copy

Page 49: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 265

CheckRegister/res/xml/preferences.xml:<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="Input/Display options" android:key="input_display_options"> <ListPreference android:key="currencySymbol" android:title="Currency Symbol" android:summary="Currency Symbol for input/display" android:defaultValue="$" android:entries="@array/currencySymbol" android:entryValues="@array/currencySymbol" /> </PreferenceCategory></PreferenceScreen>

CheckRegister/src/com/example/checkregister/CheckRegisterPreferenceActivity.java:public class CheckRegisterPreferenceActivity extends PreferenceActivity{ @Override

public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.preferences);

}}

In CheckRegister/AndroidManifest.xml:<activity android:name=".CheckRegisterPreferenceActivity"> <intent-filter> <action android:name="com.example.checkregister.PREFERENCES"></action> <category android:name="android.intent.category.DEFAULT"></category> </intent-filter></activity>

In CheckRegister/src/com/example/checkregister/CheckRegisterActivity.java:@Overridepublic boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem prefItem = menu.add(0,0,0,"Preferences"); prefItem.setIcon(android.R.drawable.ic_menu_preferences); return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0:

startActivity(new Intent("com.example.checkregister.PREFERENCES")); } return true;}

Evaluation Copy

Page 50: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 266 Rev 2.1.1 © 2012 ITCourseware, LLC

Working with Files

Your app can create and manage files in any format it likes - documents, binaryor text data files, etc.

Each app’s context has access to a files/ directory on the device’s internalfilesystem..

getFilesDir() returns a reference (a File object) to this location.

openFileOutput() and openFileInput() operate on this location.

Each app also has a cache/ directory

Files in the application’s cache directory are subject to automatic removalwhen system space is low, or when the user chooses “Clear Cache” in theManage Applications screen.

getCacheDir() returns a reference to this location.

You can create your own subdirectories with getDir().

getDir() returns a File reference to a directory under your application’shome, creating it if necessary.

File mydir = getDir("mydata", MODE_PRIVATE);

The actual directory will be the name you gave, with app_prepended to it.

Use standard Java I/O classes and operations to write, read, and manage thefiles themselves.

Evaluation Copy

Page 51: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 267

Diary/src/com/example/diary/DiaryListActivity.javapublic class DiaryListActivity extends ListActivity { private String[] diaryList; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); diaryList = getFileList(); setContentView(R.layout.diary_list); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, diaryList); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id){ String msg = "Position: " + position + " ID: " + id; Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); Intent diaryEdit = new Intent(this, DiaryActivity.class); diaryEdit.putExtra("FILENAME", diaryList[position]); startActivity(diaryEdit); } private String[] getFileList(){ File diaryDir = getDir(DiaryActivity.DIARY_DIR, MODE_PRIVATE); String[] fileList = diaryDir.list(); return fileList; }}

Evaluation Copy

Page 52: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 268 Rev 2.1.1 © 2012 ITCourseware, LLC

openFileInput() and openFileOutput()

openFileOutput() returns a java.io.FileOutputStream reference to a file underyour app’s files/ folder.

The file will be created if it doesn’t exist.

The operation mode can be:

MODE_PRIVATE (or 0 - this is the default)MODE_APPENDMODE_WORLD_READABLEMODE_WORLD_WRITABLE

From the FileOutputStream you can instantiate whatever output mechanismyou need, such as a BufferedWriter for text or OutputStreamWriter for textor binary data.

openFileInput() returns a java.io.FileInputStream, which you can use via theappropriate java.io class for the data in the file.

Evaluation Copy

Page 53: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 269

Diary/src/com/example/diary/DiaryActivity.java private void diaryLog(String msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timeStamp = sdf.format(new Date()); String logEntry = timeStamp + ": " + msg + "\n"; try { FileOutputStream fos = openFileOutput(LOGFILENAME, MODE_APPEND); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(logEntry, 0, logEntry.length()); osw.close(); } catch (IOException ioe) { Log.e("DiaryActivity:diaryLog", ioe.toString()); } }

Diary/src/com/example/diary/DiaryLogView.javapublic class DiaryLogView extends Activity { private EditText logText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.log_view); logText = (EditText)findViewById(R.id.logText); FileInputStream fis; try { fis = openFileInput(DiaryActivity.LOGFILENAME); FileChannel fc = fis.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); String text = Charset.defaultCharset().decode(bb).toString(); logText.setText(text); } catch (IOException ioe) { Log.e(“DiaryLogView”, ioe.toString()); } }}

Evaluation Copy

Page 54: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 270 Rev 2.1.1 © 2012 ITCourseware, LLC

The cache Directory

The cache directory is intended for temporary files, such as downloaded webcontent, whose removal will not impact application operations.

Android may delete cached files when storage is low.

Use getCacheDir() to get the location of the cache directory for yourapplication.

Create and access files in this location in the normal way.

Cache is not limited nor cleared automatically by the system (except when yourapp is uninstalled).

Your app is responsible for managing the amount of cache space it uses,and removing its cached files to maintain a reasonable limit of storageconsumption.

Your code should check for and remove old cache files whenever addingnew ones (or at some other time), removing them based on age or size orwhatever other criteria make sense.

Evaluation Copy

Page 55: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 271

Evaluation Copy

Page 56: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 272 Rev 2.1.1 © 2012 ITCourseware, LLC

External Storage

“External storage” refers to the built-in or removable media card - SD memory,for example - that provides additional storage beyond android’s internalfilesystem.

This storage is accessible from outside Android, for example when the userattaches the system to a computer.

Users can copy data to and from the external storage, remove files, etc.

This allows users to back up applications and data, manage multimediafiles, and so on.

When external storage is shared to a computer, it’s unavailable to Android andapps that depend on it will not be able to use it until it’s unmounted.

Environment.getExternalStorageState() returns a string matching oneof the constants defined in Environment, such as:

MEDIA_MOUNTED - external storage media is available toAndroid for reading and writing.

MEDIA_MOUNTED_READ_ONLY

MEDIA_SHARED - media present but shared via USB and notmounted to Android.

MEDIA_REMOVED, MEDIA_UNMOUNTED,MEDIA_UNMOUNTABLE, MEDIA_BAD_REMOVAL,MEDIA_CHECKING

Files on external storage are world-readable.

Evaluation Copy

Page 57: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 273

Evaluation Copy

Page 58: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 274 Rev 2.1.1 © 2012 ITCourseware, LLC

Raw Resource Files

Files you provide with your application distribution can be accessed by yourapp as raw resources.

These files will be read-only

Place the files in res/raw/.

res/raw/copyright.txtres/raw/help1.txt

To access a raw resource file, useResources.openRawResource(resourceId).

openRawResource() throws NotFoundException if the resource filedoesn’t exist, otherwise it returns an InputStream.

try { InputStream isHelp; isHelp = getResources().openRawResource(R.raw.help1); brHelp = new BufferedReader(

new InputStreamReader(isHelp));}catch (Resources.NotFoundException nfe) { Log.d("MyApp", "Help file missing", nfe);}

Evaluation Copy

Page 59: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 275

Evaluation Copy

Page 60: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 276 Rev 2.1.1 © 2012 ITCourseware, LLC

Labs

Use the MileageTrack1 project from the student files as a starting point for lab .

You can find solution code for these labs in the MileageTrack2 project.

MileageTrackActivity currently has a saveMileageInput() method, which is a stub that uses aToast to display the date/time, kilometers, liters of fuel, and cost the user has input in the form fields,and displays dummy values for kilometers per liter. Implement an onClickListener for the Savebutton that calls this method.

Once you have working, implement a saveMileageToFile() method. It should:1. Take date/time, distance, fuel, and cost as parameters.2. Open a file named mileagedata.txt with appropriate Java IO classes for writing lines of text.3. Write the mileage data as a line of text, with fields separated by commas.4. Close the file.Use a public static member String for the filename.

From your saveMileageInput() method, call saveMileageToFile(). Test by entering a fewmileage records. Now open the DDMS perspective, go to the File Browser, and locatemileagedata.txt. From a command prompt, run adb shell. Navigate to your app's files/directoryand cat mileagedata.txt.

Add a new method, mostRecentMileageFromFile(). It should:1. Open mileagedata.txt with appropriate Java IO classes for reading lines of text.2. Read to the end of the file, keeping the last two lines read.3. If two or more records are read, split the lines into fields (based on the comma delimiter used towrite them). Return, as an array of two floats, the difference between the two most recent recent(last) records, along with the most recent amount of fuel. If no records are read, return zeroes.

Create a method, showCurrentMileage(), that calls mostRecentMileageFromFile(). If non-zero values were returned, calculate both miles per gallon and kilometers per liter, and display themin the mpgView TextView. If no data was returned, clear the mpgView. In your app'sonCreate(), call showCurrentMileage().

Evaluation Copy

Page 61: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 277

Currently the app accepts, stores and displays distance in kilometers and fuel in liters. We'll keepthese units for storage, but let the user specify different units for input and display: miles and gallons.First, create two new array string-array resources in res/values/arrays.xml: distanceUnit (withelements Miles and Kilometers), and fuelUnit (with elements Gallons and Liters). Now, in res/values/xml/, create a preferences.xml that defines a PreferencesScreen withPreferencesCategory "Input/Display Units", containing two ListPreferences: Fuel Units andDistance Units.

Create a new PreferencesActivity subclass whose onCreate() callsaddPreferencesFromResource(R.xml.preferences). Register this new activity class inAndroidManifest.xml, with the intent-filter action "com.example.mileagetrack.PREFERENCES".

Finally, in the main activity, implement onCreateOptionsMenu() creating a MenuItem forPreferences. In onOptionsItemSelected(), when this item is selected, start your preferencesactivity.

In MileageTrackActivity add a setLabelsFromPreferences() method. Based on the currentvalues of the distanceUnit and fuelUnit preferences, it should set the text of the field labels to thepreferred units.

Modify saveMileageInput(). Based on the current values of the distanceUnit and fuelUnitpreferences, it should convert the input distance value from miles to kilometers if needed and theinput fuel value from gallons to liters if needed.

Test your code, examining the contents of mileagedata.txt in the adb shell.

Evaluation Copy

Page 62: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 278 Rev 2.1.1 © 2012 ITCourseware, LLC

Evaluation Copy

Page 63: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 12 Data Storage: Preferences and Files

© 2012 ITCourseware, LLC Rev 2.1.1 Page 279

Evaluation Copy

Page 64: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 280 Rev 2.1.1 © 2012 ITCourseware, LLC

Evaluation Copy

Page 65: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 43

Chapter 3 - Activities

Objectives

Create an activity.

Implement callback methods to listen foractivity lifecycle events.

Transition from one activity to anotherwith an intent.

Configure an application via theAndoidManifest.xml file.

Package an Android application within an.apk file.

Evaluation Copy

Page 66: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 44 Rev 2.1.1 © 2012 ITCourseware, LLC

A typical Android application is made up of one or more activities.

Each activity provides a screen that you can interact with.

Designate at most one of the activities in your application as the mainactivity.

The main activity is run when you first launch an application.

Your main activity can invoke additional activities which are presented asadditional screens.

The back stack maintains a list of activities that represent the current activity andall of the activities that came before it stored in a last in, first out manner.

When you invoke a new activity, it is pushed to the top of the stack.

The previous activity is stopped and remains on the stack.

When you click on the Back key, the current activity is popped off theback stack and destroyed, and the next activity on the back stack takesuser focus, becomes active, and its user interface is restored.

Activities

Evaluation Copy

Page 67: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 45

.

When an application is first launched, its main activity is the only resident of the back stack.

If the first activity chooses to launch another activity, then the second activity will move to the top of theback stack.

When a third activity is launched from the second activity, the stack now contains three items.

If you press the Back key, then the third activity is popped off the stack and terminated and the secondactivity becomes active.

Evaluation Copy

Page 68: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 46 Rev 2.1.1 © 2012 ITCourseware, LLC

Define an activity as a subclass of android.app.Activity.

Override the onCreate() method to initialize your activity.

onCreate() is called by the system when your activity is first started.

Your implementation typically consists of the following:

1. Call the superclass’s implementation to initialize the parent.

2. Call the setContentView() method to specify the user interfacelayout for this activity.

3. Retrieve references to your GUI components using thefindViewById() method.

4. Associate the components with event handling listener classes.

Creating an Activity

Evaluation Copy

Page 69: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 47

src/com.example.hello/HelloAndroidActivity.java (from HelloAndroid3 project)package com.example.hello;

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.*;

public class HelloAndroidActivity extends Activity { private TextView helloTextView;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Button sayHelloButton = (Button) findViewById(R.id.sayHello); sayHelloButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText nameEditText = (EditText) findViewById(R.id.name); String name = nameEditText.getText().toString(); helloTextView.setText("Hi " + name + "!"); } }); ... } ...}

Evaluation Copy

Page 70: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 48 Rev 2.1.1 © 2012 ITCourseware, LLC

Activity Lifecycle

An activity can be in one of four states: Not Running, Resumed, Paused, orStopped.

A Resumed, or running, activity is currently active and has the focus onthe screen.

Resumed activities are stored at the top of the back stack.

A Paused activity is partially obscured by another activity, for examplewhen a dialog pops up.

The other activity has the focus, but doesn’t cover the wholescreen.

A Stopped activity is completely covered by another activity, for examplewhen a new activity is displayed.

Paused and Stopped activities are nested one or more layers deepwithin the back stack.

Both Paused and Stopped activities remain alive and any data they contain ispreserved in memory.

Evaluation Copy

Page 71: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 49

Not Running

Resumed

Paused

Stopped

The activitystarts

Another activityobscures this activity

This activityis not visible

The activityfinishes orthe processis killed

This activitymoves to theforeground

Evaluation Copy

Page 72: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 50 Rev 2.1.1 © 2012 ITCourseware, LLC

Callback Methods

.

You can implement various callback methods within your activity to be notifiedof state transitions within your activity’s lifecycle.

The whole lifetime of your activity is encompassed between calls to theonCreate() and onDestroy() methods.

Initialize the application within the onCreate() method and cleanup anyactivity wide resources within the onDestroy() method.

You can call the finish() method on an activity to shut it down.

The visible lifetime of your activity is encompassed between calls to theonStart() and onStop() methods.

Initialize any displayable content within the onStart() method and destroyit within the onStop() method.

The onRestart() method will also be called before onStart() if theactivity was previously stopped.

The foreground lifetime of your activity is encompassed between calls to theonResume() and onPause() methods.

Cleanup resources, stop CPU consuming operations (i.e. audio), andpersist unsaved data within the onPause() method and restore them withinthe onResume() method.

Transitions from a paused to a resumed state occur often so you shouldkeep the code in these methods simple.

Don’t forget to call the superclass implementation of the callback methodfrom your method to ensure that default processing occurs.

Evaluation Copy

Page 73: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 51

Adapted from Android Developer API Guide, http://developer.android.com/guide/components/activities.html (accessed July 18, 2012)

Evaluation Copy

Page 74: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 52 Rev 2.1.1 © 2012 ITCourseware, LLC

Resource Conservation

If the system encounters a low memory situation, stopped activities are removedbefore paused activities.

The system will either call the finish() method on an activity to ask it tofinish, or it will kill the process associated with the activity.

The process can be killed after calls to onPause(), onStop(), oronDestroy().

Persist essential data within the onPause() method, because a killedactivity may not have its onStop() or onDestroy() methods called.

If the system needs to resume the activity again (for example, when youclick the Back button), it will have to recreate it.

You can store a killed activity’s state to a Bundle object so it can be restoredlater.

Override the onSaveInstanceState() callback method to store data to thepassed in Bundle object before the activity is killed.

Store data within the Bundle object as name/value pairs.

You should use the onPause() method to store long-term persistentdata and the onSaveInstanceState() method to save transient userinterface state.

Use onCreate()’s Bundle parameter to retrieve saved instance state froma previously killed invocation.

New activities will be passed null since there is no saved data.

Evaluation Copy

Page 75: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 53

If you explicitly close an activity via a Back button click, then onSaveInstanceState() will not be calledsince the activity will not have to be restored.

You may not need to override the onSaveInstanceState() method if the default implementation is sufficient.It invokes the onSaveInstanceState () method on each view within your user interface. Each view canthen store its own UI specific information into the bundle. This happens automatically for any viewcomponent that you’ve given an identifier. Make sure to call super.onSaveInstanceState() if you chooseto provide your own implementation to ensure that this default processing occurs.

Configuration Changes

Android will restart your activity whenever a configuration change is detected. Restarting the activity resultsin a call to onDestroy() followed by onCreate(). One common example of a configuration change is ascreen rotation. For this reason, it is always a good idea to handle activity restoration properly viaonSaveInstanceState() and onCreate().

src/com.example.hello/HelloAndroidActivity.java...public class HelloAndroidActivity extends Activity { private TextView helloTextView;

@Override public void onCreate(Bundle savedInstanceState) { ... helloTextView = (TextView) findViewById(R.id.hello); if (savedInstanceState != null) { helloTextView.setText(savedInstanceState .getString("greeting")); } }

@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("greeting", helloTextView.getText() .toString()); }}

Evaluation Copy

Page 76: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 54 Rev 2.1.1 © 2012 ITCourseware, LLC

Intents

Use an Intent to launch an activity from another activity.

Intent i = new Intent(this, NewActivity.class);startActivity(i);

Create a new instance of an Intent object providing your activity as thefirst constructor argument and the Class of the activity to start as thesecond argument.

Call the startActivity() method passing in the newly created Intent objectto start the new activity.

Evaluation Copy

Page 77: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 55

src/com.example.hello/WelcomeActivity.javapackage com.example.hello;

import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;

public class WelcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome);

Button nextButton = (Button) findViewById(R.id.next); nextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(); i.setClass(WelcomeActivity.this, HelloAndroidActivity.class); startActivity(i); } }); }}

Try It:

Open the HelloAndroid3 project. Select Run | Run from the menu and choose AndroidApplicationfrom the Run As dialog to view the WelcomeActivity. Click the Next button to launch theHelloAndroidActivity using an Intent.

Access the enclosing activityfrom an inner class usingClassName.this notation.

Evaluation Copy

Page 78: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 56 Rev 2.1.1 © 2012 ITCourseware, LLC

AndroidManifest.xml

.

Configure your application within the manifest file called AndroidManifest.xml.

Set the Android namespace to http://schemas.android.com/apk/res/androidwithin the root <manifest> element.

Specify the package name you used for your activities within the<manifest> element’s package attribute.

Set the minimum and target Android SDK versions that you support within the<uses-sdk> element.

Declare your application within the appropriately named <application> element.

Set the icon, label, and theme for your application using attributes.

The icon and label are viewable in the application launcher or as ashortcut on the Home screen.

The theme references an application-wide style configured in anXML file under the res/values/ directory.

Every activity you create must be declared within an <activity> element.

Specify the activity’s class name using the android:name attribute.

Prepend the activities class name with a dot to indicate that theclass is relative to the package declared in the package attributewithin the <manifest> tag.

Use an <intent-filter> with an action of android.intent.action.MAINto identify an activity as a main activity.

Set the category to android.intent.category.LAUNCHER tospecify that this activity should be listed in the application launcher.

Evaluation Copy

Page 79: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 57

AndroidManifest.xml<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.hello" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10" />

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".WelcomeActivity" android:label="@string/title_activity_hello_android" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".HelloAndroidActivity" android:label="@string/title_activity_hello_android" > </activity> </application>

</manifest>

Evaluation Copy

Page 80: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 58 Rev 2.1.1 © 2012 ITCourseware, LLC

Packaging

The Dalvik VM interprets .dex (Dalvik Executable) files rather than standard Javaclass files.

The .dex bytecode format is optimized for memory and processorconstrained environments.

You don’t distribute the .dex files directly to your Android device, instead youpackage them within an .apk file.

An .apk file contains everything you need to run an Android application,including .dex files, resources, and certificates.

.apk files are similar to JAR files and must end in an .apk extension.

Eclipse creates the .dex and .apk files automatically for you, but you can alsobuild them manually using the following steps:

1. Use the Android Asset Packaging Tool (aapt) to compile the variousXML files, including the manifest file, and to produce an R.java file.

2. Compile your source code as well as the R.java file into .class files usingthe standard Java compiler.

3. Convert the .class files from step 2, as well as .class files from librariesyou depend on into .dex files using the dex tool.

4. Use the apkbuilder tool to package the .dex files as well as compiledresources and non-compiled resources like images into an .apk file.

5. Sign the .apk file with a debug key or private key and optionally optimizeit with the zipalign tool to decrease its memory usage for production.

6. Distribute the .apk file to your emulator or, if the .apk is signed with aprivate key, your Android device.

Evaluation Copy

Page 81: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 59

Hands On:

While building an Android application on the command line is less common than building it in Eclipse, it isbeneficial to see the process outside of the IDE. The Android SDK includes a command line tool to createa basic Android project. The generated project contains an Ant script to build the .apk file.

Open a command prompt, change directories to the SDK /tools directory and run the android createproject command to build a new project in the c:\android directory:

android create project --target 1 --name AndroidApp --path C:/android/AndroidAppProject --activity AndroidAppActivity --packagecom.example.commandline

Examine the newly created files, then change directories to the C:\android\AndroidAppProject directory.

cd C:\android\AndroidAppProject

Run the ant debug command to create the .apk file.

ant debug

Examine the ant output and the generated files.

To deploy the generated .apk file to the emulator you must start the emulator and install the .apk to it. If anemulator is not already running, then you can start one by running the emulator command passing in thename of the emulator to run:

emulator -avd MyAvd

Wait for the emulator to start, then open another command prompt and run the adb command to install the.apk to the emulator:

adb install C:\android\AndroidAppProject\bin\AndroidApp-debug.apk

Look for the newly installed application within the application launcher on the emulator. If multipleemulators are running, then you must specify the emulator to install to with the adb –s option. To list thecurrent devices run adb devices.

To uninstall an application, run adb uninstall followed by the package name of the activity to uninstall:

adb uninstall com.example.commandline

Evaluation Copy

Page 82: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 60 Rev 2.1.1 © 2012 ITCourseware, LLC

Labs

Use either the Converter project from the student files or your own Converter solution from aprevious lab as a starting point for lab .

You can find solution code for labs - in the Converter2 project.

Create a distance converter activity within the Converter application that converts miles tokilometers and kilometers to miles.

Make your distance converter activity the main activity for this application within the manifest. Testthe activity within the emulator.

Create a new menu activity that provides buttons to choose between the temperature converter ordistance converter and transition to each via intents when the button is selected. Make sure toupdate the manifest to make this new activity the main activity.

Add callback methods to the menu activity for the various callbacks that were discussed in thechapter. Make sure to call the superclass method, then add trace messages using LogCat to trackwhen the various methods are called.

Perform the following operations on your application and watch the LogCat messages as they aredisplayed:

a. Start the Converter application.b. Click the Temperature button to transition to a new activity.c. Click the Android Back button to transition back to the menu activityd. Click the Android Back button again to shutdown the menu activity.e. Restart the Converter application through the application launcher.f. Click the Home button, then go to the application launcher and click Settings | Applications |Manage Applications within the emulator. Uninstall the Converter application to kill the processassociated with the activity.

(Optional) Use command line tools to create a new project and activity that displays the currenttime.

Evaluation Copy

Page 83: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Chapter 3 Activities

© 2012 ITCourseware, LLC Rev 2.1.1 Page 61

Evaluation Copy

Page 84: Android Programming - ITCourseware · © 2012 ITCourseware, LLC Rev 2.1.1 Page iii android Programming Contents Chapter 1 - Course Introduction ..... 11

Android Programming

Page 62 Rev 2.1.1 © 2012 ITCourseware, LLC

Evaluation Copy