370

PPT Companion to Android

Embed Size (px)

Citation preview

Page 1: PPT Companion to Android
Page 2: PPT Companion to Android

Few reasons to go MAD…

Smart Phones Internet access anywhere Social networking

Millions of mobile users Open standards

2

Page 3: PPT Companion to Android

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

Page 4: PPT Companion to Android

Why Android• Android was designed as a platform for software development.

• Android is openopen.

• Android is free.free.

• Community support.

• Tool support.

4

Page 5: PPT Companion to Android

Open Handset Alliance (OHA)

• The OHA is a group of hardware and software developers, including Google, NTT DoCoMo, Sprint Nextel, and HTC …

• Goal – Accelerate innovation in mobile – Offer consumers a richer, less expensive, and

better mobile experience• OHA have developed Android™, the first

complete, open, and free mobile platform

5

Page 6: PPT Companion to Android
Page 7: PPT Companion to Android

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

Page 8: PPT Companion to Android

Features (Contd….)• GSM Telephony (hardware dependent)• Bluetooth, EDGE, 3G, and WiFi (hardware

dependent)• Camera, GPS, compass, and accelerometer

(hardware dependent)• Rich development environment including a

device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

8

Page 9: PPT Companion to Android

Android Architecture

9

Page 10: PPT Companion to Android

Linux KernelLinux 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

Page 11: PPT Companion to Android

• 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

Page 12: PPT Companion to Android

• Dalvik VM (translator between the application Dalvik VM (translator between the application side and the operating system)side and the operating system)– Dex files (.dex)format– Compact and efficient than class files– Limited memory and battery power

• Core LibrariesCore Libraries– Java 5 Std edition– Collections, I/O etc…

12

Page 13: PPT Companion to Android

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

Page 14: PPT Companion to Android

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

Page 15: PPT Companion to Android

15

Write app in Java

Compiled in Java

Transformed to Dalvik byte code

Linux OS

Loaded into Dalvik VM

Android applications are compiled to Dalvik byte code

Page 16: PPT Companion to Android

Android SDK

16

ADT: Android Development Tool, an Eclipe pluginTwo 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

Page 17: PPT Companion to Android

Differences between Smart Phones

Feature Android Windows mobile BlackBerry

company Google Microsoft RIM

OS family Linux Windows Mobile OS

Languages Java Visual C++ C++

SDK Platform Multiplatform dependent dependent

Face book Yes Yes Yes

Multitasking Yes limited limited

17

Page 18: PPT Companion to Android

Differences between Apple and Android

Specification Apple AndroidOwnership Apple Proprietary Google open SourceCompatible Access Technology

3G,3.5G,Wi-Fi,Bluetooth 2G,3G,3.5G and 4G(GSM , CDMA,Bluetooth,Wi-Fi, and WiMAX)

Compatible Devices iPod , iPod Touch, iPhones Any DevicesMessaging SMS , MMS ,email SMS , MMS , email and

C2DMWeb Browser Safari Open source Web kit

layout engine coupled with Chrome’s V8 JavaScript engine

Connectivity Wi-Fi, Bluetooth Wi-Fi, Bluetooth and NFCMultitasking Supported SupportedOther device connectivity (Internet) Bluetooth (Internet Tethering)

Hotspot feature with Wi-Fi

18

Page 19: PPT Companion to Android

Differences between Apple and Android

Specification Apple AndroidChrome to phone Not supported Supported

3D Google Map Not Yet Supported

Email Attachments Single file only Multiple files

Google Talk Web browser chat GTalk Specific Client and Video Supported

Hardware Vendors Apple Samsung,Motorola,LG,Sony Ericsson, Dell,Huawei,HTC

3rd Party Branded OS No Supported

Adobe Flash Support Not Supported Supported

19

Page 20: PPT Companion to Android

Android applications have common structure

20

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

A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files

A Notification Manager that enables all apps to display custom alerts in the status bar

An Activity Manager that manages the life cycle of applications and provides a common navigation backstack

