You are on page 1of 370

Few reasons to go MAD

Smart Phones
Internet access anywhere y Social networking
y

Millions of mobile users Open standards


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 license
3

Why Android

Android was designed as a platform for software development.

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

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

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

Android Architecture

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 etc
12

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 code


Write 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 Phones


Feature 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 Android


Specification 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 Android


Specification 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 structure


Views 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 structure


Broadcast 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 Components


Home Picasa Photo Gallery

Contacts

Pick photo
GMail

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 applications


code files images UI layouts constants Autogenerated resource list

23

Hello World !!!


1. Create a new Android Project
Select File > New > Android Project

2. Fill out the project details


Enter 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 Properties
Project 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


<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android " package="com.my_domain.app.helloactivity"> <application android:label="@string/app_name"> <activity android:name=".HelloActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application>
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 elements
31

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 applications
36

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 <activity> manifest element and with flags in the intent that you pass to startActivity(). <activity> 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 intent
Original Task Original Task New Task

New Activity Activity A Root Activity


standard/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 activity
Task A
Activity 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 intent
Activity D Activity D Activity C Activity B Activity A
An 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 B
An 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 A
An intent arrives for an activity of type B

Activity B Activity A

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

Original Task
Activity A Activity B
An intent arrives for an activity of type B

If B is"singleTask"
Activity A Activity B
Activity 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.
<manifest ... > <application ... > <activity android:name=".ExampleActivity" /> ... </application ... > ... </manifest >

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 UI
55

Declaring the Activity in Manifest File


The android:name attribute is the only required attribute it specifies the class name of the activity.

Using IntentFilters
An <activity> element can also specify various intent filters using the <intent-filter> 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 result


Sometimes, 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 activity
59

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 stack
62

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 space
63

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 object
65

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 resolution
74

What Does Intent Object Contain?


Information of interest to the target component that receives the intent
Action to be taken Data to act on

Information of interest to the Android system


Category 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 intent
Class name of the target component (for example "com.enlume.ForwardTargetActivity")

Setting component name is optional


If 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 Pairs
ACTION_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 categories
82

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 headset
84

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 file
89

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 do
90

Where are Filters Specified?


Filters are specified for each component in the AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...> <application android:icon="@drawable/app_notes" ... > <activity android:name="NoteEditor" android:theme="@android:style/Theme.Light" android:label="@string/title_note" > <intent-filter android:label="@string/resolve_edit"> <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.EDIT" /> <action android:name="com.android.notepad.action.EDIT_NOTE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.INSERT" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> </intent-filter> </activity> ...

91

Intent Filters
Intent Resolution

92

Intent Filters
Intent Resolution
As 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 raised
94

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 case
An Intent object with no categories should always pass this test, regardless of what's in the filter
96

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
<intent-filter . . . > <data android:mimeType="video/mpeg" android:scheme="http" . . . /> <data android:mimeType="audio/mpeg" android:scheme="http" . . . /> ... </intent-filter>

Each <data> 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 URI
10 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 action
This 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:
<intent-filter . . . > <action android:name="code android.intent.action.MAIN" /> <category android:name="code android.intent.category.LAUNCHER" /> </intent-filter>

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 filter
10 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.ViewGroup
10 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 scenario
You 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 behavior
You 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


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout>

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_name
public 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 form
11 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. Syntax
android: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 namespace
android: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
<Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/>

