PPT Companion to Android

Embed Size (px)

DESCRIPTION

A complete power point presentation on Android.

Citation preview

Few reasons to go MAD

Smart PhonesInternet access anywhere y Social networkingy

Millions of mobile users Open standards

2

Introduction to Android Open software platform for mobile development. A complete stack OS, Middleware, Applications. An Open Handset Alliance (OHA) project. Powered by Linux operating system. Fast application development in Java. Open source under the Apache license3

Why Android

Android was designed as a platform for software development.

Android is open open. Android is free. Community support. Tool support.

4

Open Handset Alliance (OHA) The OHA is a group of hardware and software developers, including Google, NTT DoCoMo, Sprint Nextel, and HTC Goal Accelerate innovation in mobile Offer consumers a richer, less expensive, and better mobile

experience

OHA have developed Android , the first complete, open, and free mobile platform

5

Features Application framework enabling reuse and replacement

of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite for structured data storage Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)7

Features (Contd .) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware

dependent) Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

8

Android Architecture

9

Linux Kernel Android relies on Linux version 2.6 for core system services such as device drivers, security, memory management ,process management. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

10

Includes a set of C/C++ libraries. Interface through Java. Surface manager Handling UI Windows. 2D and 3D graphics. Media codecs, SQLite, Browser engine.11

Dalvik VM (translator between the application side and the operating system)

Dex files (.dex)format Compact and efficient than class files Limited memory and battery power Java 5 Std edition Collections, I/O etc12

Core Libraries

Application Framework Framework elements are: Intents , Content Providers , Views and managers This layer has been designed to facilitate the reuse of components in android Developers can build their applications to execute on android kernel and inter-operate among themselves and with existing applications

13

Applications Android will ship with a set of core applications including an a)Email client, b)SMS program, c)Calendar, d)Contacts & others. All the applications are written using the Java programming language.

14

Android applications are compiled to Dalvik byte codeWrite app in Java Compiled in Java

Transformed to Dalvik byte code

Loaded into Dalvik VM

Linux OS

15

Android SDK ADT: Android Development Tool, an Eclipe plugin Two debuggers adb: Android Debug Bridge ddms: Dalvik Debug Monitor Server

aapk: Android Application package tool All resources are bundled into an archive, called apk file.

dx: java byte code to Dalvik executable translator

16

Differences between Smart PhonesFeature company OS family Languages SDK Platform Face book Multitasking Android Google Linux Java Multiplatform Yes Yes Windows mobile Microsoft Windows Visual C++ dependent Yes limited BlackBerry RIM Mobile OS C++ dependent Yes limited

17

Differences between Apple and AndroidSpecification Ownership Compatible Access Technology Compatible Devices Messaging Web Browser Apple Apple Proprietary 3G,3.5G,Wi-Fi,Bluetooth Android Google open Source 2G,3G,3.5G and 4G(GSM , CDMA,Bluetooth,Wi-Fi, and WiMAX) Any Devices SMS , MMS , email and C2DM Open source Web kit layout engine coupled with Chromes V8 JavaScript engine Wi-Fi, Bluetooth and NFC Supported (Internet Tethering) Hotspot feature with Wi-Fi

iPod , iPod Touch, iPhones SMS , MMS ,email Safari

Connectivity Multitasking Other device connectivity

Wi-Fi, Bluetooth Supported (Internet) Bluetooth

18

Differences between Apple and AndroidSpecification Chrome to phone 3D Google Map Email Attachments Google Talk Hardware Vendors Apple Not supported Not Yet Single file only Web browser chat Apple Android Supported Supported Multiple files GTalk Specific Client and Video Supported Samsung,Motorola,LG,Son y Ericsson, Dell,Huawei,HTC Supported Supported

3rd Party Branded OS Adobe Flash Support

No Not Supported

19

Android applications have common structureViews such as lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data An Activity Manager that manages the life cycle of applications and provides a common navigation backstack A Notification Manager that enables all apps to display custom alerts in the status bar A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files 20

Android applications have common structureBroadcast receivers can trigger intents that start an application Data storage provide data for your apps, and can be shared between apps database, file, and shared preferences (hash map) used by group of applications Activity is the presentation layer of your app: there will be one per screen, and the Views provide the UI to the activity Intents specify what specific action should be performed Services run in the background and have no UI for the user they will update data, and trigger events 21

Replacing & Reusing ComponentsHome Picasa Photo Gallery

Contacts

Pick photoGMail

Chat

Blogger Blogger

Client component makes a System picks best request for a specific use New components can component for that action action functionality existing

There is a common file structure for applicationscode files images UI layouts constants Autogenerated resource list

23

Hello World !!!1. Create a new Android ProjectSelect File > New > Android Project

2. Fill out the project detailsEnter HelloWorld for Project Name Select Create new project in workspace Enter HelloWorld in App name. Enter com.enlume.HelloWorld in Package Name Enter HelloWorld in Activity name (and yes we want to create an Activity)

24

Project PropertiesProject Name Package Name This is the name of the directory or folder on your computer that you want to contain the project. This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated. The package name you use in your application must be unique across all packages installed on the system; for this reason, it's very important to use a standard domain-style package for your applications. In the example above, we used the package domain "com.chicagoandroids". This is the name for the class stub that will be generated by the plug-in. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. This is the human-readable title for your application.

Activity Name

Application Name

25

The Automatic* Portions

Left: Manifest (* not that automatic) Right: R class and the android library (no need to touch) 26

The Automatic* Portions

Left: Source directories, where your classes go Right: Resources (this is what gets automatically build into the R class)27

A word about the emulator You can create different Run configurations for different target devices. It is possible to target different resolutions (HVGA, HVGA-P, HVGA-L, etc) Network speed and latency, etc. Use the AVD manager and the Run->Run configurations to manipulate

28

Run hello world Select the root of the project. Click in the green play icon . Pick Android Project That will get the emulator going

29

The AndroidManifest lists application details 30

The AndroidManifest File This file must declare all activities, services, broadcast receivers and content provider of the application. It must also contain the required permissions for the application. For example if the application requires network access it must be specified here It can be thought as the deployment descriptor for an Android application. The "package" attribute defines the base package for the following Java elements31

The AndroidManifest File "android:versionName" and "android:versionCode" specify the version of your application. intent filter registered defines that this activity is started once the application starts (action android:name="android.intent.action.MAIN"). The category definition (category android:name="android.intent.category.LAUNCHER" ) defines that this application is added to the application directory on the Android device. The "uses-sdk" part defines the minimal SDK version your application is valid for.32

Activities and Tasks An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. An application usually consists of multiple activities that are loosely bound to each other.

33

Activities (continue)

34

Activities (continue)

35

Activities vs Tasks (Apps) A concrete class in the API An encapsulation of a particular operation They run in the process of the .APK which installed them Optionally associated with a window (UI) An execution Context More of a notion than a concrete API entity A collection of related Activities Capable of spanning multiple processes Associated with their own UI history stack What users on other platforms know as applications36