Page 21: PPT Companion to Android

Android applications have common structure

21

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

Services run in the background and have no UI for the user – they will update data, and trigger events

Intents specify what specific action should be performed

Activity is the presentation layer of your app: there will be one per screen, and the Views provide the UI to the activity

Page 22: PPT Companion to Android

Replacing & Reusing Components

GMail

Contacts

Home

Blogger

ChatClient component makes a request for a specific action

“Pick photo”

Picasa

System picks best component for that actionNew components can use existing functionalityBlogger

Photo Gallery

Page 23: PPT Companion to Android

There is a common file structure for applications

23

code

images

files

UI layouts

constants

Autogenerated resource list

Page 24: PPT Companion to Android

Hello World !!!

24

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)

Page 25: PPT Companion to Android

Project Properties

25

Project Name This is the name of the directory or folder on your computer that you want to contain the project.

Package Name 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".

Activity Name 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.

Application Name This is the human-readable title for your application.

Page 26: PPT Companion to Android

The Automatic* Portions…

26

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

Page 27: PPT Companion to Android

The Automatic* Portions…

27

• Left: Source directories, where your classes go…• Right: Resources (this is what gets automatically build into

the R class)

Page 28: PPT Companion to Android

A word about the emulator

28

• 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

Page 29: PPT Companion to Android

Run hello world

29

• Select the root of the project.

• Click in the ‘green play icon’.

• Pick Android Project• That will get the emulator

going…

Page 30: PPT Companion to Android

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

Page 31: PPT Companion to Android

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

Page 32: PPT Companion to Android

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

Page 33: PPT Companion to Android

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

Page 34: PPT Companion to Android

Activities (continue)

34

Page 35: PPT Companion to Android

Activities (continue)

35

Page 36: PPT Companion to Android

Activities vs Tasks (Apps)

36

• 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”

Page 37: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

37

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

Page 38: PPT Companion to Android

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

Page 39: PPT Companion to Android

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

Page 40: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

40

• 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:

Page 41: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

41

• Launch Modes (Cont) The modes differ from each other on four points:

① Which task will hold the activity that responds to the intent

New Activity

Activity A

Root Activity

Original Task

Activity A

Root Activity

Original Task

New Activity

New Task

standard/singleTopwithout

FLAG_ACTIVITY_NEW_TASK

singleTask/singleInstance

Page 42: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

42

• Launch Modes (Cont) The modes differ from each other on four points: (Cont)

② Whether there can be multiple instances of the activity

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

instance.

Activity B

Activity A

Task A

Activity D

Task B

Activity B and Activity C are

standard/singleTop

Activity C

Activity B

Activity C Activity B

Activity A

Task A

Activity C

Task B

Activity C is singleTask or singleInstance

Page 43: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

43

• Launch Modes (Cont) The modes differ from each other on four points:

(Cont)③ Whether the instance can have other activities in its

task"standard" • These modes permit multiple activities to

belong to the task.• A "singleTask" activity will always be the root activity of the task.

"singleTop""singleTask"

"singleInstance"

• An activity stands alone as the only activity in its task.

Page 44: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

44

• 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 B

Activity A

Activity C

Original Task

Activity DAn intent arrives for an activity of

type D

Activity B

Activity A

Activity C

Activity D

Activity D

If D is"standard"

Activity B

Activity C

Activity D

If D is"singleTop"

The existing instance D is expected to

handle the new intent (since it's at the top of the

stack)

Activity A

Page 45: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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

Original Task

An intent arrives for an activity of

type B

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.

Activity B

Page 46: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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

Original Task

An intent arrives for an activity of

type B

If B is"singleTask"

Activity B can handle the

intent since it is in position.

Activity B

Activity A Activity A

Activity B

Original Task

An intent arrives for an activity of

type B

If B is"singleTask"

Activity B cannot handle the

intent since it is not in position

and the intent is dropped.

Activity B

Activity A Activity A

Page 47: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(Cont)

47

Page 48: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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