Then you can make a reference to the view object via findViewById(R.id.<string-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
<Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/my_button_text"/>

12 3

Linear Layout
fill_parent

Some Button...
fill_parent

wrap_content

fill_parent

Layout Types
All layout types are subclass of ViewGroup class Layout types
LinearLayout 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 padding
12 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

LinearLayout
LinearLayout 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

RelativeLayout
parentTop parentLeft 1 toRightOf 1

layout_below button1

parentBottom toRightOf 1

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

android:layout_toLeftOf="@id/green"

@+id/red

@+id/green
android:layout_toRightOf="@id/red"

RelativeLayout : LayoutParams
android:layout_alignTop="@id/red"

@+id/green @+id/red @+id/green


android:layout_alignBottom="@id/red" android:layout_alignLeft="@id/red" android:layout_alignRight="@id/red"

@+id/green

@+id/green

@+id/red

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

@+id/re d

parent

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

RelativeLayout Example
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue" android:padding="10px" > <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:drawable/editbox_background" android:layout_below="@id/label" /> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/entry" android:layout_alignParentRight="true" android:layout_marginLeft="10px" android:text="OK" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@id/ok" android:text="Cancel" /> </RelativeLayout>

14 2

Table Layout
Android's TableLayout allows you to position your widgets in a grid made of identifiable rows and columns. Columns might shrink or stretch to accommodate their contents. TableLayout works in conjunction with TableRow. TableLayout containers do not display border lines for their rows, columns, or cells.

14 3

Table Layout
Rows are declared by you by putting widgets as children of a TableRow inside the overall TableLayout. The number of columns is determined by Android ( you control the number of columns in an indirect way). So if you have three rows one with two widgets one with three rows, widgets, widgets, and one with four widgets, there will be at least four columns.

14 4

Table Layout
However, a single widget can take up more than one column by including the android:layout_span property, indicating the number of columns the widget spans (this is similar to the colspan attribute one finds in table cells in HTML)
<TableRow> <TextView android:text="URL:" /> <EditText android:id="@+id/entry" android:layout_span="3" /> </TableRow>

14 5

Table Layout
Ordinarily, widgets are put into the first available column of each row. In the previous fragment, the label ( URL ) would go in the first column (column 0, as columns are counted starting from 0), and the TextField would go into a spanned set of three columns (columns 1 through 3).

14 6

Table Layout Example

14 7

Table Layout
By default, each column will be sized according to the "natural" size of the widest widget in that column. If your content is narrower than the available space, you can use the TableLayout property:
android:stretchColumns =

Its value should be a single column number (0-based) or a comma delimited list of column numbers. Those columns will be stretched to take up any available space yet on the row.
14 8

Table Layout
In our running example we stretch columns 2, 3, and 4 to fill the rest of the row.

14 9

Frame Layout
FrameLayout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout and control their position within the FrameLayout using gravity. Children are drawn in a stack, with the most recently added child on top. The size of the frame layout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

15 0

Frame Layout Example


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="yellowyellowyellow" android:gravity="bottom" android:background="#aaaa00" android:layout_width="wrap_content" android:layout_height="120dip"/> <TextView android:text="greengreengreen" android:gravity="bottom" android:background="#00aa00" android:layout_width="wrap_content" android:layout_height="90dip" /> <TextView android:text="blueblueblue" android:gravity="bottom" android:background="#0000aa" android:layout_width="wrap_content" android:layout_height="60dip" /> <TextView android:text="redredred" android:gravity="bottom" android:background="#aa0000" android:layout_width="wrap_content" android:layout_height="30dip"/> </FrameLayout>

15 1

ScrollView Layout
A ScrollView is a special type of FrameLayout in that it enables users to scroll through a list of views that occupy more space than the physical display When we have more data than what can be shown on a single screen you may use the ScrollView control. It provides a sliding or scrolling access to the data. This way the user can only see part of your layout at one time, but the rest is available via scrolling. The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout. This is similar to browsing a large web page that forces the user to scroll up the page to see the bottom part of the form.
15 2

Example of ScrollView

15 3

Absolute Layout
Is based on the simple idea of placing each control at an absolute position. You specify the exact x and y coordinates on the screen for each control. This is not recommended for most UI development since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain This class is deprecated. Use FrameLayout, RelativeLayout or a custom layout instead.
15 4

Adapting to Display Orientation


One of the key features of modern smartphones is their ability to switch screen orientation. Android supports two screen orientations portrait Landscape When you change the orientation of your Android device, your current activity is actually destroyed and then recreated. You can employ two techniques to handle changes in screen orientation Anchoring Resizing and repositioning

15 5

Adapting to Display Orientation

15 6

Adapting to Display Orientation


Anchoring:
The easiest way is to anchor your views to the four edges of the screen. When the screen orientation changes, the views can anchor neatly to the edges. Anchoring could be easily achieved by using RelativeLayout

15 7

Adapting to Display Orientation


ANCHORING VIEWS

LANDSCAPE

PORTRAIT

15 8

Adapting to Display Orientation


Resizing and Repositioning
customize the UI based on screen orientation is to create a separate res/layout folder containing the XML files for the UI of each orientation. To support landscape mode, you can create a new folder in the res folder and name it as layout-land (representing landscape). The main.xml file contained within the layout folder defines the UI for the activity in portrait mode, whereas the main.xml file in the layout-land folder defines the UI in landscape mode
15 9

Persisting State Information during Changes in Configuration


When an activity is re-created, the current state of the activity may be lost. When an activity is killed, it will fire one or more of the following two events: onPause() onSaveInstanceState(). To preserve the state of an activity, you could always implement the onPause() event. If you simply want to preserve the state of an activity so that it can be restored later when the activity is re-created (such as when the device changes orientation), a much simpler way would be to implement the onSaveInstanceState() method
16 0

Detecting Orientation Changes


Use the WindowManager class to know the device s current orientation during run time.
//---get the current display info--WindowManager wm = getWindowManager(); Display d = wm.getDefaultDisplay(); if (d.getWidth() > d.getHeight()) { //---landscape mode--}else { //---portrait mode--} 16 1

Controlling the Orientation of the Activity


You can programmatically force a change in orientation using the setRequestOrientation() method of the Activity class.
setRequestedOrientation(ActivityInfo.SCREEN_ORIEN TATION_LANDSCAPE); setRequestedOrientation(ActivityInfo.SCREEN_ORIEN TATION_PORTRAIT); you can also use the android:screenOrientation attribute on the <activity> element in AndroidManifest.xml
16 2

View Widgets (android.view.View)


Android s GUI toolkit include all the common UI widgets like text labels, buttons, input fields, etc. Widgets can be created and attached to our activities using Java code, in Android development it is more common to do it using XML-based layout files Let s have a look at the following: TextView EditText Button RadioGroup / RadioButton
16 3

View Widgets (android.view.View)


Labels
In Android the label is referred to as a TextView. The TextView is defined in main.xml, and placed into the activity s view via a setcontentView call.
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

16 4

View Widgets (android.view.View)


Buttons: The Android Button class is actually a subclass of TextView, to define a button we can try adding the following code to our layout xml file:
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button" />

android:id is the unique identifier of the element android:layout_width/layout_height are the size of the element. In the android:text attribute we set the text that its inside the Button.

16 5

View Widgets (android.view.View)


Button : We can have more attributes to configure our Button.
android:clickable we set if the button reacts to click events android:soundEffectsEnabled We can set if this button have sounds effects when its clicked or touched. Most of the widget's attributes are shared because they have inherited them from more complex elements (Views).
16 6

View Widgets (android.view.View)


ImageView and ImageButton :
are the image based versions of TextView and button To specify the image to be used, we use the android:src attribute in the XML element, which usually references a drawable resource in the project.
<ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/icon" />

ImageButton works the same way as the regular button


16 7

View Widgets (android.view.View)


EditText :
Fields are input areas where the user can type in text To use Android fields, use the EditText widget in the layout XML file
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content" />

The EditText widget is also a subclass of the TextView, but it has many other attributes that can be specified to alter the behavior of the field
16 8

View Widgets (android.view.View)


Checkbox : To use Android checkboxes, use the CheckBox widget in the layout XML file. <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a checkbox" /> In Java, we can use the methods isChecked(), setChecked(), toggle() to check or modify the state of our checkbox. we can implement the CompoundButton.OnCheckedChangedListener interface with our activity, and use setOnCheckedChangeListener() to attach a callback function to handle the check/uncheck events.
16 9

View Widgets (android.view.View)


Radiobuttons :
Android s RadioButton widget inherits from the CompoundButton, which in turn inherits from TextView. Multiple RadioButtons can be put inside a RadioGroup, which means that only one button of the group can be selected at a time.

17 0

View Widgets (android.view.View)


<RadioGroup android:id="@+id/myRadioGroup" android:layout_width="wrap_content android:layout_height="wrap_content" android:orientation="vertical"> <RadioButtonandroid:id="@+id/radioButton01 android:text="RadioButton01" android:layout_width="wrap_content android:layout_height="wrap_content"> </RadioButton> <RadioButtonandroid:id="@+id/radioButton02 android:text="RadioButton02" android:layout_width="wrap_content android:layout_height="wrap_content"> </RadioButton> </RadioGroup>

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 Menus
Create 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

<option menu>

<sub-menu>

<context menu>

17 6

Menu Composition
Hi Hola Sub2 Home <sub-menu> Hello Long press in EditText

Sub1 Plus

Pre

Next <option menu> <context menu from EditText>

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:
<menu> , <item>, <group>
17 8

Creating a Menu Resource


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

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

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

17 9

Creating a Menu Resource


<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/new_game" android:icon="@drawable/ic_new_game" android:title="@string/new_game" /> <item android:id="@+id/help" android:icon="@drawable/ic_help" android:title="@string/help" /> </menu> 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 Menuobject
18 1

Inflating a option menu resource


Inflating 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 action


Response 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()method
18 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 called
This 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
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/file" android:icon="@drawable/file" android:title="@string/file" > <!-- "file" submenu --> <menu> <item android:id="@+id/create_new" android:title="@string/create_new" /> <item android:id="@+id/open" android:title="@string/open" /> </menu> </item> </menu>

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. TimePickerDialog
19 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 dialog
19 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 Dialog


static 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 Buttons


AlertDialog.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 List


final 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


Date
Android 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 Gallery
21 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 itself
21 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 more
21 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 AdapterView
Filling 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 side
22 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<String> adapter = new ArrayAdapter<String>(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 set
22 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 android:id="@+id/actv" android:layout_width="fill_parent" android:layout_height="wrap_content" /> AutoCompleteTextView actv = (AutoCompleteTextView) this.findViewById(R.id.actv); ArrayAdapter<String> aa = new ArrayAdapter<String>(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 types
22 6

MultiAutoCompleteTextView
It requires that you give it a tokenizer that can parse the sentence and tell it whether to start suggesting again. <MultiAutoCompleteTextView android:id="@+id/mactv"
android:layout_width="fill_parent" android:layout_height="wrap_content" /> MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) this .findViewById(R.id.mactv); ArrayAdapter<String> aa2 = new ArrayAdapter<String>(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 class
You have to create ListView object yourself from resource file just like any other View object

Option #2 - Your activity extends ListActivity class


ListView object gets created by the ListActivity's contructor, so you don't need to create it yourself

23 0

Option #1 - Extending Activity Class


public 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<String> arrayAdapter = new ArrayAdapter<String>( this, // Application context R.layout.list_item, // layout description for each list item COUNTRIES); lv.setAdapter(arrayAdapter); } 23 1

Example of ListView Layout


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
23 2

Example of List Item Layout


<?xml version="1.0" encoding="UTF-8"?> <TextView xmlns:android="http://schemas.andro id.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" > </TextView>

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 screen
23 4

Option #2: Extending ListActivity


public 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<String> arrayAdapter = new ArrayAdapter<String>( 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 Spinner
public 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<CharSequence> 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


<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:layout_marginBottom="10dip" android:text="@string/planet_prompt" /> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:prompt="@string/planet_prompt" /> </LinearLayout>

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 Gallery
public 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


<?xml version="1.0" encoding="utf-8"?> <Gallery xmlns:android="http://schemas.android.com/ap k/res/android" android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" />
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 position
Adapter.getView()

A new View is returned


Expensive

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 t
public 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

Do
public 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 better
static class ViewHolder { TextView text; ImageView icon; }

24 9

Even better
public 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 <resources>. For each style you want to create, add a <style> element to the file with a name that uniquely identifies the style (this attribute is required). Then add an <item>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 <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property
25 2

Example
<!-- normal sample !--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <!-- style all the properties are moved to some resource file !--> <TextView style="@style/FillHorizontaly" android:text="@string/hello" /> <!-- definition of the style !--> <?xml version="1.0" encoding="utf-8"?> <resources> <style name="FillHorizontaly" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> </style> </resources>

25 3

Styles And Themes Inheritance


The parent attribute in the <style> 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.
<style name="GreenText" parent="@android:style/TextAppearance"> <item name="android:textColor">#80FF00</item> </style>
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
<style name="Fill"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">fill_parent</item> </style> <style name="Fill.VerticalOrientation"> <item name="android:orientation">vertical</item> </style>

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
<resources> <style name=" MyTheme "> <item name=" ... "> ... </item> <item name=" ... "> ... </item> </style> </resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <style name=" MyTheme "> <item name="panelForegroundColor"> #FFFFFFFF </item> <item name="panelBackgroundColor"> ?panelForegroundColor </item> <item name="panelTextSize"> 14 </item> <item name="menuItemTextColor"> ?panelTextColor </item> <item name="menuItemTextSize"> ?panelTextSize </item> </style> </resources>

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: <application android:theme="@style/MyTheme"> If you want to apply it to a single activity and not the whole application, edit the activity tag to add its attribute. <activity android:theme="@style/MyTheme">
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:
<item name="pageMargin">2sp</item>
25 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.
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="pageMargin" format="reference|dimension" /> </resources>

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:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello" android:layout_margin="?pageMargin"/> 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 handling
26 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 element
26 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 Activity
And having it implement the Listener interface

Using the main Activity


And 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 Advantages


You 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.

Disadvantages
If 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


Approach
Anonymous Listeners allow you to set up a separate callback for each UI element, but does add overhead by creating separate instances for each listener

Advantages
Assuming 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.

Disadvantages
If 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 <service> element as a child of the <application> element.
<manifest ... > ... <application ... > <service android:name=".ExampleService" /> ... </application> </manifest> 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 application's main thread. Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multithreading. Stops the service after all start requests have been handled, so you never have to call stopSelf(). Provides default implementation of onBind() that returns null. Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation. That's all you need: a constructor and an implementation of onHandleIntent(). If you decide to also override other callback methods, such as onCreate(), onStartCommand(), or onDestroy(), be sure to call the super implementation, so that the IntentService can properly handle the life of the worker thread.

28 1

Using IntentService
public class HelloIntentService extends IntentService { public HelloIntentService() { super("HelloIntentService"); } protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } } }

28 2

Service Life Cycle


Service Lifecycle


Two ways that a service can be used


The service can be started and allowed to run until someone stops it or it stops itself.
started by calling Context.startService() and stopped by calling Context.stopService()

The service can be operated programmatically using an interface that it defines and exports.
Clients establish a connection to the Service object and use that connection to call into the service. established by calling Context.bindService() and closed by calling Context.unbindService()

Service Life Cycle


Service Lifecycle (Cont)

Bound Services
Bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.
28 5

Bound Services(contd.)
A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service

28 6

Bound Services(contd.)
A client can bind to the service by calling bindService(). It must provide an implementation of ServiceConnection, which monitors the connection with the service. When the Android system creates the connection between the client and service, it calls onServiceConnected() on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the service
28 7

Creating a Bound Service


When creating a service that provides binding, you must provide an IBinder that provides the programming interface that clients can use to interact with the service. There are three ways you can define the interface:
Extending the Binder class Using a Messenger Using AIDL
28 8

Extending the Binder class


If your service is used only by the local application and does not need to work across processes, then you can implement your own Binder class that provides your client direct access to public methods in the service. This works only if the client and service are in the same application and process, which is most common

28 9

Extending the Binder class


Here's how to set it up:
In your service, create an instance of Binder that either :
contains public methods that the client can call returns the current Service instance, which has public methods the client can call returns an instance of another class hosted by the service with public methods the client can call

Return this instance of Binder from the onBind() callback method. In the client, receive the Binder from the onServiceConnected() callback method and make calls to the bound service using the methods provided.
29 0

Broadcast Receiver Overview

An Intent-based publishsubscribe mechanism. Great for listening system events such as SMS messages.
29 1

Broadcast Receiver
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements Your app can
Receive and react to system services (example: battery low) Receive and react to other apps broadcast announcements Initiate broadcasts to other apps
29 2

Registering
To register Broadcast Receiver, you can
Dynamically register with registerReceiver (in code) Using <register> tag in AndroidManifest.xml

29 3

1. Registering in Code

29 4

2. Registering Broadcast Receiver in Manifest

29 5

BroadcastReceiver

29 6

Sending Broadcast
Broadcast is sent using Intent and sendBroadcast or sendOrderedBroadcast methods Example:
Intent intent = new Intent( com.enlume.MSG_PRO"); sendBroadcast(intent);

29 7

Normal vs. Ordered Broadcast


Normal Broadcasts
Sent with sendBroadcast. All broadcasts are run in undefined order, often at the same time.

Ordered Broadcasts
Sent with sendOrderedBroadcast. Each receiver executes in turn. Possible to propagate a result to next receiver. Order can be controlled using android:priority tag.

29 8

Receiver Lifecycle
Broadcast Receiver object is valid only for the duration of the onReceive(Context, Intent) method.
You cannot do anything asynchronous in here! Except you can start a service.. Which can start a thread

29 9

Android - SQLite Database


Using SQL databases in Android:
Android (as well as iPhoneOS) uses an embedded standalone program called sqlite3 which can be used to:
create a database, define SQL tables, indices, queries, views, triggers , Insert rows, delete rows, change rows, run queries and administer a SQLite database file

30 0

SQLite Database
Using SQLite
SQLite implements most of the SQL-92standard for SQL. It has partial support for triggers and allows most complex queries (exception made for outer joins). SQLITE does not implement referential integrity constraints through the foreign key constraint model. SQLite uses a relaxed data typing model. Instead of assigning a type to an entire column, types are assigned to individual values. Therefore it is possible to insert a string into numeric column and so on.
30 1

SQLite Database
A way of opening/creating a SQLITE database in your local Android s data space is given below SQLiteDatabasedb = this.openOrCreateDatabase("myfriendsDB", MODE_PRIVATE, null); where the assumed prefix for the database stored in the devices ram is: "/data/data/<CURRENT_namespace>/databases/". For instance if this app is created in a namespace called cis493.sql1 , the full name of the newly created database will be: /data/data/cis493.sql1/databases/myfriendsDB . This file could later be used by other activities in the app or exported out of the emulator (adbpush ) and given to a tool such as SQLITE_ADMINISTRATOR. MODEcould be: MODE_PRIVATE, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples activities. 30 2

SQLite Database

Database is saved in the device s memory


30 3

Executing SQL commands on the Database


Once created, the database is ready for normal operations such as:
creating, altering, dropping resources (tables, indices, triggers, views, queries etc.) or administrating database resources (containers, users, ).

Actionqueries and Retrievalqueries represent the most common operations against the database.
A retrieval query is typically a SQL-Select command in which a table holding a number of fields and rows is produced as an answer to a data request. An actionquery usually performs maintenance and administrative tasks such as manipulating tables, users, environment, etc.

30 4

Creating-Populating a Table
We will use the execSQL( )method to manipulate SQL action queries. The following example creates a new table called tblAmigo. The table has three fields: a numeric unique identifier called recID, and two string fields representing our friend s nameand phone. If a table with such a name exists it is first dropped and then created anew. Finally three rows are inserted in the table.

30 5

Creating-Populating a Table
Comments
The field recIDis defined as PRIMARY KEY of the table. The autoincrement feature guarantees that each new record will be given a unique serial number (0,1,2, ). The database data types are very simple, for instance we will use: text,varchar, integer, float, numeric, date, time, timestamp, blob, boolean, and so on. In general, any well-formed SQL action command (insert, delete, update, create, drop, alter, etc.) could be framed inside an execSQL( ) method. You should make the call to execSQLinside of a try-catch-finally block. Be aware of potential SQLiteExceptionsituations thrown by the method.
30 6

Asking SQL Questions


Retrieval queries are SQL-select statements. Answers produced by retrieval queries are always held in an output table. In order to process the resulting rows, the user should provide a cursor device. Cursors allow a row-by-row access of the records returned by the retrieval queries. Android offers two mechanisms for phrasing SQL-select statements: rawQueries and simplequeries. Both return a database cursor.
Raw queries take for input a syntactically correct SQL-select statement. The select query could be as complex as needed and involve any number of tables (remember that outer joins are not supported). Simple queries are compact parametized select statements that operate on a single table (for developers who prefer not to use SQL). 30 7

Using RawQuery(version 1)
Consider the following code fragmentCursor
c1 = db.rawQuery("select count(*) as Total from tblAMIGO",null);

The previous rawQuery contains a select-statement that counts the rows in the table tblAMIGO. The result of this count is held in a table having only one row and one column. The column is called Total . The cursor c1will be used to traverse the rows (one!) of the resulting table. Fetching a row using cursor c1requires advancing to the next record in the answer set. Later the (singleton) field total must be bound to a local Java variable.
30 8

Using ParametizedRawQuery(version 2)
Using arguments.Assume we want to count how many friends are there whose name is BBB and their recID> 1. We could use the following construction
String mySQL= "select count(*) as Total " + " from tblAmigo" + " where recID> ?" + " and name = ?"; String[] args= {"1", "BBB"}; Cursor c1 = db.rawQuery(mySQL, args);
30 9

Using RawQuery(version 3)
Using arguments : Assume we want to count how many friends are there whose name is BBB and their recID> 1. We could concatenate pieces of the string. Special care around (single) quoted strings.
String[] args= {"1", "BBB"}; String mySQL= " select count(*) as Total " + " from tblAmigo" + " where recID> " + args[0] + " and name = '" + args[1] + "'"; Cursor c1 = db.rawQuery(mySQL, null);
31 0

Simple Queries
Simple queries use a template implicitly representing a condensed version of a typical (non-joining) SQL select statement. No explicit SQL statement is made. Simple queries can only retrieve data from a single table. The method s signature has a fixed sequence of seven arguments representing:
the table name, the columns to be retrieved, the search condition (where-clause), arguments for the where-clause, the group-by clause, having-clause, and the order-by clause. 31 1

Simple Queries
The signature of the Android s simple query method is: query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

31 2

CURSORS AND CONTENT VALUES


ContentValues are used to insert new rows into tables. Each Content Values object represents a single table row as a map of column names to values. Queries in Android are returned as Cursor objects. Rather than extracting and returning a copy of the result values, Cursors are pointers to the result set within the underlying data.
31 3

CURSORS AND CONTENT VALUES


The Cursor class includes a number of navigation functions :
moveToFirst : Moves the cursor to the first row in the query result moveToNext : Moves the cursor to the next row moveToPrevious : Moves the cursor to the previous row getCount : Returns the number of rows in the result set getColumnIndexOrThrow :Returns the index for the column with the specified name (throwing an exception if no column exists with that name) getColumnName : Returns the name of the specified column index getColumnNames :Returns a string array of all the column names in the current Cursor moveToPosition : Moves the Cursor to the specified row getPosition : Returns the current Cursor position 31 4

Extracting Results from a Cursor


To extract values from a result Cursor, first use the moveTo<location> methods. Then use the type safe get<type> methods (passing in a column index) to return the value stored at the current row for the specified column. String columnValue = myResult.getString(columnIndex);

31 5

Inserting New Rows


To create a new row, construct a ContentValues object and use its put methods to provide a value for each column. Insert the new row by passing the Content Values object into the insert method called on the target database along with the table name.
// Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ] // Insert the row into your table myDatabase.insert(DATABASE_TABLE, null, newValues);

31 6

Updating a Row
Updating rows is also done with Content Values. Create a new ContentValues object, using the put methods to assign new values to each column you want to update. Call update on the database, passing in the table name, the updated Content Values object, and a where clause that specifies the row(s) to update
// Define the updated row content. ContentValues updatedValues = new ContentValues(); // Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ] String where = KEY_ID + "=" + rowId; // Update the row with the specified index with the new values. myDatabase.update(DATABASE_TABLE, newValues, where, null);

31 7

Deleting Rows
To delete a row simply call delete on a database, specifying the table name and a where clause that returns the rows you want to delete.
myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null);

31 8

Introducing the SQLiteOpenHelper


SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases. By implementing an SQLite Open Helper you hide the logic used to decide if a database needs to be created or upgraded before it s opened. Extend the SQLiteOpenHelper class by overriding the constructor, onCreate, and onUpgrade methods to handle the creation of a new database and upgrading to a new version respectively. To use an implementation of the helper class, create a new instance, passing in the context, database name, and current version, and a CursorFactory Call getReadableDatabase or getWritableDatabase to open and return a readable/writable instance of the underlying database.
31 9

Content Providers
Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications; there's no common storage area that all Android packages can access. Android ships with a number of content providers for common data types (audio, video, images, personal contact information, and so on). You can see some of them listed in the android.provider package.
32 0

Content Providers
If you want to make your own data public, you have two options:
You can create your own content provider you can add the data to an existing provider if there's one that controls the same type of data and you have permission to write to it.

Common interface for querying the data. Applications do not call these methods directly.
They use a ContentResolver object and call its methods instead.
ContentResolver cr = getContentResolver();

A ContentResolver can talk to any content provider.


32 1

Content Providers
Content providers expose their data as a simple table on a database model, where each row is a record and each column is data of a particular type and meaning. A query returns a Cursor object that can move from record to record and column to column to read the contents of each field. Content provider exposes a public URI that uniquely identifies its data set
URIs begin with content:// Android Provides constants for native content providers, for example:
ContactsContract.Contacts.CONTENT_URI 32 2

Querying a Content Provider


To query a content provider, you can use either:
ContentResolver.query() Activity.managedQuery()

Both methods take the same set of arguments, and both return a Cursor object. ManagedQuery() causes the activity to manage the life cycle of the Cursor. A managed Cursor handles all of the niceties, such as unloading itself when the activity pauses, and requerying itself when the activity restarts. To restrict a query to just one record, you can append the _ID value for that record to the URI that is, place a string matching the ID as the last segment of the path part of the URI.
For example, if the ID is 23, the URI would be: content://. . . ./23

There are some helper methods, particularly ContentUris.withAppendedId() and Uri.withAppendedPath(), that make it easy to append an ID to a URI 32 3

Querying a Content Provider


Content Provider queries take a very similar form to database queries. Using the query method on the ContentResolver object, pass in:
The URI of the content provider data you want to query A projection that represents the columns you want to include in the result set A where clause that defines the rows to be returned. You can include ? wild cards that will be replaced by the values stored in the selection argument parameter. An array of selection argument strings that will replace the ? s in the where clause A string that describes the order of the returned rows
32 4

Querying a Content Provider


// Return all rows Cursor allRows = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null); // Return all columns for rows where column 3 equals a set value // and the rows are ordered by column 5. String where = KEY_COL3 + = + requiredValue; String order = KEY_COL5; Cursor someRows = getContentResolver().query(MyProvider.CONTENT_URI, null, where, null, order);
32 5

Adding, Updating, and Deleting Content


Data kept by a content provider can be modified by:
Adding new records Adding new values to existing records Batch updating existing records Deleting records

All data modification is accomplished using ContentResolver methods. If you don't have permission to write to a content provider, the ContentResolver methods will fail

32 6

Inserts
The Content Resolver offers two methods for inserting new records into your Content Provider
Insert bulkInsert.

Both methods accept the URI of the item type you re adding; where the former takes a single new ContentValues object, the latter takes an array. The simple insert method will return a URI to the newly added record BulkInsert returns the number of successfully added items
32 7

Inserts
// Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ] Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues); // Create a new row of values to insert. ContentValues[] valueArray = new ContentValues[5]; // TODO: Create an array of new rows int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI, valueArray);

32 8

Deletes
To delete a single record using the Content Resolver, call delete, passing in the URI of the row you want to remove. Alternatively, you can specify a where clause to remove multiple rows.
// Remove a specific row. getContentResolver().delete(myRowUri, null, null); // Remove the first five rows. String where = _id < 5 ; getContentResolver().delete(MyProvider.CONTENT_URI, where, null);

32 9

Updates
Updates to a Content Provider are handled using the update method on a Content Resolver. The update method takes the following :
URI of the target Content Provider ContentValues object that maps column names to updated values A where clause that specifi es which rows to update

33 0

Updates
// Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Create a replacement map, specifying which columns you want to // update, and what values to assign to each of them. newValues.put(COLUMN_NAME, newValue); // Apply to the first 5 rows. String where = _id < 5 ; getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);

33 1

Native Android Content Providers


Android exposes many Content Providers that supply access to the native databases.
Browser CallLog Contacts MediaStore Settings

33 2

Querying Native Content Provider


You need
URI
ContactsContract.Contacts.CONTENT_URI

Names Of data fields (result comes in table)


ContactsContract.Contacts.DISPLAY_NAME

Data types of those fields


String

Remember to modify the manifest file for permissions!


33 3

Query
// Get a cursor over every contact. Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null); // Let the activity manage the cursor lifecycle. startManagingCursor(cursor); // Use the convenience properties to get the index of the columns int nameIdx = cursor.getColumnIndexOrThrow(People.NAME); int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER); String[] result = new String[cursor.getCount()]; if (cursor.moveToFirst()) do { // Extract the name. String name = cursor.getString(nameIdx); // Extract the phone number. String phone = cursor.getString(phoneIdx); result[cursor.getPosition()] = name + ( + phone + ) ; } while(cursor.moveToNext());

33 4

Modifying the Manifest


<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package= com.enlume.provider" android:versionCode="1" android:versionName="1.0"> ... <uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission> </manifest>

33 5

Implementing your own Content Provider


Set up a system for storing data For example, SQLite or flat file Extend ContentProvider class Declare the Content Provider in manifest

33 6

Extend ContentProvider
public class MyContentProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://fi.tamk.phonenumber"); @Override public int delete(Uri uri, String selection, String[] selectionArgs) {...} @Override public String getType(Uri uri) {...} @Override public Uri insert(Uri uri, ContentValues values) {...} @Override public boolean onCreate() {...} @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {...} @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {...} }

33 7

Manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".CallMe" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name=".MyContentProvider" android:authorities="fi.tamk.phonenumber"></provider> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>

33 8

Querying the ContentProvider


Native Content Provider
Cursor cur = managedQuery(ContactsContract.Contacts.CONTENT _URI, null, null, null, null);

My own provider
Cursor cur = managedQuery(MyContentProvider.CONTENT_URI, null, null, null, null);

33 9

Content Providers
A content provider makes a specific set of the application's data available to other applications.


The data can be stored in the file system, in an SQLite, or in any other manner that makes sense.
Application Activity Application Activity Content Resolver Activity Application Service

Content Resolver

Content Provider

Content Resolver

Data

SQLite

XML

Remote Store

Multi-Threading
Threads
A Thread is a concurrent unit of execution. Thread has its own call stack for methods being invoked, their arguments and local variables. Each virtual machine instance has at least one main Thread running when it is started; typically, there are several others for housekeeping. The application might decide to launch additional Threads for specific purposes.
34 1

Multi-Threading
Thread Threads in the same VM interact and synchronize by the use of shared objects and monitors associated with these objects. There are basically two main ways of having a Thread execute application code.
Create a new class that extends Thread and override its run() method. Create a new Thread instance passing to it a Runnable object. In both cases, the start() method must be called to actually execute the new Thread.

34 2

Multi-Threading

34 3

Advantages of MultiThreading
Threads share the process' resources but are able to execute independently. Applications responsibilities can be separated
main thread runs UI, and slow tasks are sent to background threads.

Threading provides an useful abstraction of concurrent execution. Particularly useful in the case of a single process that spawns multiple threads on top of a multiprocessor system. In this case real parallelism is achieved. Consequently, a multithreaded program operates faster on computer systems that have multiple CPUs.

34 4

Disadvantages of Multi-Threading
Code tends to be more complex Need to detect, avoid, resolve deadlocks

34 5

Multi-Threading
When an application is launched, the system creates a thread called "main" for the application. The main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widgets, including drawing events. It is also the thread where your application interacts with running components of the Android UI toolkit.
34 6

Multi-Threading
This single-thread model can yield poor performance unless your application is implemented properly. If everything is happening in a single thread, performing long operations on the UI thread will block the whole user interface. If the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with "application not responding" (ANR) dialog
34 7

Multi-Threading
Here's an example of a click listener downloading an image over the network and displaying it in an ImageView:
public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork(); mImageView.setImageBitmap(b); } }).start(); }

The Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In this piece of code above, the ImageView is manipulated on a worker thread, which can cause really weird problems
34 8

Multi-Threading
Android offers several ways to access the UI thread from other threads
Handler objects Posting Runnable objects to the main view. Using AsyncTask class

34 9

Handler Class
When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, intent receivers, etc) and any windows they create. You can create your own secondary threads, and communicate back with the main application thread through a Handler. When you create a new Handler, it is bound to the message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

35 0

Threads and UI
Warning
Background threads are not allowed to interact with the UI. Only the main process can access the (main) activity s view. (Global) class variables can be seen and updated in the threads

35 1

Handler s MessageQueue
A secondary thread that wants to communicate with the main thread must request a message token using the obtainMessage() method. Once obtained, the background thread can fill data into the message token and attach it to the Handler s message queue using the sendMessage() method. The Handler uses the handleMessage() method to continuously attend new messages arriving to the main thread. A message extracted from the process queue can either return some data to the main process or request the execution of runnable objects through the post() method.

35 2

Multi-Threading

35 3

Multi-Threading

35 4

Messages
To send a Message to a Handler, the thread must first invoke obtainMessage() to get the Message object out of the pool. There are a few forms of obtainMessage(), allowing you to just create an empty Message object, or messages holding arguments Example
// thread 1 produces some local data String localData = Greeting from thread 1 ; // thread 1 requests a message & adds localData to it Message mgs = myHandler.obtainMessage (1, localData);