Activities and Tasks (Cont) Tasks (Cont)

All activities in a task are arranged in a stack. If one activity starts another, the new activity is pushed on the stack and it becomes the running activity. When the user presses the BACK key, the current activity is popped from the stack and the previous one resumes.

37

Managing Tasks Android manages tasks and the back stack by placing all activities started in succession in the same task and in a "last in, first out" stack. You might decide that you want to interrupt the normal behavior. Perhaps you want an activity in your application to begin a new task when it is started (instead of being placed within the current task). when you start an activity, you want to bring forward an existing instance of it (instead of creating a new instance on top of the back stack). you want your back stack to be cleared of all activities start an activity except for the root activity when the user leaves the task.38

Managing Tasks You can do these things and more, with attributes in the manifest element and with flags in the intent that you pass to startActivity(). attributes you can use are:taskAffinity launchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTaskLaunch

And the principal intent flags you can use are:FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_SINGLE_TOP

39

Activities and Tasks (Cont) Launch modes allow you to define how a new instance of an activity is associated with the current task

There are four launch modes: standard (default) / singleTop / singleTask / singleInstance A launch mode can be set for each activity:

40

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points:Which task will hold the activity that responds to the intentOriginal Task Original Task New Task

New Activity Activity A Root Activitystandard/singleTop without FLAG_ACTIVITY_NEW_TASK

Activity A Root Activity New Activity

singleTask/singleInstance

41

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points: (Cont)Whether there can be multiple instances of the activityTask AActivity B Activity C Activity B Activity A Activity C Activity D Activity B Activity A Activity C

Task B

Task A

Task B

Activity B and Activity C are standard/singleTop

Activity C is singleTask or singleInstance

A "standard" or "singleTop" activity can be instantiated many times. A "singleTask" or "singleInstance" activity is limited to just one instance.

42

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points: (Cont)Whether the instance can have other activities in its task"standard" "singleTop" "singleTask" These modes permit multiple activities to belong to the task. A "singleTask" activity will always be the root activity of the task.

"singleInstance" An activity stands alone as the only activity in its task.

43

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points: (Cont)Whether a new instance of the class will be launched to handle a new intentActivity D Activity D Activity C Activity B Activity AAn intent arrives for an activity of type D

Activity D Activity C Activity B Activity A

Activity D Activity C Activity B Activity A

The existing instance D is expected to handle the new intent (since it's at the top of the stack)

Original Task

If D is"standard"

If D is"singleTop"

44

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points: (Cont)Whether a new instance of the class will be launched to handle a new intent (Cont)Activity BAn intent arrives for an activity of type B

Activity B

Original Task

If B is"singleInstance"

A "singleInstance" activity is always at the top of the stack, so it is always in position to handle the intent.

Activities and Tasks (Cont) Launch Modes (Cont)

The modes differ from each other on four points: (Cont)Whether a new instance of the class will be launched to handle a new intent (Cont)Activity B Activity AAn intent arrives for an activity of type B

Activity B Activity A

Activity B can handle the intent since it is in position.

Original TaskActivity A Activity BAn intent arrives for an activity of type B

If B is"singleTask"Activity A Activity BActivity B cannot handle the intent since it is not in position and the intent is dropped.

Original Task

If B is"singleTask"

Activities and Tasks (Cont)

47

Activities and Tasks (Cont) Using Intent Flags : FLAG_ACTIVITY_NEW_TASK :Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent(). FLAG_ACTIVITY_SINGLE_TOP: If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity. FLAG_ACTIVITY_NO_HISTORY : This flag implies that the called activity is not kept in the task s stack. When navigating away, the user cannot return to it. FLAG_ACTIVITY_CLEAR_TOP If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()). 48

Activities and Tasks (Cont) Affinities

An affinity means a preference for each activity to belong to a certain task. An individual affinity can be set for each activity:

By default, a new activity is launched into the task of the activity that called startActivity().

Activities and Tasks (Cont) Affinities (Cont) Two circumstances where the affinity comes into play: FLAG_ACTIVITY_NEW_TASK flag If the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task. allowTaskReparenting attribute If an activity has its allowTaskReparenting attribute set to "true", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore.

Activities and Tasks (Cont) Clearing the Stack Default Control If the user leaves a task for a long time, the system clears the task of all activities except the root activity. Some activity attributes that can be used to modify the default control: If alwaysRetainTaskState is set to the root activity of a task The task retains all activities in its stack even after a long period. If clearTaskOnLaunch is set to the root activity of a task The stack is cleared down to the root activity whenever the user leaves the task and returns to it. The user always returns to the task in its initial state, even after a momentary absence.

Activities and Tasks (Cont) Clearing the Stack (Cont)

Some activity attributes that can be used to modify the default control: (Cont)If finishOnTaskLaunch is set to an activity of a task- The activity remains part of the task only for the current session.- If the user leaves and then returns to the task, it no longer is present.

Another way to force activities to be removed from the stack (FLAG_ACTIVITY_CLEAR_TOP flag):If an intent includes the FLAG_ACTIVITY_CLEAR_TOP flag and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away.

Process Basics How does it all of this relate to the Unix roots of Android?Android process == Linux process (w/ its own unique UID) By default, 1 process per APK By default, 1 thread per process Most components interleave events into the main thread

53

Creating an Activity To create an activity, you must create a subclass of Activity . In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle. The two most important callback methods are:onCreate() onPause().

54

Declaring the Activity in Manifest File You must declare your activity in the manifest file in order for it to be accessible to the system. ... ...

There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI55

Declaring the Activity in Manifest File The android:name attribute is the only required attribute it specifies the class name of the activity.

Using IntentFiltersAn element can also specify various intent filters using the element in order to declare how other application components may activate it. When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity 56

Starting an Activity You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. The intent specifies either the exact activity you want to start or describes the type of action you want to perform. An intent can also carry small amounts of data to be used by the activity that is started

57

Starting an Activity Intent Examples :Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);

Starting an activity for a resultSometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity()) To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method. 58

Managing the Activity Lifecycle An activity can exist in essentially three states:Resumed :The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".) Paused: Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. Stopped : The activity is completely obscured by another activity59

Paused v/s Stopped A paused activity is completely alive The Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager It can be killed by the system in extremely low memory situations. A stopped activity is also still alive. The Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager. It is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.

60

Android Activity Life Cycle Activities have several states Lifecycle methods are called on transitions You typically don t need to use them all, but they are there

61

Android Activity Life Cycle @override these methods in your Activity class, and Android will call them at the appropriate time onCreate(Bundle): This is called when the 1st Activity Startsup onStart(): Called just before the activity becomes visible to the user onResume(): Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack62