Page 49: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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().

Page 50: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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 attributeIf 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.

Page 51: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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.

Page 52: PPT Companion to Android

Activities and Tasks Activities and Tasks (Cont)(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.

Page 53: PPT Companion to Android

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

Page 54: PPT Companion to Android

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

Page 55: PPT Companion to Android

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

Page 56: PPT Companion to Android

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

Page 57: PPT Companion to Android

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

Page 58: PPT Companion to Android

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

Page 59: PPT Companion to Android

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

Page 60: PPT Companion to Android

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

Page 61: PPT Companion to Android

Android Activity Life Cycle

61

• Activities have several states

• Lifecycle methods are called on transitions

• You typically don’t need to use them all, but they are there

Page 62: PPT Companion to Android

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

Page 63: PPT Companion to Android

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

Page 64: PPT Companion to Android

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

Page 65: PPT Companion to Android

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

Page 66: PPT Companion to Android

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

Page 67: PPT Companion to Android

Tasks and Back Stack

67

Page 68: PPT Companion to Android

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.

Page 69: PPT Companion to Android

Application Life Cycle (1)

System Process

Home Process

Home

Mail Process

Mail Message

Browser Process

Browser

Map Process

Map

Page 70: PPT Companion to Android

Application Life Cycle (2)

System Process

Home Process

Home

Map Process

Map

Browser Process

Browser

Mail Process

MessageMail

Page 71: PPT Companion to Android

Intents & Intent Filters

71

Page 72: PPT Companion to Android

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

Page 73: PPT Companion to Android

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

Page 74: PPT Companion to Android

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

Page 75: PPT Companion to Android

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

Page 76: PPT Companion to Android

Intent Object Structure

76

Page 77: PPT Companion to Android

Intent Object Structure Is Made Of

• Component name• Action• Data• Category• Extras• Flags

77

Page 78: PPT Companion to Android

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

Page 79: PPT Companion to Android

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

Page 80: PPT Companion to Android

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

Page 81: PPT Companion to Android

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

Page 82: PPT Companion to Android

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

Page 83: PPT Companion to Android

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 top-level application launcher.

• Many more

83

Page 84: PPT Companion to Android

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

Page 85: PPT Companion to Android

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

Page 86: PPT Companion to Android

Intent Resolution

86

Page 87: PPT Companion to Android

What is Intent Resolution?

• Android's scheme of determining which target component should be selected for handling a passed intent

87

Page 88: PPT Companion to Android

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

Page 89: PPT Companion to Android

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

Page 90: PPT Companion to Android

What are Intent Filters?

• Filters describe and advertise the capabilities of a target componentכ Informs the system which implicit intents a

component can handle• If a component does not have any intent filters, it can

receive only explicit intents.• A component with filters can receive both explicit

and implicit intents.• A component has separate filters for each job it can

do90

Page 91: PPT Companion to Android

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

Page 92: PPT Companion to Android

Intent Filters

92

Intent Resolution

Page 93: PPT Companion to Android

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

Page 94: PPT Companion to Android

How Android System Perform Intent Resolution (for Implicit Intents)?

• An implicit Intent object are tested against an intent filters (of target components) in three areasכ Actionכ Categoryכ Data (both URI and data type)

• To be delivered to the target component that owns the filter, it must pass all three tests.

• If an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate.

• If no target can be found, an exception is raised94

Page 95: PPT Companion to Android

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

Page 96: PPT Companion to Android

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

Page 97: PPT Companion to Android

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

Page 98: PPT Companion to Android

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

Page 99: PPT Companion to Android

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

Page 100: PPT Companion to Android

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.

100

Page 101: PPT Companion to Android

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

101

Page 102: PPT Companion to Android

Intent Resolution – Special Use Cases

102

Page 103: PPT Companion to Android

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

103

Page 104: PPT Companion to Android

.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

104

Page 105: PPT Companion to Android

User Interface In Android

105

Page 106: PPT Companion to Android

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.

106

Page 107: PPT Companion to Android

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

107

Page 108: PPT Companion to Android

View Hierarchy

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

108

Page 109: PPT Companion to Android

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.

109

Page 110: PPT Companion to Android

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

110

Page 111: PPT Companion to Android

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.

111

Page 112: PPT Companion to Android

Advantages of Option #1: Declaring UIin 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)

112

Page 113: PPT Companion to Android

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.

113

Page 114: PPT Companion to Android

Example: Layout File<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns: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>

114

Page 115: PPT Companion to Android

Where to create Layout file?

• Save the file with the .xml extension, in your Android project's res/layout/ directory

115

Page 116: PPT Companion to Android

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);}