35 5

sendMessage Methods
You deliver the message using one of the sendMessage...() family of methods, such as
sendMessage() puts the message at the end of the queue immediately sendMessageAtFrontOfQueue() puts the message at the front of the queue immediately (versus the back, as is the default), so your message takes priority over all others sendMessageAtTime() puts the message on the queue at the stated time, expressed in the form of milliseconds based on system uptime (SystemClock.uptimeMillis()) sendMessageDelayed() puts the message on the queue after a delay, expressed in milliseconds
35 6

Processing Messages
To process messages sent by the background threads, your Handler needs to implement the listener handleMessage( . . . ) which will be called with each message that appears on the message queue. There, the handler can update the UI as needed. However, it should still do that work quickly, as other UI work is suspended until the Handler is done.

35 7

Using the AsyncTask class

35 8

Using the AsyncTask class


AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by

35 9

Using the AsyncTask class

36 0

Using the AsyncTask class

36 1

Example: Using the AsyncTask class

36 2

Example: Using the AsyncTask class

36 3

Example: Using the AsyncTask class

36 4

Example: Using the AsyncTask class

36 5

Debugging An Android APP


Debugging is a methodical process of finding and reducing the number of bugs and defects in a computer program. Ways to debug an application in Android : Logcat : Android provides a general-purpose logging package that you can take advantage of to log informational or error messages from your running application Eclipse Debugger: Eclipse provides a source-level debugger that the Android SDK connects with the running Dalvik bytecode, so you have all the debug capability you d normally expect from a Java program running under Eclipse. Android Debug Bridge (adb) : This provides a command-line debugging interface to a running Android phone or emulator
36 6