Android Activity Life Cycle onPause(): Called when the system is about to start resuming another activity onStop(): This is called when the activity is no longer visible to the user onDestroy(): Called before the activity is destroyed. It could be called either because the activity is finishing or because the system is temporarily destroying this instance of the activity to save space63

Saving Activity State When an activity is paused or stopped, the state of the activity is retained. Any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it "resumes"), those changes are still there. When the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact.64

Saving Activity State The system must recreate the Activity object if the user navigates back to it and important information about the activity state is preserved by implementing an additional callback method The callback method in which you can save information about the current state of your activity is onSaveInstanceState(). The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object65

Tasks and Back Stack A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the "back stack"), in the order in which each activity is opened. When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. When the user presses the BACK key, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored)66

Tasks and Back Stack

67

Application Life Cycle Applications run in their own process. Process are started and stopped as needed to run an application s component. Process may be killed to reclaim resources.

Application Life Cycle (1)System Process

Home Process Home Mail Process Mail Map Process Browser Process Message

Browser

Map

Application Life Cycle (2)System Process

Home Process Home Browser Process Map Process Mail Mail Message Map

Browser

Intents & Intent Filters

71

What is Intent Messaging? Three of the core components of an Android application - activities, services, and broadcast receivers - are activated through messages, called intents One activity starts another activity by creating/sending an Intent Means of leveraging activities, services, and broadcast receivers of other applications Application #1 can use Photo display activity of Application #2 (or system) by creating/sending an intent

72

What is Intent Messaging? An Intent object is passed to startActivity() or startActivityForResult() to launch an activity or get an existing activity to do something new An Intent object is passed to startService() to initiate a service or deliver new instructions to an ongoing service. Intent objects passed to any of the broadcast methods

73

What is Intent Messaging? Intent messaging is a facility for late run-time binding between components in the same or different applications. Enables a flexible and agile architecture: A component that performs a task is selected during runtime One activity can start another activity by creating an intent that says Display web browser - Android runtime then selects a best qualified Display web browser activity among the possible candidates during runtime through so-called Intent resolution74

What Does Intent Object Contain? Information of interest to the target component that receives the intentAction to be taken Data to act on

Information of interest to the Android systemCategory of component that should handle the intent Instructions on how to launch a target activity

75

Intent Object Structure

76

Intent Object Structure Is Made Of Component name Action Data Category Extras Flags

77

Component name Field Specifies the name of the component (name of the activity if the component is activity) that should handle the intentClass name of the target component (for example "com.enlume.ForwardTargetActivity")

Setting component name is optionalIf it is set, the Intent object is delivered to an instance of the designated class. If it is not set, Android uses other information in the Intent object to locate a suitable target - this is called intent resolution

78

Action Field A string naming the action to be performed The Intent class defines a number of predefined action constants, including ACTION_CALL, ACTION_EDIT, ACTION_MAIN, ACTION_SYNC, ACTION_BATTERY_LOW, etc. You can also define your own action strings for activating the components in your application The action largely determines how the rest of the intent is structured - particularly the data and extras fields much as a method name determines a set of arguments and a return value.79

Data Field The URI of the data to be acted on and the MIME type of that data. Different actions are paired with different kinds of data specifications. If the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. If the action is ACTION_CALL, the data field would be a tel: URI with the number to call. If the action is ACTION_VIEW and the data field is an http: URI, the receiving activity would be called upon to download and display whatever data the URI refers to.

80

Data Field Examples of Action/Data PairsACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is "1". ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with the person filled in. ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. ACTION_DIAL tel:123 -- Dial the phone dialer with the given number filled in. ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is "1". ACTION_VIEW content://contacts/people/ -- Display a list of people, which the user can browse through. This example is a typical top-level entry into the Contacts application, showing you the list of people. 81

Category Field A string containing additional information about the kind of component (activity, service, or broadcast receiver) that should handle the intent. Any number of category descriptions can be placed in an Intent object Android provides a set of predefined categories (We will see them in the following slide) You can define your own categories82

Pre-defined Categories (by Android) CATEGORY_BROWSABLE - The target activity can be invoked within the browser to display data referenced by a link for example, an image or an e-mail message. CATEGORY_HOME - This is the home activity, that is the first activity that is displayed when the device boots. CATEGORY_LAUNCHER - The activity can be the initial activity of a task and is listed in the toplevel application launcher. 83 Many more

Extras Field Key-value pairs for additional information that should be delivered to the component handling the intent. Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras. ACTION_TIMEZONE_CHANGED action has a "timezone extra that identifies the new time zone ACTION_HEADSET_PLUG action has a "state" extra indicating whether the headset is now plugged in or unplugged , as well as a "name" extra for the type of headset84

Flags Field Flags of various sorts. Many instruct the Android system how to launch an activity (for example, which task the activity should belong to) and how to treat it after it's launched (for example, whether it belongs in the list of recent activities).

85

Intent Resolution

86

What is Intent Resolution? Android's scheme of determining which target component should be selected for handling a passed intent

87

Types of Intents Explicit intents Designate the target component by its class (the component name field is set by the class name) Since component names (class name of the target activity, for example) would generally not be known to developers of other applications, explicit intents are typically used for application-internal messages such as an activity starting a subordinate service or launching a sister activity. Implicit intents Do not name a target (the component name field is blank). Implicit intents are often used to activate components in other applications.88

Intent Resolution Schemes Explicit resolution for Explicit intents Android delivers an explicit intent to an instance of the designated target class. Nothing in the Intent object other than the component name matters for determining which component should get the intent. Implicit resolution for Implicit intents In the absence of a designated target, the Android must find the best component (or components) to handle the intent By comparing the contents of the Intent object to intent filters, structures associated with the possible target components that can potentially receive intents - intent filters are specified for each component in the AndroidManifest.xml file89

What are Intent Filters? Filters describe and advertise the capabilities of a target component Informs the system which implicit intents a component can handle If a component does not have any intent filters, it can receive only explicit intents. A component with filters can receive both explicit and implicit intents. A component has separate filters for each job it can do90

Where are Filters Specified? Filters are specified for each component in the AndroidManifest.xml file ...

91

Intent FiltersIntent Resolution

92

Intent Filters Intent ResolutionAs shown in the previous illustration. Activity3 has issue a generic request for help processing an incoming text-message. Assume the user has installed a Fancy SMS application to (perhaps) replace the standard HUMBLE SMS app originally included in Android. Upon the arrival of the implicit Intent, Android will (somehow) tell the user: You have got a new text-message. I have a FANCY and a HUMBLE SMS application which one you want me to execute? Make it a default?

93

How Android System Perform Intent Resolution (for Implicit Intents)? An implicit Intent object are tested against an intent filters (of target components) in three areas Action Category Data (both URI and data type) To be delivered to the target component that owns the filter, it must pass all three tests. If an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. If no target can be found, an exception is raised94