116

Page 117: PPT Companion to Android

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

117

Page 118: PPT Companion to Android

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"

118

Page 119: PPT Companion to Android

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.

119

Page 120: PPT Companion to Android

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);

120

Page 121: PPT Companion to Android

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.

121

Page 122: PPT Companion to Android

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

122

Page 123: PPT Companion to Android

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"/>

123

Page 124: PPT Companion to Android

fill_parent

fill_

pare

nt

Some Button...Some Button...fill_parent

wrap_content

Linear Layout

Page 125: PPT Companion to Android

Layout Types

• All layout types are subclass of ViewGroup class• Layout types

כ LinearLayoutכ RelativeLayoutכ TableLayoutכ FrameLayoutכ Tab layout

125

Page 126: PPT Companion to Android

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

126

Page 127: PPT Companion to Android

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()

127

Page 128: PPT Companion to Android

LinearLayout

128

Page 129: PPT Companion to Android

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

129

Page 130: PPT Companion to Android

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.

130

Page 131: PPT Companion to Android

LinearLayout

• Linear Layout: Fill Model

131

Page 132: PPT Companion to Android

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“

132

Page 133: PPT Companion to Android

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.

133

Page 134: PPT Companion to Android

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.

134

Page 135: PPT Companion to Android

LinearLayout• Linear Layout: Padding• Example: The EditText box has been changed to

display 30px of padding all around

135

Page 136: PPT Companion to Android

LinearLayout

LinearLayoutLinearLayoutverticalvertical

LinearLayoutLinearLayouthorizontalhorizontal

weight=0.5weight=0.5 weight=0.5weight=0.5

Page 137: PPT Companion to Android

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.

137

Page 138: PPT Companion to Android

RelativeLayout

toRightOf 1toRightOf 111parentTopparentTopparentLeftparentLeft

layout_belowlayout_belowbutton1button1

22parentBottomparentBottomtoRightOf 1toRightOf 1

Page 139: PPT Companion to Android

RelativeLayout : LayoutParams

@+id/green@+id/green

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

android:layout_below="@id/red"

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

android:layout_toLeftOf="@id/green"

android:layout_toRightOf="@id/red"

Page 140: PPT Companion to Android

RelativeLayout : LayoutParams

@+id/red@+id/red

@+id/green@+id/greenandroid:layout_alignBottom="@id/red"

@+id/green@+id/green

android:layout_alignTop="@id/red"

@+id/red@+id/red

@+id/green@+id/green

android:layout_alignLeft="@id/red"

@+id/green@+id/green

android:layout_alignRight="@id/red"

Page 141: PPT Companion to Android

parentparent

@+id/@+id/redred

@+id/@+id/redred

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true"

RelativeLayout : LayoutParams

Page 142: PPT Companion to Android

RelativeLayout Example

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androidandroid: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

Page 143: PPT Companion to Android

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.

143

Page 144: PPT Companion to Android

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.

144

Page 145: PPT Companion to Android

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:" /><EditTextandroid:id="@+id/entry"android:layout_span="3" /></TableRow>

145

Page 146: PPT Companion to Android

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

146

Page 147: PPT Companion to Android

Table Layout Example

147

Page 148: PPT Companion to Android

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.

148

Page 149: PPT Companion to Android

Table Layout• In our running example we stretch columns 2, 3,