Debugging An Android APP


Ways to debug an application in Android :
DDMS : Android also provides a special windoworiented debugging environment custom tailored for Android and the Dalvik VM. Traceview : An Android-specific utility that tracks all the method calls your application executed and the time spent in each method.

36 7

Debugging An Android APP


Using Log Cat : To open the Logcat window: go to Window > Show view > Other, Android > Logcat. Logcat has different levels of logging. V stands for Verbose (lowest priority) D stands for Debug I stand for Info W stands for Warning E stands for Error To use Logcat you have to import android.util.Log in your project. Then you can call the static class Log. You can also filter the Log for making it more clean: Click in the + sign of your Logcat window at the right side of screen, and add new Filter with tag name
36 8

Debugging An Android APP


Eclipse Debugger
Eclipse provides a built-in Debugger , in which you can set breakpoints where the program will pause, and allow you to step through the program line by line and inspect the values of variables, amongst other features. To open the Debugger: go to Window->Open Perspective->-Debug and set the Break Point. Debug the application by right click on the selected project and click on the debug as ->android application or by click on the bug button in the tool bar
36 9

Debugging An Android APP


Eclipse Debugger Step Into () or F5 key: The next expression on the currently-selected line to be executed is invoked, and execution suspends at the next executable line in the method that is invoked. Step Over () or F6 key: The currently-selected line is executed and suspends on the next executable line. Step Return () orF7 key: Execution resumes until the next return statement in the current method is executed, and execution suspends on the next executable line.
37 0

You might also like