Action Test To pass this test, the action specified in the Intent object must match one of the actions listed in the filter. If the Intent object or the filter does not specify an action, the results are as follows:If a filter does not specify any action, there is nothing for an intent to match, so all intents fail the test. No intents can get through the filter. On the other hand, an Intent object that doesn't specify an action automatically passes the test as long as the filter contains at least one action.95

Category Test For an intent to pass the category test, every category in the Intent object must match a category in the filter.The filter can list additional categories, but it cannot omit any that are in the intent The categories of the filter should be the super-set of the categories of the Intent object

Special caseAn Intent object with no categories should always pass this test, regardless of what's in the filter96

Category Test android.intent.category.DEFAULT Android treats all implicit intents passed to startActivity() as if they contained at least one category: "android.intent.category.DEFAULT (the CATEGORY_DEFAULT constant). Therefore, activities that are willing to receive implicit intents must include "android.intent.category.DEFAULT" in their intent filters.

97

Data Test Example ...

Each element can specify a data type (MIME media type) and URI.

98

Data Test - URI For each part of the URI, there are separate parts scheme, host, port, and path scheme://host:port/path Example content://com.example.project:200/folder/subfolder/etc The scheme is "content", the host is "com.example.project", the port is "200", and the path is "folder/subfolder/etc". The host and port together constitute the URI authority When the URI in an Intent object is compared to a URI specification in a filter, it's compared only to the parts of the URI actually mentioned in the filter For example, if a filter specifies only a scheme, all URIs with that scheme match the filter. If a filter specifies a scheme and an authority but no path, all URIs with the same scheme and authority match, regardless of their paths. If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme, authority, and path match. 99

Data Test - Mime media type It's more common in filters than a URI. Both the Intent object and the filter can use a "* wildcard for the subtype field for example, "text/*" or "audio/*" indicating any subtype matches.

10 0

Data Test - Testing Rules An Intent object that contains neither a URI nor a data type passes the test only if the filter likewise does not specify any URIs or data types. An Intent object that contains a URI but no data type passes the test only if its URI matches a URI in the filter and the filter likewise does not specify a type. This will be the case only for URIs like mailto: and tel: that do not refer to actual data. An Intent object that contains a data type but not a URI passes the test only if the filter lists the same data type and similarly does not specify a URI. An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a content: or file: URI and the filter does not specify a URI10 1

Intent Resolution Special Use Cases

10 2

.MAIN Action & .LAUNCHER Category Activities that can initiate applications have filters with "android.intent.action.MAIN" specified as the actionThis is a way an application gets started fresh, without a reference to any particular data.

If they are to be represented in the application launcher, they also specify the "android.intent.category.LAUNCHER" category:

10 3

.MAIN Action & .LAUNCHER Category The Android system populates the application launcher, the top-level screen that shows the applications that are available for the user to launch, by finding all the activities with intent filters that specify the "android.intent.action.MAIN" action and "android.intent.category.LAUNCHER category. It then displays the icons and labels of those activities in the launcher. The Android system discovers the home screen by looking for the activity with "android.intent.category.HOME" in its filter10 4

User Interface In Android

10 5

View and ViewGroup The user interface is built using View and ViewGroup objects. During compilation time, each element in the XML file is compiled into its equivalent Android GUI class, with attributes represented by methods A View : represents the basic building block for user interface components. occupies a rectangular area on the screen and is responsible for drawing and event handling. is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides derives from the base class android.view.View. 10 6

View and ViewGroup One or more Views can be grouped together into a ViewGroup. The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative. A ViewGroup derives from the base class. android.view.ViewGroup10 7

View Hierarchy All the views in a window are arranged in a tree you show the tree by calling setContentView(rootNode) in the activity

10 8

What is a Layout? Your layout is the architecture for the user interface in an Activity. It defines the layout structure and holds all the elements that appear to the user.

10 9

How to declare a Layout? Two Options Option #1: Declare UI elements in XML (most common and preferred)Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for UI controls called widgets (TextView, Button, etc.) and layouts.

Option #2: Instantiate layout elements at runtime (in Java code)Your application can create View and ViewGroup objects (and manipulate their properties) programmatically (in Java code).11 0

Example of using both options You can use either or both of these options for declaring and managing your application's UI Example usage scenarioYou could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.11 1

Advantages of Option #1: Declaring UI in XML Separation of the presentation from the code that controls its behaviorYou can modify UI without having to modify your source code and recompile For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages

Easier to visualize the structure of your UI (without writing any code)Easier to design/debug UI Visualizer tool (like the one in Eclipse IDE)11 2

Layout File Structure Each layout file must contain exactly one root element, which must be a View (Button, for example) or ViewGroup object (LinearLayout, for example). Once you've defined the root element, you can add additional layout objects or widgets (View) as child elements to gradually build a View hierarchy that defines your layout.

11 3

Example: Layout File

11 4

Where to create Layout file? Save the file with the .xml extension, in your Android project's res/layout/ directory

11 5

Load the Layout XML Resource When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation.By calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_namepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); }

11 6

Attributes Every View and ViewGroup object supports their own variety of attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the id attribute). Other attributes are considered "layout parameters, which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object. These attributes are typically in XML form11 7

ID Attribute Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. Syntaxandroid:id="@+id/my_button"11 8

ID Attribute - Android Resource ID There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespaceandroid:id="@android:id/empty

With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.11 9

How to reference views in Java code? Assuming a view/widget is defined in the layout file with a unique ID

Then you can make a reference to the view object via findViewById(R.id.).Button myButton = (Button) findViewById(R.id.my_button);12 0

What Are Layout Parameters? XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams.This subclass contains property types that define the size and position for each child view, as appropriate for the view group.

12 1

Parent view group defines layout parameters for each child view (including the child view group)

12 2

layout_width & layout_height wrap_content tells your view to size itself to the dimensions required by its content fill_parent tells your view to become as big as its parent view group will allow. match_parent Same as fill_parent Introduced in API Level 8

12 3

Linear Layoutfill_parent

Some Button...fill_parent

wrap_content

fill_parent

Layout Types All layout types are subclass of ViewGroup class Layout typesLinearLayout RelativeLayout TableLayout FrameLayout Tab layout

12 5

LinearLayout Aligns all children in a single direction vertically or horizontally, depending on how you define the orientation attribute. All children are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are To configure a LinearLayout, you have five main areas of control besides the container's contents: Orientation fill model weight gravity padding12 6

LinearLayout Orientation : indicates whether the LinearLayout represents a row or a column. Add the android:orientation property to your LinearLayout element in your XML layout, setting the value to be horizontal for a row or vertical for a column. The orientation can be modified at runtime by invoking setOrientation()

12 7

LinearLayout

12 8

LinearLayout Linear Layout: Fill Model Widgets have a "natural" size based on their accompanying text. When their combined sizes does not exactly match the width of the Android device's screen, we may have the issue of what to do with the remaining space

12 9