and 4 to fill the rest of the row.

149

Page 150: PPT Companion to Android

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

150

Page 151: PPT Companion to Android

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

1

Page 152: PPT Companion to Android

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.

152

Page 153: PPT Companion to Android

Example of ScrollView

153

Page 154: PPT Companion to Android

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.

154

Page 155: PPT Companion to Android

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 re-created.

• You can employ two techniques to handle changes in screen orientation

כ Anchoringכ Resizing and repositioning

155

Page 156: PPT Companion to Android

Adapting to Display Orientation

156

Page 157: PPT Companion to Android

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

157

Page 158: PPT Companion to Android

Adapting to Display Orientation

158

ANCHORING VIEWS

LANDSCAPE

PORTRAIT

Page 159: PPT Companion to Android

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

159

Page 160: PPT Companion to Android

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

160

Page 161: PPT Companion to Android

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

161

Page 162: PPT Companion to Android

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

162

Page 163: PPT Companion to Android

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

163

Page 164: PPT Companion to Android

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" />

164

Page 165: PPT Companion to Android

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.

165

Page 166: PPT Companion to Android

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

166

Page 167: PPT Companion to Android

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

167

Page 168: PPT Companion to Android

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

168

Page 169: PPT Companion to Android

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.

169

Page 170: PPT Companion to Android

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.

170

Page 171: PPT Companion to Android

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>

171

Page 172: PPT Companion to Android

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");}});

172

Page 173: PPT Companion to Android

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.");}

173

Page 174: PPT Companion to Android

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

174

Page 175: PPT Companion to Android

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.

175

Page 176: PPT Companion to Android

Creating MenusCreate an application that supports

options/sub/context menus

176

<option menu> <sub-menu> <context menu>

Automatically fill “Hi!” in the EditText

Plus menu willalso open a sub-menu

Display messages whena menu clicked

Page 177: PPT Companion to Android

Menu Composition

177

Plus

Home

Pre

Next

<option menu>

Sub1

Sub2

Hi

Hola

Hello<sub-menu>

<context menu from EditText>

Long press in EditText

Page 178: PPT Companion to Android

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>

178

Page 179: PPT Companion to Android

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

179

Page 180: PPT Companion to Android

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.

180

Page 181: PPT Companion to Android

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

181

Page 182: PPT Companion to Android

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

182

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

Page 183: PPT Companion to Android

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

183

@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; }

Page 184: PPT Companion to Android

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

184

Page 185: PPT Companion to Android

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)

185

Page 186: PPT Companion to Android

Populating Menu with Menu Items: #1

// Override this method of Activity class in order to create menu items.@Overridepublic void onCreateContextMenu(ContextMenu menu, // Context menu that is being builtView view, // The view for which the context menu is being builtContextMenuInfo 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");}

186

Page 187: PPT Companion to Android

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.

187

Page 188: PPT Companion to Android

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;}

188

Page 189: PPT Companion to Android

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

189

Page 190: PPT Companion to Android

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>

190

Page 191: PPT Companion to Android

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

191

Page 192: PPT Companion to Android

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

192

Page 193: PPT Companion to Android

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

193

Page 194: PPT Companion to Android

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

194

Page 195: PPT Companion to Android

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);

195

Page 196: PPT Companion to Android

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)

196

Page 197: PPT Companion to Android

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().

197

Page 198: PPT Companion to Android

Creating an Alert Dialog

198

Page 199: PPT Companion to Android

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();

199

Page 200: PPT Companion to Android

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();

200

Page 201: PPT Companion to Android

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();

201

Page 202: PPT Companion to Android

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);

202

Page 203: PPT Companion to Android

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.

203

Page 204: PPT Companion to Android

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.

204

Page 205: PPT Companion to Android

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)

205

Page 206: PPT Companion to Android

Date/Time Selection Widgets

206

Page 207: PPT Companion to Android

Date/Time Selection Widgets

207

Page 208: PPT Companion to Android

Date/Time Selection Widgets

208

Page 209: PPT Companion to Android

Date/Time Selection Widgets

209

Page 210: PPT Companion to Android

Date/Time Selection Widgets

210

Page 211: PPT Companion to Android

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

211

Page 212: PPT Companion to Android

LIST CONTROLS

212

Page 213: PPT Companion to Android

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

213

Page 214: PPT Companion to Android

Understanding Adapters

214

Page 215: PPT Companion to Android

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

215

Page 216: PPT Companion to Android

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

216

Page 217: PPT Companion to Android

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

217

Page 218: PPT Companion to Android

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

218

Page 219: PPT Companion to Android

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

219

Page 220: PPT Companion to Android

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 = newOnItemClickListener() {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);

220

Page 221: PPT Companion to Android

Getting to Know SimpleCursorAdapter

221

Page 222: PPT Companion to Android

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

222

Page 223: PPT Companion to Android

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”});

223

Page 224: PPT Companion to Android

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

224

Page 225: PPT Companion to Android

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);

225

Page 226: PPT Companion to Android

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

226

Page 227: PPT Companion to Android

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());

227

Page 228: PPT Companion to Android

AutoCompleteTextViews

228

Page 229: PPT Companion to Android

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

229

Page 230: PPT Companion to Android

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

230

Page 231: PPT Companion to Android

Option #1 - Extending Activity Class

public class HelloListView extends Activity {@Overridepublic 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 contextR.layout.list_item, // layout description for each list itemCOUNTRIES);lv.setAdapter(arrayAdapter);}

231

Page 232: PPT Companion to Android

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"><ListViewandroid:id="@+id/listview"android:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>

232

Page 233: PPT Companion to Android

Example of List Item Layout

<?xml version="1.0" encoding="UTF-8"?><TextView

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dp"android:textSize="16sp"></TextView>

233

Page 234: PPT Companion to Android

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

234

Page 235: PPT Companion to Android

Option #2: Extending ListActivity

public class HelloListView extends ListActivity {// Array as a data sourcestatic final String[] COUNTRIES = new String[] {"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"};@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Create an adapter from Array data source objectArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, // Application contextR.layout.list_item, // layout description for each list itemCOUNTRIES); // 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);}}

235

Page 236: PPT Companion to Android

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

236

Page 237: PPT Companion to Android

Example of Spinnerpublic class HelloSpinner extends Activity {/** Called when the activity is first created. */@Overridepublic 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());}

237

Page 238: PPT Companion to Android

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"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="10dip"android:layout_marginBottom="10dip"android:text="@string/planet_prompt"/><Spinnerandroid:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="wrap_content"android:prompt="@string/planet_prompt"/></LinearLayout>

238

Page 239: PPT Companion to Android

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.

239

Page 240: PPT Companion to Android

Gallery Class

• A child class of AdapterView class

• A view that shows items in a centerlocked, horizontally scrolling list

240

Page 241: PPT Companion to Android

Example of Gallerypublic class HelloGallery extends Activity {@Overridepublic 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();}});}

241

Page 242: PPT Companion to Android

Example of Gallery Layout

<?xml version="1.0" encoding="utf-8"?><Gallery

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/gallery"android:layout_width="fill_parent"android:layout_height="wrap_content"/>

242

Page 243: PPT Companion to Android

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.

243

Page 244: PPT Companion to Android

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.

244

Page 245: PPT Companion to Android

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.

245

Page 246: PPT Companion to Android

Do you even know how ListView works?

246

Page 247: PPT Companion to Android