LinearLayout Linear Layout: Fill Model All widgets inside a LinearLayout must supply dimensional attributes android:layout_width and android:layout_height to help address the issue of empty space. Values used in defining height and width are: Specific a particular dimension, such as 125px to indicate the widget should take up exactly 125 pixels. Provide wrap content which means the widget should fill up its natural space, unless that is too big, in which case Android can use word-wrap as needed to make it fit. Provide fill_parent, which means the widget should fill up all available space in its enclosing container, after all other widgets are taken care of.13 0

LinearLayout Linear Layout: Fill Model

13 1

LinearLayout Linear Layout: Weight It is used to proportionally assign space to widgets in a view. You set android:layout_weight to a value (1, 2, 3, ) to indicates what proportion of the free space should go to that widget. Example Both the TextView and the Button widgets have been set as in the previous example. Both have the additional property android:layout_weight="1 whereas the EditText control has android:layout_weight="2

13 2

LinearLayout Linear Layout: Gravity It is used to indicate how a control will align on the screen. By default, widgets are left- and top-aligned. You may use the XML property android:layout_gravity= to set other possible arrangements: left, center, right, top, bottom, etc.

13 3

LinearLayout Linear Layout: Padding By default, widgets are tightly packed next to each other. If you want to increase the whitespace between widgets, you will want to use the android:padding property (or by calling setPadding() at runtime on the widget's Java object). The padding specifies how much space there is between the boundaries of the widget's "cell" and the actual widget contents. Note: Padding is analogous to the margins on a word processing document.13 4

LinearLayout Linear Layout: Padding Example: The EditText box has been changed to display 30px of padding all around

13 5

LinearLayoutLinearLayout vertical

LinearLayout horizontal weight=0.5 weight=0.5

RelativeLayout RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID)You can align two elements by right border, or make one below another, centered in the screen, centered left, and so on

Elements are rendered in the order given, so if the first element is centered in the screen, other elements aligning themselves to that element will be aligned relative to screen center.13 7

RelativeLayoutparentTop parentLeft 1 toRightOf 1

layout_below button1

2

parentBottom toRightOf 1

RelativeLayout : LayoutParams@+id/red @+id/greenandroid:layout_above="@id/green" android:layout_below="@id/red"

android:layout_toLeftOf="@id/green"

@+id/red

@+id/greenandroid:layout_toRightOf="@id/red"

RelativeLayout : LayoutParamsandroid:layout_alignTop="@id/red"

@+id/green @+id/red @+id/greenandroid:layout_alignBottom="@id/red" android:layout_alignLeft="@id/red" android:layout_alignRight="@id/red"

@+id/green

@+id/green

@+id/red

RelativeLayout : LayoutParamsandroid:layout_alignParentTop="true" android:layout_alignParentLeft="true"

@+id/re d

parent

@+id/re dandroid:layout_alignParentBottom="true" android:layout_alignParentRight="true"

RelativeLayout Example

17 1

Using android.widget.Button To capture button clicks, we set up an event listener using the setOnClickListener method. E.g., we might use an (anonymous) inner class to capture button clicks, as is defined below:Button button01=(Button)findViewById(R.id.button01); button01.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d("PropertyApp", "button01 has just been pressed"); } });17 2

Using android.widget.RadioButton To get the ID of a currently-checked radio button we use the getCheckedRadioButtonID method. E.g.:RadioGroup myRadioGroup; myRadioGroup=(RadioGroup)findViewById(R.id.myRadioGroup); int checkedID = myRadioGroup.getCheckedRadioButtonId(); if (checkedID == -1) { Log.d(TAG, "No radio button was selected."); } else if (checkedID == R.id.radioButton01) { Log.d(TAG, "'radioButton01' was selected."); } else if (checkedID == R.id.radioButton02) { Log.d(TAG, "'radioButton02' was selected."); }

17 3

Creating Menus Menus are an important part of an activity's user interface, which provide users a familiar way to perform actions. There are three types of application menus:Options Menu : The primary collection of menu items for an activity, which appears when the user touches the MENU button. When your application is running on Android 3.0 or later, you can provide quick access to select menu items by placing them directly in the Action Bar, as "action items."17 4

Creating Menus Types of application menus:Context Menu A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu.

Submenu A floating list of menu items that appears when the user touches a menu item that contains a nested menu.

17 5

Creating MenusCreate an application that supports options/sub/context menus

Display messages when a menu clicked

Automatically fill Hi! in the EditText Plus menu will also open a sub-menu

17 6

Menu CompositionHi Hola Sub2 Home Hello Long press in EditText

Sub1 Plus

Pre

Next

17 7

Creating a Menu Resource Instead of instantiating a Menu in your application code, you should define a menu and all its items in an XML menu resource. Inflate the menu resource (load it as a programmable object) in your application code. To create a menu resource, create an XML file inside your project's res/menu/ directory and build the menu with the following elements: , , 17 8

Creating a Menu Resource Defines a Menu, which is a container for menu items A element must be the root node for the file and can hold one or more and elements

Creates a MenuItem, which represents a single item in a menu. This element may contain a nested element in order to create a submenu.

An optional, invisible container for elements. It allows you to categorize menu items so they share properties such as active state and visibility

17 9

Creating a Menu Resource android:id A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it. android:icon A reference to a drawable to use as the item's icon. android:title A reference to a string to use as the item's title. 18 0

Inflating a Menu Resource From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate().public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.game_menu, menu); return true; }

The getMenuInflater() method returns a MenuInflater for the activity. With this object, you can call inflate(), which inflates a menu resource into a Menuobject18 1

Inflating a option menu resourceInflating a menu resource (menu.xml) by adding onCreateOptionsMenu(Menu menu) in the main Activity. Menu items in menu.xml will appear when the user touches the MENU button

public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }

18 2

Response to user actionResponse to menu click events by overriding onOptionsItemSelected(Menu menu) in the main Activity. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuItemPlus: Toast.makeText(this, "Plus Button Clicked !", Toast.LENGTH_SHORT).show(); Log.i(TAG,"menuItemPlus"); return true; : : case R.id.menuItemNext: Toast.makeText(this, "Next Button Clicked !", Toast.LENGTH_SHORT).show(); Log.i(TAG,"menuItemNext"); return true; } return false; }

18 3

Changing menu items at runtime Once the activity is created, the onCreateOptionsMenu() method is called only once. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu()method18 4

How to Create Context Menu? A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu. When Context menu is opened for the first time, the Android system will call the Activity's onCreateContextMenu(Menu menu) callback method. You, as a context menu developer, override this method in your Activity class and populate the Menu object given to you with MenuItem's. You can populate the menu in two ways Scheme #1: by calling add() for each item you'd like in the menu. Scheme #2: by inflating a menu resource that was defined in XML (preferred)18 5