Don’tpublic View getView(int position, View convertView, ViewGroup

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

247

Page 248: PPT Companion to Android

Dopublic View getView(int position, View convertView, ViewGroup

parent) {if (convertView == null) {convertView = mInflater.inflate(R.layout.item, null);}((TextView)

convertView.findViewById(R.id.text)).setText(DATA[position]);((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);return convertView;}

248

Page 249: PPT Companion to Android

Even better

static class ViewHolder {TextView text;ImageView icon;}

249

Page 250: PPT Companion to Android

Even betterpublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;

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

250

Page 251: PPT Companion to Android

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.

251

Page 252: PPT Companion to Android

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

252

Page 253: PPT Companion to Android

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>

253

Page 254: PPT Companion to Android

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>

254

Page 255: PPT Companion to Android

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>

255

Page 256: PPT Companion to Android

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.

256

Page 257: PPT Companion to Android

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>

257

Page 258: PPT Companion to Android

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

258

Page 259: PPT Companion to Android

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>

259

Page 260: PPT Companion to Android

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>

260

Page 261: PPT Companion to Android

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"/>

261

Page 262: PPT Companion to Android

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.

262

Page 263: PPT Companion to Android

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

263

Page 264: PPT Companion to Android

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

264

Page 265: PPT Companion to Android

265

Listener Callback Trigger

View.setOnKeyListener onKey() Press Physical Key when registered View has focus

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

View.setOnFocusChanged onFocusChanged() Focus shifts away from registered view

Page 266: PPT Companion to Android

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)

266

Page 267: PPT Companion to Android

Using a separate Listener class

• Approachכ 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

267

Page 268: PPT Companion to Android

Using a separate Listener class

268

Page 269: PPT Companion to Android

Using a separate Listener class

269

Page 270: PPT Companion to Android

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

270

Page 271: PPT Companion to Android

Using an anonymous inner class

271

Page 272: PPT Companion to Android

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

272

Page 273: PPT Companion to Android

Using the main Activity

273

Page 274: PPT Companion to Android

274

Page 275: PPT Companion to Android

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.

275

Page 276: PPT Companion to Android

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.

276

Page 277: PPT Companion to Android

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()

277

Page 278: PPT Companion to Android

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.

278

Page 279: PPT Companion to Android

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>

279

Page 280: PPT Companion to Android

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.

280

Page 281: PPT Companion to Android

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 multi-threading.כ 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.

281

Page 282: PPT Companion to Android

Using IntentServicepublic 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) { } } } }}

282

Page 283: PPT Companion to Android

Service Life CycleService 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()

Page 284: PPT Companion to Android

Service Life CycleService Life Cycle

• Service Lifecycle (Cont)

Page 285: PPT Companion to Android

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.

285

Page 286: PPT Companion to Android

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

286

Page 287: PPT Companion to Android

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

287

Page 288: PPT Companion to Android

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

288

Page 289: PPT Companion to Android

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

289

Page 290: PPT Companion to Android

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.

290

Page 291: PPT Companion to Android

Broadcast Receiver Overview

• An Intent-based publish-subscribe mechanism.

• Great for listening system events such as SMS messages.

291

Page 292: PPT Companion to Android

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

292

Page 293: PPT Companion to Android

Registering

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

293

Page 294: PPT Companion to Android

1. Registering in Code

294

Page 295: PPT Companion to Android

2. Registering Broadcast Receiver in Manifest

295

Page 296: PPT Companion to Android

BroadcastReceiver

296

Page 297: PPT Companion to Android

Sending Broadcast

• Broadcast is sent using Intent and sendBroadcast or sendOrderedBroadcast methods

• Example:כ Intent intent = new Intent(“com.enlume.MSG_PRO"); sendBroadcast(intent);

297

Page 298: PPT Companion to Android

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.

298

Page 299: PPT Companion to Android

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

299

Page 300: PPT Companion to Android

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

300

Page 301: PPT Companion to Android

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.

301

Page 302: PPT Companion to Android

SQLite Database• A way of opening/creating a SQLITE database in your local Android’s data

space is given belowSQLiteDatabasedb = 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.

302

Page 303: PPT Companion to Android

SQLite Database

• Database is saved in the device’s memory

303

Page 304: PPT Companion to Android

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.

304

Page 305: PPT Companion to Android

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.

305

Page 306: PPT Companion to Android

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.

306

Page 307: PPT Companion to Android

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

307

Page 308: PPT Companion to Android

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.

308

Page 309: PPT Companion to Android

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);