Populating Menu with Menu Items: #1// Override this method of Activity class in order to create menu items. @Override public void onCreateContextMenu( ContextMenu menu, // Context menu that is being built View view, // The view for which the context menu is being built ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); menu.setHeaderTitle("Context menu"); menu.add(0, Menu.FIRST , Menu.NONE, "menu #1"); menu.add(0, Menu.FIRST + 1, Menu.NONE, "menu #2"); menu.add(0, Menu.FIRST + 2, Menu.NONE, "menu #3"); menu.add(0, Menu.FIRST + 3, Menu.NONE, "menu #4"); } 18 6

How to handle User's Menu Selection? When a menu item is selected by a user from the Context Menu, onContextItemSelected() callback method of your Activity gets calledThis callback passes you the MenuItem that has been selected. You can identify the item by requesting the itemId, with getItemId(), which returns the integer that was assigned with the add(int groupId, int itemId, int order, CharSequence title) method. Once you identify the menu item, you can take an appropriate action.

18 7

Example: Handling Menu Selection/* Handles item selections */ public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NEW_GAME: newGame(); return true; case MENU_QUIT: quit(); return true; } return false; }

18 8

Creating Submenus A submenu is a menu that the user can open by selecting an item in another menu. You can add a submenu to any menu (except a submenu). Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, View, etc.).

18 9

Creating Submenus

19 0

Creating Dialogs A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress

19 1

Creating Dialogs The Dialog class is the base class for creating dialogs. Typically you are going to use subclasses of Dialog class instead of using it directly. Example subclasses of Dialog class :AlertDialog. ProgressDialog DatePickerDialog. TimePickerDialog19 2

Showing a Dialog A dialog is always created and displayed as a part of an Activity. You should normally create dialogs from within your Activity's onCreateDialog(int) callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the "owner" of each dialog19 3

Showing a Dialog When you want to show a dialog, call showDialog(int) and pass it an integer that uniquely identifies the dialog that you want to display. When a dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity, which is where you should instantiate the Dialog. Define onPrepareDialog(int, Dialog) method if you want to change any properties of the dialog each time it is opened

19 4

Example of Showing a Dialogstatic final int DIALOG_PAUSED_ID = 0; static final int DIALOG_GAMEOVER_ID = 1; protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_PAUSED_ID: // do the work to define the pause Dialog break; case DIALOG_GAMEOVER_ID: // do the work to define the game over Dialog break; default: dialog = null; } return dialog; }

When it's time to show one of the dialogs,call showDialog(int) with the ID of a dialog:showDialog(DIALOG_PAUSED_ID);

19 5

Creating an Alert Dialog An AlertDialog is an extension of the Dialog class. It should be used for dialogs that use any of the following features:A title A text message One, two, or three buttons A list of selectable items (with optional checkboxes or radio buttons)

19 6

Creating an Alert Dialog To create an AlertDialog, use the AlertDialog.Builder subclass. Get a Builder with AlertDialog.Builder(Context) and then use the class's public methods to define all of the AlertDialog properties. After you're done with the Builder, retrieve the AlertDialog object with create().

19 7

Creating an Alert Dialog

19 8

Creating an Alert Dialog Adding ButtonsAlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MyActivity.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); 19 9

Creating an Alert Dialog Adding Listfinal CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create();

20 0

Creating an Alert Dialog Adding checkboxes and radio buttons To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoiceItems( ) methods final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create();

20 1

Creating a ProgressDialog A ProgressDialog is an extension of the AlertDialog class. It displays a progress animation in the form of a spinning wheel, for a task with progress that's undefined, or a progress bar, for a task that has a defined progression. Opening a progress dialog can be as simple as calling ProgressDialog.show().ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true);20 2

Creating a ProgressDialog The default style of a progress dialog is the spinning wheel. If you want to create a progress bar that shows the loading progress with granularity, some more code is required. To show the progression with an animated progress bar: Initialize the ProgressDialog with the class constructor, ProgressDialog(Context). Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other properties, such as the message. When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback. You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far. 20 3

Date/Time Selection Widgets DateAndroid also supports widgets (DatePicker, TimePicker) and dialogs (DatePickerDialog, TimePickerDialog) for helping users enter dates and times. The DatePicker and DatePickerDialog allow you to set the starting date for the selection, in the form of a year, month, and day. Value of month runs from 0 for January through 11 for December Each widget provides a callback object (OnDateChangedListener or OnDateSetListener) where you are informed of a new date selected by the user.20 4

Date/Time Selection Widgets Time Selection The widgets TimePicker and TimePickerDialog let you:set the initial time the user can adjust, in the form of an hour (0 through 23) and a minute (0 through 59) indicate if the selection should be in 12-hour mode (with an AM/PM toggle), or in 24-hour mode. provide a callback object (OnTimeChangedListener or OnTimeSetListener) to be notified of when the user has chosen a new time (which is supplied to you in the form of an hour and minute)20 5

Date/Time Selection Widgets

20 6

Date/Time Selection Widgets

20 7

Date/Time Selection Widgets

20 8

Date/Time Selection Widgets

20 9

Date/Time Selection Widgets

21 0

Date/Time Selection Widgets Other Time Widgets Android provides a DigitalClock and AnalogClock widgets. Automatically update with the passage of time (no user intervention is required).

21 1

LIST CONTROLS

21 2

Understanding Adapters List controls are used to display collections of data. But instead of using a single type of control to manage both the display and the data, Android separates these two responsibilities into list controls and adapters. List controls are classes that extend android.widget.AdapterView and include ListView, GridView, Spinner, and Gallery21 3

Understanding Adapters

21 4

What is AdapterView Class? The AdapterView is a child class of ViewGroup A special kind of container of view objects (list items) Typically you are going to use subsclasses of AdapterView class instead of using it directly Example subclasses of AdapterView class ListView Spinner Gallery An AdapterView access the data through Adapter object Instead of accessing data directly itself21 5

What is an Adapter? An Adapter object acts as a bridge between an AdapterView object and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set. Types of Adatpers - they implements ListAdatper interface ArrayAdatper CursorAdatper There are a few more21 6

Adapter Class Hierarchy BaseAdatper abstract class implements ListAdapter and SpinnerAdatper interfaces ArrayAdapter and CursorAdapter classes are subclasses of BaseAdapter class You can create a custom adaptor by extending BaseAdapter class

21 7

AdapterView Responsibilities Two main responsibilities of AdapterViewFilling the layout with data (it received through the help of an Adapter) Handling user selections - when a user selects an item, perform some action

21 8

Filling the Layout with Data Inserting data into the layout is typically done by binding the AdapterView class to an Adapter, which retrieves data from an external source (perhaps a list that the code supplies or query results from the device's database).

21 9

Handling User Selections You handle the user's selection by setting the class's AdapterView.OnItemClickListener member to a listener and catching the selection changes // Create a message handling object as an anonymous class.private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id){ // Display a messagebox. Toast.makeText(mContext,"You've got an event", Toast.LENGTH_SHORT).show(); } }; // Now hook into our object and set its onItemClickListener member // to our class handler object. mHistoryView = (ListView)findViewById(R.id.my_list_view); mHistoryView.setOnItemClickListener(mMessageClickedHandler);

22 0

Getting to Know SimpleCursorAdapter

22 1

Getting to Know SimpleCursorAdapter On the left-hand side is the AdapterView; in this example, it is a ListView made up of TextView children. On the right-hand side is the data; in this example, it s represented as a result set of data rows that came from a query against a content provider. To map the data rows to the ListView, the SimpleCursorAdapter needs to have a child layout resource ID. The child layout must describe the layout for each of the data elements from the right-hand side that should be Displayed on the left-hand side22 2

Getting to Know ArrayAdapter The ArrayAdapter is the simplest of the adapters in Android. It specifically targets list controls and assumes that TextView controls represent the list items (i.e., the child views). Creating a new ArrayAdapter can look as simple as this:ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, new string[]{ India", Bhutan", Nepal });22 3

Getting to Know SimpleCursorAdapter The constructor of SimpleCursorAdapter looks like this: SimpleCursorAdapter(Context context, int childLayout, Cursor c, String[] from, int[] to) There is a careful collaboration going on between the ListView and our adapter. When the ListView wants to display a row of data, it calls the getView() method of the adapter, passing in the position to specify the row of data to be displayed. The adapter responds by building the appropriate child view using the layout that was set in the adapter s constructor and by pulling the data from the appropriate record in the result set22 4

AutoCompleteTextView The AutoCompleteTextView control is a TextView with auto-complete functionality. In other words, as the user types in the TextView, the control can display suggestions for selection. AutoCompleteTextView actv = (AutoCompleteTextView) this.findViewById(R.id.actv); ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, new String[] {"English", "Hebrew", "Hindi", "Spanish", "German", "Greek" }); actv.setAdapter(aa);

22 5

MultiAutoCompleteTextView If you have played with the AutoCompleteTextView control, you know that the control offers suggestions only for the entire text in the text view. In other words, if you type a sentence, you don t get suggestions for each word. That s where MultiAutoCompleteTextView comes in. You can use the MultiAutoCompleteTextView to provide suggestions as the user types22 6

MultiAutoCompleteTextView It requires that you give it a tokenizer that can parse the sentence and tell it whether to start suggesting again. MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) this .findViewById(R.id.mactv); ArrayAdapter aa2 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, new String[] {"English", "Hebrew", "Hindi", "Spanish", "German", "Greek" }); mactv.setAdapter(aa2); mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

22 7

AutoCompleteTextViews

22 8

ListView Class A child class of AdapterView class Shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view

22 9

Two Choices of Activity Class Option #1 - Your activity extends Activity classYou have to create ListView object yourself from resource file just like any other View object

Option #2 - Your activity extends ListActivity classListView object gets created by the ListActivity's contructor, so you don't need to create it yourself

23 0

Option #1 - Extending Activity Classpublic class HelloListView extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Since HelloListView extends Activity (instead of ListActivity), // we have to create ListView object ourselves. ListView lv =(ListView)findViewById(R.id.listview); ArrayAdapter arrayAdapter = new ArrayAdapter( this, // Application context R.layout.list_item, // layout description for each list item COUNTRIES); lv.setAdapter(arrayAdapter); } 23 1

Example of ListView Layout 23 2

Example of List Item Layout

23 3

Option #2: ListActivity Activity class Android-provided utility class specially designed for displaying a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. ListActivity hosts a ListView object that can be bound through an adatper to different data sources, typically either an array or a Cursor holding query results. setListAdapter(ListAdatper adapter) method automatically creates ListView object from the ListAdapter object Has a default layout that consists of a single, full-screen list in the center of the screen23 4

Option #2: Extending ListActivitypublic class HelloListView extends ListActivity { // Array as a data source static final String[] COUNTRIES = new String[] { "Yemen", "Yugoslavia", "Zambia", "Zimbabwe" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create an adapter from Array data source object ArrayAdapter arrayAdapter = new ArrayAdapter( this, // Application context R.layout.list_item, // layout description for each list item COUNTRIES); // String array of countries defined // Notice that this does not load a layout file for the Activity (which you // usually do with setContentView(int)). Instead, setListAdapter(ListAdapter) // automatically adds a ListView to fill the entire screen of the ListActivity. setListAdapter(arrayAdapter); } }

23 5

Spinner Class A child class of AdapterView class Displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view There is NO special SpinnerActivity class, so you have to create Spinner object yourself

23 6

Example of Spinnerpublic class HelloSpinner extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); }

23 7

Example of Spinner Layout

23 8

GridView Control Android has a GridView control that can display data in the form of a grid. The contents of the grid can be text, images, and so on. The usage pattern for the GridView is :Define the grid in the XML layout Bind the data to the grid.

23 9

Gallery Class A child class of AdapterView class A view that shows items in a centerlocked, horizontally scrolling list

24 0

Example of Gallerypublic class HelloGallery extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery g = (Gallery) findViewById(R.id.gallery); g.setAdapter(new ImageAdapter(this)); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show(); } }); }

24 1

Example of Gallery Layout 24 2

Creating Custom Adapters Standard adapters in Android are easy to use, but they have some limitations. To address this, Android provides an abstract class called BaseAdapter that you can extend if you need a custom adapter. You would use a custom adapter if you had special data management needs or if you wanted more control over how to display child views. You might also use a custom adapter to improve performance by using caching techniques.24 3

Do you even know how ListView works? Gimme views For each positionAdapter.getView()

A new View is returnedExpensive

What if I have 1,000,000 items?Create new view for each item? The answer is NO:-) Android caches views for you.

24 4

Do you even know how ListView works? There s a component in Android called Recycler . If you have 1 billion items there are only visible items in the memory + view in recycler. ListView asks for a view type1 first time (getView) x visible items. convertView is null in getView you create new view of type1 and return it. ListView asks for a view type1 when one item1 is outside of the window and new item of the same type is coming from the bottom.convertView is not null = item1. You should just set new data and return convertView back. No need to create view again.24 5

Do you even know how ListView works?

24 6

Don tpublic View getView(int position, View convertView, ViewGroup parent) { View item = mInflater.inflate(R.layout.list_item_icon_text, null); ((TextView) item.findViewById(R.id.text)).setText(DATA[position]); ((ImageView) item.findViewById(R.id.icon)).setImageBitmap( (position & 1) == 1 ? mIcon1 : mIcon2); return item; }

24 7

Dopublic View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(R.layout.item, null); } ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]); ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap( (position & 1) == 1 ? mIcon1 : mIcon2); return convertView; }24 8

Even betterstatic class ViewHolder { TextView text; ImageView icon; }

24 9

Even betterpublic View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item_icon_text, null); holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.text); holder.icon = (ImageView) convertView.findViewById(R.id.icon); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(DATA[position]); holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2); return convertView; }