309

Page 310: PPT Companion to Android

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);

310

Page 311: PPT Companion to Android

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.

311

Page 312: PPT Companion to Android

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)

312

Page 313: PPT Companion to Android

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.

313

Page 314: PPT Companion to Android

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

314

Page 315: PPT Companion to Android

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);

315

Page 316: PPT Companion to Android

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 tablemyDatabase.insert(DATABASE_TABLE, null, newValues);

316

Page 317: PPT Companion to Android

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);

317

Page 318: PPT Companion to Android

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);

318

Page 319: PPT Companion to Android

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.

319

Page 320: PPT Companion to Android

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.

320

Page 321: PPT Companion to Android

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.

321

Page 322: PPT Companion to Android

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

322

Page 323: PPT Companion to Android

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

323

Page 324: PPT Companion to Android

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

324

Page 325: PPT Companion to Android

Querying a Content Provider

// Return all rowsCursor 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);

325

Page 326: PPT Companion to Android

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

326

Page 327: PPT Companion to Android

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

327

Page 328: PPT Companion to Android

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 rowsint count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI,valueArray);

328

Page 329: PPT Companion to Android

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);

329

Page 330: PPT Companion to Android

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

330

Page 331: PPT Companion to Android

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);

331

Page 332: PPT Companion to Android

Native Android Content Providers

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

332

Page 333: PPT Companion to Android

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!

333

Page 334: PPT Companion to Android

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 columnsint 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());

334

Page 335: PPT Companion to Android

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>

335

Page 336: PPT Companion to Android

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

336

Page 337: PPT Companion to Android

Extend ContentProvider

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

337

Page 338: PPT Companion to Android

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>

338

Page 339: PPT Companion to Android

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);

339

Page 340: PPT Companion to Android

Content ProvidersContent 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.

Activity

ApplicationActivity

Application

Activity

Content Provider

Service

Application

Data SQLite XML Remote Store

Content Resolver Content Resolver

Content Resolver

Page 341: PPT Companion to Android

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.

341

Page 342: PPT Companion to Android

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.

342

Page 343: PPT Companion to Android

Multi-Threading

343

Page 344: PPT Companion to Android

Advantages of Multi-Threading

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

344

Page 345: PPT Companion to Android

Disadvantages of Multi-Threading

• Code tends to be more complex • Need to detect, avoid, resolve deadlocks

345

Page 346: PPT Companion to Android

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.

346

Page 347: PPT Companion to Android

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

347

Page 348: PPT Companion to Android

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

348

Page 349: PPT Companion to Android

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

349

Page 350: PPT Companion to Android

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.

350

Page 351: PPT Companion to Android

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

351

Page 352: PPT Companion to Android

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.

352

Page 353: PPT Companion to Android

Multi-Threading

353

Page 354: PPT Companion to Android

Multi-Threading

354

Page 355: PPT Companion to Android

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);

355

Page 356: PPT Companion to Android

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

356

Page 357: PPT Companion to Android

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.

357

Page 358: PPT Companion to Android

Using the AsyncTask class

358

Page 359: PPT Companion to Android

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

359

Page 360: PPT Companion to Android

Using the AsyncTask class

360

Page 361: PPT Companion to Android

Using the AsyncTask class

361

Page 362: PPT Companion to Android

Example: Using the AsyncTask class

362

Page 363: PPT Companion to Android

Example: Using the AsyncTask class

363

Page 364: PPT Companion to Android

Example: Using the AsyncTask class

364

Page 365: PPT Companion to Android

Example: Using the AsyncTask class

365

Page 366: PPT Companion to Android

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

366

Page 367: PPT Companion to Android

Debugging An Android APP

• Ways to debug an application in Android :כ DDMS : Android also provides a special window-

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

367

Page 368: PPT Companion to Android

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

368

Page 369: PPT Companion to Android

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

369

Page 370: PPT Companion to Android

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.

370