25 0

Applying Styles And Themes A style is a collection of properties that specify the look and format for a View or window. A style can specify properties such as height, padding, font color, font size, background color, and much more. A style is defined in an XML resource that is separate from the XML that specifies the layout. Styles in Android share a similar philosophy to cascading stylesheets in web design they allow you to separate the design from the content.

25 1

Defining Styles To create a set of styles, save an XML file in the res/values/ directory of your project. The name of the XML file is arbitrary, but it must use the .xml extension and be saved in the res/values/ folder. The root node of the XML file must be . For each style you want to create, add a element to the file with a name that uniquely identifies the style (this attribute is required). Then add an element for each property of that style, with a name that declares the style property and a value to go with it (this attribute is required). The value for the can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property25 2

Example fill_parent wrap_content

25 3

Styles And Themes Inheritance The parent attribute in the element lets you specify a style from which your style should inherit properties. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. You can inherit from styles that you've created yourself or from styles that are built into the platform. #80FF00 25 4

Styles And Themes Inheritance If you want to inherit from styles that you've defined yourself, you do not have to use the parent attribute. Instead, just prefix the name of the style you want to inherit to the name of your new style, separated by a period fill_parent fill_parent vertical

25 5

Using Themes One problem with styles is that you need to add an attribute specification of style="@style/..." to every view definition that you want it to apply to. If you have some style elements you want applied across an entire activity, or across the whole application, you should use a theme instead. A theme is really just a style applied broadly, but in terms of defining a theme, it's exactly like a style.25 6

Using Themes ... ... #FFFFFFFF ?panelForegroundColor 14 ?panelTextColor ?panelTextSize

25 7

Using Themes Now that the theme is created, you can apply it to your application by editing the AndroidManifest.xml file of your application and adding the android:theme attribute to the application tag with its attribute as the theme's name you specified earlier. Example: If you want to apply it to a single activity and not the whole application, edit the activity tag to add its attribute. 25 8

Custom Attributes Although it is nice to be able to override the default system properties in some cases, what we'd really like to do is define custom properties of our own in our application's layouts. Say we wanted the margins of all of our activities to be a certain dimension. Below is an example of a custom attribute added to our custom theme in themes.xml which we can use to define a property called pageMargin:2sp25 9

Custom Attributes If you simply copy the above text into your new file themes.xml, you will get a build error Error: No resource found that matches the given name: attr 'pageMargin'. This is because we have not defined what pageMargin is to the build system. Create a file called attrs.xml in res/values/. Here you will create your style attributes, which are any customizable attributes you would like for your theme to define.

26 0

Custom Attributes The format attribute indicates what type of values we can define for pageMargin; in this case, either a reference to another attribute, or a dimension such as 2sp or 4px. Other examples of possible formats are color,boolean, integer, and float. Now, I could set the margins in my views by referencing a single constant, instead of putting the same value piecemeal around the code: 26 1

Handling UI Events Events are actually system-generated messages that are sent to the View object whenever a UI element is accessed in some fashion by a user. Handling and handlers are two other terms used in conjunction with events in Java and Android. Once these events are triggered by a user s touch, keystroke, or navigation key, they must be handled within your application.

26 2

Handling UI Events Via the View class Each of the UI elements in your application is a View object Each has events that are unique to that element. User interaction with specific UI elements is kept separate and organized. Each of these View objects keeps track of its own user-input events. The way that a View object within your layout talks with the rest of your application program logic is via a public callback method that is invoked by Android when a given action occurs in that UI View object. Android provides nested interfaces that are already a part of all of your View class-based widgets are called event listeners for event handling26 3

Event Callback Methods An event listener is a Java interface in the View class that contains a single callback method to handle that type of user-input event. When you implement a specific event listener interface, you are telling Android that your View class will handle that specific event on that specific View. These callback methods are called by Android when the View object that the callback method is registered to is triggered by the user-input device used to access that UI interface element26 4

Listener

Callback

Trigger Press Physical Key when registered View has focus

View.setOnKeyListener

onKey()

View.setOnTouchListener

onTouch()

Touch registered View on screen

View.setOnClickListener

onClick()

Press registered UI widget, usually Button

View.setOnLongClickListener

onLongClick()

Long press on registered widget, usually Button

View.setOnCreateContextMenuListener

onCreateContextMenu()

Long press on registered widget, usually ListView Focus shifts away from registered view

View.setOnFocusChanged

onFocusChanged()

26 5

Listener Implementations Using a separate Listener class Using an anonymous inner class Using the main ActivityAnd having it implement the Listener interface

Using the main ActivityAnd specifying the method in the layout file (main.xml)

26 6

Approach

Using a separate Listener class

Use an external class that implements View.OnClickListener

Import android.view.View.OnClickListener, then say implements OnClickListener AdvantagesYou can pass arguments to change behavior Separate classes generally promote loose coupling

So, if event handler can be applied to different controls, it can be change independently from rest of app.But, in most real situations, behavior is tightly coupled to app anyhow.

DisadvantagesIf you want to call code in main Activity, you need reference Even then, that code in main Activity must be public 26 7

Using a separate Listener class

26 8

Using a separate Listener class

26 9

Using an anonymous inner class ApproachAnonymous Listeners allow you to set up a separate callback for each UI element, but does add overhead by creating separate instances for each listener

AdvantagesAssuming that each class is applied to a single control only, it s a shorter approach. This approach is widely used in Swing, SWT, AWT, and GWT.

DisadvantagesIf you applied the handler to more than one control, you would have to cut and paste the code for the handler. This approach should be applied for a single control only If the code for the handler is long, it makes the code harder to read by putting it inline. This approach is usually used only when handler code is short 27 0

Using an anonymous inner class

27 1

Using the main Activity Approach Have the main Activity implement the Listener interface. Put the handler method in the main Activity. Call setOnClickListener(this).

Advantages Assuming that the app has only a single control of that Listener type, this is the shortest and simplest of the approaches.

Disadvantages Scales poorly to multiple controls unless they have completely identical behavior. This approach should be applied when your app has only a single control of that Listener type You cannot pass arguments to the Listener. So, again, works poorly for multiple controls 27 2

Using the main Activity

27 3

27 4

Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication . For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.27 5

Services A service can essentially take two forms: Started :A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself. Bound A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results. A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

27 6

Services To create a service, you must create a subclass of Service (or one of its existing subclasses). In your implementation, you need to override some callback methods. onStartCommand()The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService()27 7

Services onBind()The system calls this method when another component wants to bind with the service by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.

onCreate()The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.

onDestroy()The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.

27 8

Declaring a service in the manifest Like activities (and other components), you must declare all services in your application's manifest file. To declare your service, add a element as a child of the element. ... ... 27 9

Extending the IntentService class A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.28 0

Extending the IntentService class Is a subclass of Service that uses a worker thread to handle all start requests, one at a time. The IntentService does the following:Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your app