• Like
PPT Companion to Android
Upcoming SlideShare
Loading in...5
×

PPT Companion to Android

  • 14,451 views
Uploaded on

A complete power point presentation on Android. …

A complete power point presentation on Android.
(favorite the presentation if you like it !)

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
14,451
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
1,840
Comments
0
Likes
13

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1.  
  • 2. Few reasons to go MAD…
    • Smart Phones
      • Internet access anywhere
      • Social networking
    • Millions of mobile users
    • Open standards
  • 3. 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
  • 4. Why Android
    • Android was designed as a platform for software development.
    • Android is open .
    • Android is free.
    • Community support.
    • Tool support.
  • 5. 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
  • 6.  
  • 7. 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)
  • 8. 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
  • 9. Android Architecture
  • 10. Linux Kernel
    • Android relies on Linux version 2.6 for core system services such as device drivers, security, memory management ,process management.
    • The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
  • 11.
    • Includes a set of C/C++ libraries.
    • Interface through Java.
    • Surface manager – Handling UI Windows.
    • 2D and 3D graphics.
    • Media codecs, SQLite, Browser engine.
  • 12.
    • Dalvik VM (translator between the application side and the operating system)
      • Dex files (.dex)format
      • Compact and efficient than class files
      • Limited memory and battery power
    • Core Libraries
      • Java 5 Std edition
      • Collections, I/O etc…
  • 13. 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
  • 14. 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.
  • 15. Android applications are compiled to Dalvik byte code Write app in Java Compiled in Java Transformed to Dalvik byte code Linux OS Loaded into Dalvik VM
  • 16. Android SDK  ADT: Android Development Tool, an Eclipe plugin  Two debuggers  adb : Android Debug Bridge  ddms : Dalvik Debug Monitor Server  aapk : Android Application package tool  All resources are bundled into an archive, called apk file.  dx : java byte code to Dalvik executable translator
  • 17. 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
  • 18. Differences between Apple and Android Specification Apple Android Ownership Apple Proprietary Google open Source Compatible 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 Devices Messaging SMS , MMS ,email SMS , MMS , email and C2DM Web Browser Safari Open source Web kit layout engine coupled with Chrome’s V8 JavaScript engine Connectivity Wi-Fi, Bluetooth Wi-Fi, Bluetooth and NFC Multitasking Supported Supported Other device connectivity (Internet) Bluetooth (Internet Tethering) Hotspot feature with Wi-Fi
  • 19. Differences between Apple and Android Specification Apple Android Chrome 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
  • 20. Android applications have common structure Views such as lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data 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
  • 21. Android applications have common structure Broadcast receivers can trigger intents that start an application Data storage provide data for your apps, and can be shared between apps – database, file, and shared preferences (hash map) used by group of applications 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
  • 22. Replacing & Reusing Components GMail Contacts Home Blogger Chat Client component makes a request for a specific action “ Pick photo” Picasa System picks best component for that action New components can use existing functionality Blogger Photo Gallery
  • 23. There is a common file structure for applications code images files UI layouts constants Autogenerated resource list
  • 24. Hello World !!!
    • 1. Create a new Android Project
      • Select File > New > Android Project
    • 2. Fill out the project details
      • Enter HelloWorld for Project Name
      • Select “ Create new project in workspace ”
      • Enter HelloWorld in App name.
      • Enter com.enlume.HelloWorld in Package Name
      • Enter HelloWorld in Activity name (and yes we want to create an Activity)
  • 25. Project Properties 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.
  • 26. The Automatic* Portions…
    • Left: Manifest (* not that automatic)
    • Right: R class and the android library (no need to touch)
  • 27. The Automatic* Portions…
    • Left: Source directories, where your classes go…
    • Right: Resources (this is what gets automatically build into the R class)
  • 28. A word about the emulator
    • You can create different Run configurations for different target devices.
    • It is possible to target different resolutions (HVGA, HVGA-P, HVGA-L, etc)
    • Network speed and latency, etc.
    • Use the AVD manager and the ‘Run->Run configurations’ to manipulate
  • 29. Run hello world
    • Select the root of the project.
    • Click in the ‘green play icon’.
    • Pick Android Project
    • That will get the emulator going…
  • 30. The AndroidManifest lists application details
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • package=&quot;com.my_domain.app.helloactivity&quot;>
    • <application android:label=&quot;@string/app_name&quot;>
    • <activity android:name=&quot;.HelloActivity&quot;>
    • <intent-filter>
    • <action android:name=&quot;android.intent.action.MAIN&quot;/>
    • <category android:name=&quot;android.intent.category.LAUNCHER&quot;/>
    • </intent-filter>
    • </activity>
    • </application>
  • 31. 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 &quot;package&quot; attribute defines the base package for the following Java elements
  • 32. The AndroidManifest File
    • &quot;android:versionName&quot; and &quot;android:versionCode&quot; specify the version of your application.
    • intent filter registered defines that this activity is started once the application starts (action android:name=&quot;android.intent.action.MAIN&quot;).
    • The category definition (category android:name=&quot;android.intent.category.LAUNCHER&quot; ) defines that this application is added to the application directory on the Android device.
    • The &quot;uses-sdk&quot; part defines the minimal SDK version your application is valid for.
  • 33. 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.
  • 34. Activities (continue)
  • 35. Activities (continue)
  • 36. Activities vs Tasks (Apps)
    • A concrete class in the API
    • An encapsulation of a particular operation
    • They run in the process of the .APK which installed them
    • Optionally associated with a window (UI)
    • An execution Context
    • More of a notion than a concrete API entity
    • A collection of related Activities
    • Capable of spanning multiple processes
    • Associated with their own UI history stack
    • What users on other platforms know as “applications”
  • 37. Activities and Tasks (Cont)
    • Tasks (Cont)
      • All activities in a task are arranged in a stack.
      • If one activity starts another, the new activity is pushed on the stack and it becomes the running activity.
      • When the user presses the BACK key, the current activity is popped from the stack and the previous one resumes.
  • 38. Managing Tasks
    • Android manages tasks and the back stack by placing all activities started in succession in the same task and in a &quot;last in, first out&quot; 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.
  • 39. 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
  • 40. Activities and Tasks (Cont)
    • Launch modes allow you to define how a new instance of an activity is associated with the current task
      • There are four launch modes:
    • standard (default) / singleTop / singleTask / singleInstance
      • A launch mode can be set for each activity:
  • 41. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points:
        • Which task will hold the activity that responds to the intent
    New Activity Activity A Root Activity Original Task Activity A Root Activity Original Task New Activity New Task standard/singleTop without FLAG_ACTIVITY_NEW_TASK singleTask/singleInstance
  • 42. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points: (Cont)
        • Whether there can be multiple instances of the activity
          • A &quot;standard&quot; or &quot;singleTop&quot; activity can be instantiated many times.
          • A &quot;singleTask&quot; or &quot;singleInstance&quot; 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
  • 43. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points: (Cont)
        • Whether the instance can have other activities in its task
    &quot;standard&quot;
    • These modes permit multiple activities to belong to the task.
    • A &quot;singleTask&quot; activity will always be the root activity of the task.
    &quot;singleTop&quot; &quot;singleTask&quot; &quot;singleInstance&quot;
    • An activity stands alone as the only activity in its task.
  • 44. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points: (Cont)
        • Whether a new instance of the class will be launched to handle a new intent
    Activity B Activity A Activity C Original Task Activity D An intent arrives for an activity of type D Activity B Activity A Activity C Activity D Activity D If D is&quot;standard&quot; Activity B Activity C Activity D If D is&quot;singleTop&quot; The existing instance D is expected to handle the new intent (since it's at the top of the stack) Activity A
  • 45. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points: (Cont)
        • Whether a new instance of the class will be launched to handle a new intent (Cont)
    Activity B Original Task An intent arrives for an activity of type B If B is&quot;singleInstance&quot; A &quot;singleInstance&quot; activity is always at the top of the stack, so it is always in position to handle the intent. Activity B
  • 46. Activities and Tasks (Cont)
    • Launch Modes (Cont)
      • The modes differ from each other on four points: (Cont)
        • Whether a new instance of the class will be launched to handle a new intent (Cont)
    Activity B Original Task An intent arrives for an activity of type B If B is&quot;singleTask&quot; 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&quot;singleTask&quot; Activity B cannot handle the intent since it is not in position and the intent is dropped. Activity B Activity A Activity A
  • 47. Activities and Tasks (Cont)
  • 48. Activities and Tasks (Cont)
    • Using Intent Flags :
      • FLAG_ACTIVITY_NEW_TASK :Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().
      • FLAG_ACTIVITY_SINGLE_TOP: If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity.
      • FLAG_ACTIVITY_NO_HISTORY : This flag implies that the called activity is not kept in the task’s stack. When navigating away, the user cannot return to it.
      • FLAG_ACTIVITY_CLEAR_TOP If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()).
  • 49. Activities and Tasks (Cont)
    • Affinities
      • An affinity means a preference for each activity to belong to a certain task.
      • An individual affinity can be set for each activity:
      • By default, a new activity is launched into the task of the activity that called startActivity().
  • 50. Activities and Tasks (Cont)
    • Affinities (Cont)
      • Two circumstances where the affinity comes into play:
        • FLAG_ACTIVITY_NEW_TASK flag
    • If the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity.
          • If there's already an existing task with the same affinity as the new activity, the activity is launched into that task.
          • If not, it begins a new task.
      • allowTaskReparenting attribute
    • If an activity has its allowTaskReparenting attribute set to &quot;true&quot;, it can move from the task it starts in to the task it has an affinity for when that task comes to the fore.
  • 51. Activities and Tasks (Cont)
    • Clearing the Stack
      • Default Control
    • If the user leaves a task for a long time, the system clears the task of all activities except the root activity.
      • Some activity attributes that can be used to modify the default control:
        • If alwaysRetainTaskState is set to the root activity of a task
          • The task retains all activities in its stack even after a long period.
        • If clearTaskOnLaunch is set to the root activity of a task
          • The stack is cleared down to the root activity whenever the user leaves the task and returns to it.
          • The user always returns to the task in its initial state, even after a momentary absence.
  • 52. Activities and Tasks (Cont)
    • Clearing the Stack (Cont)
      • Some activity attributes that can be used to modify the default control: (Cont)
        • If finishOnTaskLaunch is set to an activity of a task
          • - The activity remains part of the task only for the current session.
          • - If the user leaves and then returns to the task, it no longer is present.
      • Another way to force activities to be removed from the stack ( FLAG_ACTIVITY_CLEAR_TOP flag):
        • If an intent includes the FLAG_ACTIVITY_CLEAR_TOP flag and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away.
  • 53. 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
  • 54. 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().
  • 55. 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=&quot;.ExampleActivity&quot; />       ...   </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
  • 56. 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 &quot;main&quot; action and should be placed in the &quot;launcher&quot; 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
  • 57. 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
  • 58. 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.
  • 59. 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 &quot;running&quot;.)
      • 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
  • 60. 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.
  • 61. Android Activity Life Cycle
    • Activities have several states
    • Lifecycle methods are called on transitions
    • You typically don’t need to use them all, but they are there
  • 62. 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
  • 63. 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
  • 64. 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 &quot;resumes&quot;), 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.
  • 65. 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
  • 66. 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 &quot;back stack&quot;), 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)
  • 67. Tasks and Back Stack
  • 68. 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 .
  • 69. Application Life Cycle (1) System Process Home Process Home Mail Message Browser Map Mail Process Browser Process Map Process
  • 70. Application Life Cycle (2) System Process Home Process Home Map Browser Message Mail Map Process Browser Process Mail Process
  • 71. Intents & Intent Filters
  • 72. 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
  • 73. 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
  • 74. 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”
  • 75. 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
  • 76. Intent Object Structure
  • 77. Intent Object Structure Is Made Of
    • Component name
    • Action
    • Data
    • Category
    • Extras
    • Flags
  • 78. 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 &quot; com.enlume.ForwardTargetActivity&quot;)
    • 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”
  • 79. 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 e xtras fields - much as a method name determines a set of arguments and a return value.
  • 80. 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.
  • 81. Data Field
    • Examples of Action/Data Pairs
      • ACTION_VIEW content://contacts/people/1 – Display information about the person whose identifier is &quot;1&quot;.
      • 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 &quot;1&quot;.
      • 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.
  • 82. 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
  • 83. 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
  • 84. 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 &quot;timezone“ extra that identifies the new time zone
      • ACTION_HEADSET_PLUG action has a &quot;state&quot; extra indicating whether the headset is now plugged in or unplugged , as well as a &quot;name&quot; extra for the type of headset
  • 85. 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).
  • 86. Intent Resolution
  • 87. What is Intent Resolution?
    • Android's scheme of determining which target component should be selected for handling a passed intent
  • 88. 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.
  • 89. 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
  • 90. What are Intent Filters?
    • Filters describe and advertise the capabilities of a target component
      • Informs the system which implicit intents a component can handle
    • If a component does not have any intent filters, it can receive only explicit intents.
    • A component with filters can receive both explicit and implicit intents.
    • A component has separate filters for each job it can do
  • 91. Where are Filters Specified?
    • Filters are specified for each component in the AndroidManifest.xml file
    • <manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; ...>
    • <application android:icon=&quot;@drawable/app_notes&quot; ... >
    • <activity android:name=&quot;NoteEditor&quot;
    • android:theme=&quot;@android:style/Theme.Light&quot;
    • android:label=&quot;@string/title_note&quot; >
    • <intent-filter android:label=&quot;@string/resolve_edit&quot;>
    • <action android:name=&quot;android.intent.action.VIEW&quot; />
    • <action android:name=&quot;android.intent.action.EDIT&quot; />
    • <action android:name=&quot;com.android.notepad.action.EDIT_NOTE&quot; />
    • <category android:name=&quot;android.intent.category.DEFAULT&quot; />
    • <data android:mimeType=&quot;vnd.android.cursor.item/vnd.google.note&quot; />
    • </intent-filter>
    • <intent-filter>
    • <action android:name=&quot;android.intent.action.INSERT&quot; />
    • <category android:name=&quot;android.intent.category.DEFAULT&quot; />
    • <data android:mimeType=&quot;vnd.android.cursor.dir/vnd.google.note&quot; />
    • </intent-filter>
    • </activity>
    • ...
  • 92. Intent Filters Intent Resolution
  • 93. 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?
  • 94. How Android System Perform Intent Resolution (for Implicit Intents)?
    • An implicit Intent object are tested against an intent filters (of target components) in three areas
      • Action
      • Category
      • Data (both URI and data type)
    • To be delivered to the target component that owns the filter, it must pass all three tests.
    • If an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate.
    • If no target can be found, an exception is raised
  • 95. 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.
  • 96. 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
  • 97. Category Test - android.intent.category.DEFAULT
    • Android treats all implicit intents passed to startActivity() as if they contained at least one category: &quot;android.intent.category.DEFAULT“ (the CATEGORY_DEFAULT constant).
    • Therefore, activities that are willing to receive implicit intents must include &quot;android.intent.category.DEFAULT&quot; in their intent filters.
  • 98. Data Test
    • Example
    • <intent-filter . . . >
    • <data android:mimeType=&quot;video/mpeg&quot; android:scheme=&quot;http&quot; . . . />
    • <data android:mimeType=&quot;audio/mpeg&quot; android:scheme=&quot;http&quot; . . . />
    • . . .
    • </intent-filter>
    • Each <data> element can specify a data type (MIME media type) and URI.
  • 99. 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 &quot;content&quot;, the host is &quot;com.example.project&quot;, the port is &quot;200&quot;, and the path is &quot;folder/subfolder/etc&quot;.
      • 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.
  • 100. Data Test - Mime media type
    • It's more common in filters than a URI.
    • Both the Intent object and the filter can use a &quot;*“ wildcard for the subtype field — for example, &quot;text/*&quot; or &quot;audio/*&quot; — indicating any subtype matches.
  • 101. 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
  • 102. Intent Resolution – Special Use Cases
  • 103. .MAIN Action & .LAUNCHER Category
    • Activities that can initiate applications have filters with &quot; android.intent.action.MAIN&quot; 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 &quot; android.intent.category.LAUNCHER&quot; category:
    • <intent-filter . . . >
    • <action android:name=&quot;code android.intent.action.MAIN&quot; />
    • <category android:name=&quot;code android.intent.category.LAUNCHER&quot; />
    • </intent-filter>
  • 104. .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 &quot;android.intent.action.MAIN&quot; action and &quot;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 &quot;android.intent.category.HOME&quot; in its filter
  • 105. User Interface In Android
  • 106. 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.
  • 107. View and ViewGroup
    • One or more Views can be grouped together into a ViewGroup.
    • The ViewGroup class serves as the base for subclasses called &quot;layouts,&quot; which offer different kinds of layout architecture, like linear, tabular and relative.
    • A ViewGroup derives from the base class.
    • android.view.ViewGroup
  • 108. View Hierarchy
    • All the views in a window are arranged in a tree you show the tree by calling setContentView(rootNode) in the activity
  • 109. 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.
  • 110. 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).
  • 111. 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.
  • 112. Advantages of Option #1: Declaring UI in XML
    • Separation of the presentation from the code that controls its behavior
      • You can modify UI without having to modify your source code and recompile
      • For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages
    • Easier to visualize the structure of your UI (without writing any code)
      • Easier to design/debug UI
      • Visualizer tool (like the one in Eclipse IDE)
  • 113. 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.
  • 114. Example: Layout File
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <LinearLayout
    • xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;fill_parent&quot;
    • android:orientation=&quot;vertical&quot; >
    • <TextView android:id=&quot;@+id/text&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:text=&quot;Hello, I am a TextView&quot; />
    • <Button android:id=&quot;@+id/button&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:text=&quot;Hello, I am a Button&quot; />
    • </LinearLayout>
  • 115. Where to create Layout file?
    • Save the file with the .xml extension, in your Android project's res/layout/ directory
  • 116. 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);
    • }
  • 117. 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 &quot;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
  • 118. 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=&quot;@+id/my_button&quot;
  • 119. 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=&quot;@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.
  • 120. How to reference views in Java code?
    • Assuming a view/widget is defined in the layout file with a unique ID
      • <Button android:id=&quot;@+id/my_button&quot;
      • android:layout_width=&quot;wrap_content&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • android:text=&quot;@string/my_button_text&quot;/>
    • Then you can make a reference to the view object via findViewById(R.id.<string-id>).
      • Button myButton = (Button) findViewById(R.id.my_button);
  • 121. 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.
  • 122.
    • Parent view group defines layout parameters for each child view (including the child view group)
  • 123. 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=&quot;@+id/my_button&quot;
      • android:layout_width=&quot;match_parent&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • android:text=&quot;@string/my_button_text&quot;/>
  • 124. Linear Layout fill_parent fill_parent Some Button... fill_parent wrap_content
  • 125. Layout Types
    • All layout types are subclass of ViewGroup class
    • Layout types
      • LinearLayout
      • RelativeLayout
      • TableLayout
      • FrameLayout
      • Tab layout
  • 126. 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
  • 127. 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()
  • 128. LinearLayout
  • 129. LinearLayout
    • Linear Layout: Fill Model
    • Widgets have a &quot;natural&quot; 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
  • 130. 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.
  • 131. LinearLayout
    • Linear Layout: Fill Model
  • 132. 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=&quot;1“ whereas the EditText control has android:layout_weight=&quot;2“
  • 133. 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.
  • 134. 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 &quot;cell&quot; and the actual widget contents.
      • Note: Padding is analogous to the margins on a word processing document.
  • 135. LinearLayout
    • Linear Layout: Padding
    • Example: The EditText box has been changed to display 30px of padding all around
  • 136. LinearLayout LinearLayout vertical LinearLayout horizontal weight=0.5 weight=0.5
  • 137. 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.
  • 138. RelativeLayout toRightOf 1 1 parentTop parentLeft layout_below button1 2 parentBottom toRightOf 1
  • 139. RelativeLayout : LayoutParams @+id/green @+id/red android:layout_above=&quot;@id/green&quot; android:layout_below=&quot;@id/red&quot; @+id/green @+id/red android:layout_toLeftOf=&quot;@id/green&quot; android:layout_toRightOf=&quot;@id/red&quot;
  • 140. RelativeLayout : LayoutParams @+id/red @+id/red @+id/green android:layout_alignBottom=&quot;@id/red&quot; @+id/green android:layout_alignTop=&quot;@id/red&quot; @+id/green android:layout_alignLeft=&quot;@id/red&quot; @+id/green android:layout_alignRight=&quot;@id/red&quot;
  • 141. RelativeLayout : LayoutParams android:layout_alignParentTop=&quot;true&quot; android:layout_alignParentLeft=&quot;true&quot; android:layout_alignParentBottom=&quot;true&quot; android:layout_alignParentRight=&quot;true&quot; parent @+id/red @+id/red
  • 142. RelativeLayout Example
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:background=&quot;@drawable/blue&quot;
    • android:padding=&quot;10px&quot; >
    • <TextView android:id=&quot;@+id/label&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:text=&quot;Type here:&quot; />
    • <EditText android:id=&quot;@+id/entry&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:background=&quot;@android:drawable/editbox_background&quot;
    • android:layout_below=&quot;@id/label&quot; />
    • <Button android:id=&quot;@+id/ok&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:layout_below=&quot;@id/entry&quot;
    • android:layout_alignParentRight=&quot;true&quot;
    • android:layout_marginLeft=&quot;10px&quot;
    • android:text=&quot;OK&quot; />
    • <Button android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:layout_toLeftOf=&quot;@id/ok&quot;
    • android:layout_alignTop=&quot;@id/ok&quot;
    • android:text=&quot;Cancel&quot; />
    • </RelativeLayout>
  • 143. 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.
  • 144. 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.
  • 145. 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=&quot;URL:&quot; />
    • <EditText
    • android:id=&quot;@+id/entry&quot;
    • android:layout_span=&quot;3&quot; />
    • </TableRow>
  • 146. 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).
  • 147. Table Layout Example
  • 148. Table Layout
    • By default, each column will be sized according to the &quot;natural&quot; 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.
  • 149. Table Layout
    • In our running example we stretch columns 2, 3, and 4 to fill the rest of the row.
  • 150. 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).
  • 151. Frame Layout Example
    • <FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:layout_width=&quot;match_parent&quot;
    • android:layout_height=&quot;match_parent&quot;>
    • <TextView
    • android:text=&quot;yellowyellowyellow&quot;
    • android:gravity=&quot;bottom&quot;
    • android:background=&quot;#aaaa00&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;120dip&quot;/>
    • <TextView
    • android:text=&quot;greengreengreen&quot;
    • android:gravity=&quot;bottom&quot;
    • android:background=&quot;#00aa00&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;90dip&quot; />
    • <TextView
    • android:text=&quot;blueblueblue&quot;
    • android:gravity=&quot;bottom&quot;
    • android:background=&quot;#0000aa&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;60dip&quot; />
    • <TextView
    • android:text=&quot;redredred&quot;
    • android:gravity=&quot;bottom&quot;
    • android:background=&quot;#aa0000&quot;
    • android:layout_width=&quot;wrap_content&quot;
    • android:layout_height=&quot;30dip&quot;/>
    • </FrameLayout>
  • 152. 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.
  • 153. Example of ScrollView
  • 154. 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.
  • 155. 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
  • 156. Adapting to Display Orientation
  • 157. 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
  • 158. Adapting to Display Orientation ANCHORING VIEWS LANDSCAPE PORTRAIT
  • 159. 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
  • 160. 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
  • 161. 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---
    • }
  • 162. 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_ORIENTATION_LANDSCAPE);
      • setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      • you can also use the android:screenOrientation attribute on the <activity> element in AndroidManifest.xml
  • 163. 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
  • 164. 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=&quot;fill_parent&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • android:text=&quot;@string/hello&quot;
      • />
  • 165. 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=&quot;fill_parent&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • android:text=&quot;Button&quot;
      • />
      • 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.
  • 166. 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).
  • 167. 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=&quot;fill_parent&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • android:src=&quot;@drawable/icon&quot;
      • />
      • ImageButton works the same way as the regular button
  • 168. 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=&quot;fill_parent&quot;
      • android:layout_height=&quot;wrap_content&quot;
      • />
      • 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
  • 169. View Widgets (android.view.View)
    • Checkbox :
      • To use Android checkboxes, use the CheckBox widget in the layout XML file.
      • <CheckBox android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;This is a checkbox&quot; />
      • 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.
  • 170. 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.
  • 171. View Widgets (android.view.View)
    • <RadioGroup android:id=&quot;@+id/myRadioGroup&quot;
    • android:layout_width=&quot;wrap_content“ android:layout_height=&quot;wrap_content&quot;
    • android:orientation=&quot;vertical&quot;>
    • <RadioButtonandroid:id=&quot;@+id/radioButton01“
    • android:text=&quot;RadioButton01&quot;
    • android:layout_width=&quot;wrap_content” android:layout_height=&quot;wrap_content&quot;>
    • </RadioButton>
    • <RadioButtonandroid:id=&quot;@+id/radioButton02“
    • android:text=&quot;RadioButton02&quot;
    • android:layout_width=&quot;wrap_content“ android:layout_height=&quot;wrap_content&quot;>
    • </RadioButton>
    • </RadioGroup>
  • 172. 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(&quot;PropertyApp&quot;, &quot;button01 has just been pressed&quot;);
    • }
    • });
  • 173. 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, &quot;No radio button was selected.&quot;);
    • } else if (checkedID == R.id.radioButton01) {
    • Log.d(TAG, &quot;'radioButton01' was selected.&quot;);
    • } else if (checkedID == R.id.radioButton02) {
    • Log.d(TAG, &quot;'radioButton02' was selected.&quot;);
    • }
  • 174. 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 &quot;action items.&quot;
  • 175. 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.
  • 176. Creating Menus
    • Create an application that supports options/sub/context menus
    <option menu> <sub-menu> <context menu> Automatically fill “Hi!” in the EditText Plus menu will also open a sub-menu Display messages when a menu clicked
  • 177. Menu Composition Plus Home Pre Next <option menu> Sub1 Sub2 Hi Hola Hello <sub-menu> <context menu from EditText> Long press in EditText
  • 178. 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>
  • 179. 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
  • 180. Creating a Menu Resource
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> <menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;>     <item android:id=&quot;@+id/new_game&quot;           android:icon=&quot;@drawable/ic_new_game&quot;           android:title=&quot;@string/new_game&quot; />     <item android:id=&quot;@+id/help&quot;           android:icon=&quot;@drawable/ic_help&quot;           android:title=&quot;@string/help&quot; /> </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.
  • 181. 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
  • 182. Inflating a option menu resource
    • Inflating a menu resource (menu.xml) by adding onCreateOptionsMenu(Menu menu) in the main Activity.
    • Menu items in menu.xml will appear when the user touches the MENU button
    public boolean onCreateOptionsMenu (Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu. menu , menu); return true; }
  • 183. Response to user action
    • Response to menu click events by overriding onOptionsItemSelected(Menu menu) in the main Activity.
    •   You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item
    @Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id.menuItemPlus: Toast.makeText(this, &quot;Plus Button Clicked !&quot;, Toast.LENGTH_SHORT).show(); Log.i(TAG,&quot;menuItemPlus&quot;); return true; : : case R.id.menuItemNext: Toast.makeText(this, &quot;Next Button Clicked !&quot;, Toast.LENGTH_SHORT).show(); Log.i(TAG,&quot;menuItemNext&quot;); return true; } return false; }
  • 184. 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
  • 185. 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)
  • 186. Populating Menu with Menu Items: #1
    • // Override this method of Activity class in order to create menu items.
    • @Override
    • public void onCreateContextMenu(
    • ContextMenu menu, // Context menu that is being built
    • View view, // The view for which the context menu is being built
    • ContextMenuInfo menuInfo) {
    • super.onCreateContextMenu(menu, view, menuInfo);
    • menu.setHeaderTitle(&quot;Context menu&quot;);
    • menu.add(0, Menu.FIRST , Menu.NONE, &quot;menu #1&quot;);
    • menu.add(0, Menu.FIRST + 1, Menu.NONE, &quot;menu #2&quot;);
    • menu.add(0, Menu.FIRST + 2, Menu.NONE, &quot;menu #3&quot;);
    • menu.add(0, Menu.FIRST + 3, Menu.NONE, &quot;menu #4&quot;);
    • }
  • 187. 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.
  • 188. 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;
    • }
  • 189. 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.).
  • 190. Creating Submenus
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> <menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;>     <item android:id=&quot;@+id/file&quot;           android:icon=&quot;@drawable/file&quot;           android:title=&quot;@string/file&quot; >         <!-- &quot;file&quot; submenu -->         <menu>             <item android:id=&quot;@+id/create_new&quot;                   android:title=&quot;@string/create_new&quot; />             <item android:id=&quot;@+id/open&quot;                   android:title=&quot;@string/open&quot; />         </menu>     </item> </menu>
  • 191. 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
  • 192. 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
  • 193. 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 &quot;owner&quot; of each dialog
  • 194. 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
  • 195. 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);
  • 196. 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)
  • 197. 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().
  • 198. Creating an Alert Dialog
  • 199. Creating an Alert Dialog – Adding Buttons
    • AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(&quot;Are you sure you want to exit?&quot;)        .setCancelable(false)        .setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                 MyActivity.this.finish();            }        })        .setNegativeButton(&quot;No&quot;, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                 dialog.cancel();            }        }); AlertDialog alert = builder.create();
  • 200. Creating an Alert Dialog – Adding List
    • final CharSequence[] items = {&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(&quot;Pick a color&quot;); 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();
  • 201. 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 = {&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(&quot;Pick a color&quot;); 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();
  • 202. 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, &quot;&quot;,                         &quot;Loading. Please wait...&quot;, true);
  • 203. 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 &quot;STYLE_HORIZONTAL&quot; 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.
  • 204. 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.
  • 205. 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)
  • 206. Date/Time Selection Widgets
  • 207. Date/Time Selection Widgets
  • 208. Date/Time Selection Widgets
  • 209. Date/Time Selection Widgets
  • 210. Date/Time Selection Widgets
  • 211. 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).
  • 212. LIST CONTROLS
  • 213. 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
  • 214. Understanding Adapters
  • 215. 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
  • 216. 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
  • 217. 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
  • 218. 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
  • 219. 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).
  • 220. Handling User Selections
    • You handle the user's selection by setting the class's AdapterView.OnItemClickListener member to a listener and catching the selection changes
    • // Create a message handling object as an anonymous class.
    • private OnItemClickListener mMessageClickedHandler = new
    • OnItemClickListener() {
    • public void onItemClick(AdapterView parent, View v, int position, long id){
    • // Display a messagebox.
    • Toast.makeText(mContext,&quot;You've got an event&quot;,
    • 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);
  • 221. Getting to Know SimpleCursorAdapter
  • 222. 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
  • 223. 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&quot;,”Bhutan&quot;,”Nepal”});
  • 224. 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
  • 225. 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=&quot;@+id/actv&quot;
    • android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; />
    • AutoCompleteTextView actv = (AutoCompleteTextView) this.findViewById(R.id.actv);
    • ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
    • android.R.layout.simple_dropdown_item_1line,
    • new String[] {&quot;English&quot;, &quot;Hebrew&quot;, &quot;Hindi&quot;, &quot;Spanish&quot;, &quot;German&quot;, &quot;Greek&quot;
    • });
    • actv.setAdapter(aa);
  • 226. 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
  • 227. 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=&quot;@+id/mactv&quot;
    • android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; />
    • MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) this
    • .findViewById(R.id.mactv);
    • ArrayAdapter<String> aa2 = new ArrayAdapter<String>(this,
    • android.R.layout.simple_dropdown_item_1line,
    • new String[] {&quot;English&quot;, &quot;Hebrew&quot;, &quot;Hindi&quot;, &quot;Spanish&quot;, &quot;German&quot;, &quot;Greek&quot; });
    • mactv.setAdapter(aa2);
    • mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
  • 228. AutoCompleteTextViews
  • 229. 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
  • 230. 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
  • 231. Option #1 - Extending Activity Class
    • public class HelloListView extends Activity {
    • @Override
    • public void onCreate(Bundle savedInstanceState) {
    • super.onCreate(savedInstanceState);
    • setContentView(R.layout.main);
    • // Since HelloListView extends Activity (instead of ListActivity),
    • // we have to create ListView object ourselves.
    • ListView lv =(ListView)findViewById(R.id.listview);
    • ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    • this, // Application context
    • R.layout.list_item, // layout description for each list item
    • COUNTRIES);
    • lv.setAdapter(arrayAdapter);
    • }
  • 232. Example of ListView Layout
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:orientation=&quot;vertical&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;fill_parent&quot;>
    • <ListView
    • android:id=&quot;@+id/listview&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;/>
    • </LinearLayout>
  • 233. Example of List Item Layout
    • <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • <TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;fill_parent&quot;
    • android:padding=&quot;10dp&quot;
    • android:textSize=&quot;16sp&quot;
    • >
    • </TextView>
  • 234. 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
  • 235. Option #2: Extending ListActivity
    • public class HelloListView extends ListActivity {
    • // Array as a data source
    • static final String[] COUNTRIES = new String[] {
    • &quot;Yemen&quot;, &quot;Yugoslavia&quot;, &quot;Zambia&quot;, &quot;Zimbabwe&quot;
    • };
    • @Override
    • public void onCreate(Bundle savedInstanceState) {
    • super.onCreate(savedInstanceState);
    • // Create an adapter from Array data source object
    • ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    • this, // Application context
    • R.layout.list_item, // layout description for each list item
    • COUNTRIES); // String array of countries defined
    • // Notice that this does not load a layout file for the Activity (which you
    • // usually do with setContentView(int)). Instead, setListAdapter(ListAdapter)
    • // automatically adds a ListView to fill the entire screen of the ListActivity.
    • setListAdapter(arrayAdapter);
    • }
    • }
  • 236. 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
  • 237. Example of Spinner
    • public class HelloSpinner extends Activity {
    • /** Called when the activity is first created. */
    • @Override
    • public void onCreate(Bundle savedInstanceState) {
    • super.onCreate(savedInstanceState);
    • setContentView(R.layout.main);
    • Spinner spinner = (Spinner) findViewById(R.id.spinner);
    • ArrayAdapter<CharSequence> adapter =
    • ArrayAdapter.createFromResource(
    • this,
    • R.array.planets_array,
    • android.R.layout.simple_spinner_item);
    • adapter.setDropDownViewResource(
    • android.R.layout.simple_spinner_dropdown_item);
    • spinner.setAdapter(adapter);
    • spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
    • }
  • 238. Example of Spinner Layout
    • <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • <LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:orientation=&quot;vertical&quot;
    • android:padding=&quot;10dip&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;>
    • <TextView
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:layout_marginTop=&quot;10dip&quot;
    • android:layout_marginBottom=&quot;10dip&quot;
    • android:text=&quot;@string/planet_prompt&quot;
    • />
    • <Spinner
    • android:id=&quot;@+id/spinner&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:prompt=&quot;@string/planet_prompt&quot;
    • />
    • </LinearLayout>
  • 239. 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.
  • 240. Gallery Class
    • A child class of AdapterView class
    • A view that shows items in a centerlocked, horizontally scrolling list
  • 241. Example of Gallery
    • public class HelloGallery extends Activity {
    • @Override
    • public void onCreate(Bundle savedInstanceState) {
    • super.onCreate(savedInstanceState);
    • setContentView(R.layout.main);
    • Gallery g = (Gallery) findViewById(R.id.gallery);
    • g.setAdapter(new ImageAdapter(this));
    • g.setOnItemClickListener(new OnItemClickListener() {
    • public void onItemClick(AdapterView parent,
    • View v, int position, long id) {
    • Toast.makeText(HelloGallery.this, &quot;&quot; +
    • position, Toast.LENGTH_SHORT).show();
    • }
    • });
    • }
  • 242. Example of Gallery Layout
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <Gallery xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • android:id=&quot;@+id/gallery&quot;
    • android:layout_width=&quot;fill_parent&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • />
  • 243. 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.
  • 244. 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.
  • 245. 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.
  • 246. Do you even know how ListView works?
  • 247. Don’t
    • public View getView(int position, View convertView, ViewGroup parent) {
    • View item = mInflater.inflate(R.layout.list_item_icon_text, null);
    • ((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
    • ((ImageView) item.findViewById(R.id.icon)).setImageBitmap(
    • (position & 1) == 1 ? mIcon1 : mIcon2);
    • return item;
    • }
  • 248. Do
    • public View getView(int position, View convertView, ViewGroup parent) {
    • if (convertView == null) {
    • convertView = mInflater.inflate(R.layout.item, null);
    • }
    • ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]);
    • ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap(
    • (position & 1) == 1 ? mIcon1 : mIcon2);
    • return convertView;
    • }
  • 249. Even better
    • static class ViewHolder {
    • TextView text;
    • ImageView icon;
    • }
  • 250. Even better
    • public View getView(int position, View convertView, ViewGroup parent) {
    • ViewHolder holder;
    • if (convertView == null) {
    • convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
    • holder = new ViewHolder();
    • holder.text = (TextView) convertView.findViewById(R.id.text);
    • holder.icon = (ImageView) convertView.findViewById(R.id.icon);
    • convertView.setTag(holder);
    • } else {
    • holder = (ViewHolder) convertView.getTag();
    • }
    • holder.text.setText(DATA[position]);
    • holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
    • return convertView;
    • }
  • 251. 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.
  • 252. 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
  • 253. Example
    • <!-- normal sample !--> <TextView     android:layout_width=&quot;fill_parent&quot;     android:layout_height=&quot;wrap_content&quot;     android:text=&quot;@string/hello&quot; /> <!-- style all the properties are moved to some resource file !--> <TextView     style=&quot;@style/FillHorizontaly&quot;     android:text=&quot;@string/hello&quot; />
    • <!-- definition of the style !--> <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?> <resources>     <style name=&quot;FillHorizontaly&quot; parent=&quot;@android:style/TextAppearance.Medium&quot;>         <item name=&quot;android:layout_width&quot;>fill_parent</item>         <item name=&quot;android:layout_height&quot;>wrap_content</item>     </style> </resources>
  • 254. 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=&quot;GreenText&quot; parent=&quot;@android:style/TextAppearance&quot;>     <item name=&quot;android:textColor&quot;>#80FF00</item> </style>
  • 255. 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=&quot;Fill&quot;>    <item name=&quot;android:layout_width&quot;>fill_parent</item>    <item name=&quot;android:layout_height&quot;>fill_parent</item> </style> <style name=&quot;Fill.VerticalOrientation&quot;>    <item name=&quot;android:orientation&quot;>vertical</item> </style>
  • 256. Using Themes
    • One problem with styles is that you need to add an attribute specification of style=&quot;@style/...&quot; 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.
  • 257. Using Themes
    • <resources>
    • <style name=&quot; MyTheme &quot;>
    • <item name=&quot; ... &quot;> ... </item>
    • <item name=&quot; ... &quot;> ... </item>
    • </style>
    • </resources>
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <resources>
    • <style name=&quot; MyTheme &quot;>
    • <item name=&quot;panelForegroundColor&quot;> #FFFFFFFF </item>
    • <item name=&quot;panelBackgroundColor&quot;> ?panelForegroundColor </item>
    • <item name=&quot;panelTextSize&quot;> 14 </item>
    • <item name=&quot;menuItemTextColor&quot;> ?panelTextColor </item>
    • <item name=&quot;menuItemTextSize&quot;> ?panelTextSize </item>
    • </style>
    • </resources>
  • 258. 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=&quot;@style/MyTheme&quot;>
    • 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=&quot;@style/MyTheme&quot;>
  • 259. 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= &quot;pageMargin&quot; >2sp</item>
  • 260. 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= &quot;1.0&quot;  encoding= &quot;utf-8&quot; ?> <resources>     <attr name= &quot;pageMargin&quot;  format= &quot;reference|dimension&quot;  /> </resources>
  • 261. 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= &quot;fill_parent&quot;     android:layout_height= &quot;wrap_content&quot;     android:text= &quot;Hello&quot;     android:layout_margin= &quot;?pageMargin&quot; />
  • 262. 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.
  • 263. 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
  • 264. 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
  • 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
  • 266. 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)
  • 267. 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
  • 268. Using a separate Listener class
  • 269. Using a separate Listener class
  • 270. 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
  • 271. Using an anonymous inner class
  • 272. 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
  • 273. Using the main Activity
  • 274.
  • 275. 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.
  • 276. Services
    • A service can essentially take two forms:
    • Started :
      • A service is &quot;started&quot; 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 &quot;bound&quot; 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.
  • 277. 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()
  • 278. 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.
  • 279. 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=&quot;.ExampleService&quot; />       ...   </application> </manifest>
  • 280. 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.
  • 281. 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.
  • 282. Using IntentService
    • public class HelloIntentService extends IntentService {   public HelloIntentService() {       super(&quot;HelloIntentService&quot;);   }   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) {               }           }       }   } }
  • 283. Service Life Cycle
    • Service Lifecycle
      • Two ways that a service can be used
        • The service can be started and allowed to run until someone stops it or it stops itself.
          • started by calling Context.startService() and stopped by calling Context.stopService()
        • The service can be operated programmatically using an interface that it defines and exports.
          • Clients establish a connection to the Service object and use that connection to call into the service.
          • established by calling Context.bindService() and closed by calling Context.unbindService()
  • 284. Service Life Cycle
    • Service Lifecycle (Cont)
  • 285. 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.
  • 286. 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
  • 287. 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
  • 288. 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
  • 289. 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
  • 290. 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.
  • 291. Broadcast Receiver Overview
    • An Intent-based publish-subscribe mechanism.
    • Great for listening system events such as SMS messages.
  • 292. 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
  • 293. Registering
    • To register Broadcast Receiver, you can
      • Dynamically register with registerReceiver (in code)
      • Using <register> tag in AndroidManifest.xml
  • 294. 1. Registering in Code
  • 295. 2. Registering Broadcast Receiver in Manifest
  • 296. BroadcastReceiver
  • 297. Sending Broadcast
    • Broadcast is sent using Intent and sendBroadcast or sendOrderedBroadcast methods
    • Example:
      • Intent intent = new Intent(“com.enlume.MSG_PRO&quot;);
      • sendBroadcast(intent);
  • 298. 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.
  • 299. 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
  • 300. 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
  • 301. 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.
  • 302. SQLite Database
    • A way of opening/creating a SQLITE database in your local Android’s data space is given below
    • SQLiteDatabasedb = this.openOrCreateDatabase(&quot;myfriendsDB&quot;, MODE_PRIVATE, null);
    • where the assumed prefix for the database stored in the devices ram is: &quot;/data/data/<CURRENT_namespace>/databases/&quot;.
    • 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.
  • 303. SQLite Database
    • Database is saved in the device’s memory
  • 304. 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.
  • 305. 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.
  • 306. 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.
  • 307. 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).
  • 308. Using RawQuery(version 1)
    • Consider the following code fragmentCursor
    • c1 = db.rawQuery(&quot;select count(*) as Total from tblAMIGO&quot;,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.
  • 309. 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= &quot;select count(*) as Total &quot;
    • + &quot; from tblAmigo&quot;
    • + &quot; where recID> ?&quot;
    • + &quot; and name = ?&quot;;
    • String[] args= {&quot;1&quot;, &quot;BBB&quot;};
    • Cursor c1 = db.rawQuery(mySQL, args);
  • 310. 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= {&quot;1&quot;, &quot;BBB&quot;};
    • String mySQL= &quot; select count(*) as Total &quot;
    • + &quot; from tblAmigo&quot;
    • + &quot; where recID> &quot; + args[0]
    • + &quot; and name = '&quot; + args[1] + &quot;'&quot;;
    • Cursor c1 = db.rawQuery(mySQL, null);
  • 311. 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.
  • 312. 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)
  • 313. 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.
  • 314. 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
  • 315. 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);
  • 316. Inserting New Rows
    • To create a new row, construct a ContentValues object and use its put methods to provide a value for each column.
    • Insert the new row by passing the Content Values object into the insert method called on the target database — along with the table name.
    • // Create a new row of values to insert.
    • ContentValues newValues = new ContentValues();
    • // Assign values for each row.
    • newValues.put(COLUMN_NAME, newValue);
    • [ ... Repeat for each column ... ]
    • // Insert the row into your table
    • myDatabase.insert(DATABASE_TABLE, null, newValues);
  • 317. 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 + &quot;=&quot; + rowId;
    • // Update the row with the specified index with the new values.
    • myDatabase.update(DATABASE_TABLE, newValues, where, null);
  • 318. 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 + &quot;=&quot; + rowId, null);
  • 319. 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.
  • 320. 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. 
  • 321. 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.
  • 322. 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
  • 323. 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
  • 324. 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
  • 325. Querying a Content Provider
    • // Return all rows
    • Cursor allRows = getContentResolver().query(MyProvider.CONTENT_URI,
    • null, null, null, null);
    • // Return all columns for rows where column 3 equals a set value
    • // and the rows are ordered by column 5.
    • String where = KEY_COL3 + “=” + requiredValue;
    • String order = KEY_COL5;
    • Cursor someRows = getContentResolver().query(MyProvider.CONTENT_URI,
    • null, where, null, order);
  • 326. 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
  • 327. 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
  • 328. Inserts
    • // Create a new row of values to insert.
    • ContentValues newValues = new ContentValues();
    • // Assign values for each row.
    • newValues.put(COLUMN_NAME, newValue);
    • [ ... Repeat for each column ... ]
    • Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI,
    • newValues);
    • // Create a new row of values to insert.
    • ContentValues[] valueArray = new ContentValues[5];
    • // TODO: Create an array of new rows
    • int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI,
    • valueArray);
  • 329. 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);
  • 330. 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
  • 331. 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);
  • 332. Native Android Content Providers
    • Android exposes many Content Providers that supply access to the native databases.
      • Browser
      • CallLog
      • Contacts
      • MediaStore
      • Settings
  • 333. 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!
  • 334. Query
    • // Get a cursor over every contact.
    • Cursor cursor = getContentResolver().query(People.CONTENT_URI,
    • null, null, null, null);
    • // Let the activity manage the cursor lifecycle.
    • startManagingCursor(cursor);
    • // Use the convenience properties to get the index of the columns
    • int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
    • int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    • String[] result = new String[cursor.getCount()];
    • if (cursor.moveToFirst())
    • do {
    • // Extract the name.
    • String name = cursor.getString(nameIdx);
    • // Extract the phone number.
    • String phone = cursor.getString(phoneIdx);
    • result[cursor.getPosition()] = name + “ (“ + phone + “)”;
    • } while(cursor.moveToNext());
  • 335. Modifying the Manifest
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • package=“com.enlume.provider&quot;
    • android:versionCode=&quot;1&quot;
    • android:versionName=&quot;1.0&quot;>
    • ...
    • <uses-permission android:name=&quot;android.permission.READ_CONTACTS&quot;>
    • </uses-permission>
    • </manifest>
  • 336. 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
  • 337. Extend ContentProvider
    • public class MyContentProvider extends ContentProvider {
    • public static final Uri CONTENT_URI = Uri.parse(&quot;content://fi.tamk.phonenumber&quot;);
    • @Override
    • public int delete(Uri uri, String selection, String[] selectionArgs) {...}
    • @Override
    • public String getType(Uri uri) {...}
    • @Override
    • public Uri insert(Uri uri, ContentValues values) {...}
    • @Override
    • public boolean onCreate() {...}
    • @Override
    • public Cursor query(Uri uri, String[] projection, String selection,
    • String[] selectionArgs, String sortOrder) {...}
    • @Override
    • public int update(Uri uri, ContentValues values, String selection,
    • String[] selectionArgs) {...}
    • }
  • 338. Manifest
    • <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
    • <manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    • package=&quot;fi.tamk&quot;
    • android:versionCode=&quot;1&quot;
    • android:versionName=&quot;1.0&quot;>
    • <application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;>
    • <activity android:name=&quot;.CallMe&quot;
    • android:label=&quot;@string/app_name&quot;>
    • <intent-filter>
    • <action android:name=&quot;android.intent.action.MAIN&quot; />
    • <category android:name=&quot;android.intent.category.LAUNCHER&quot; />
    • </intent-filter>
    • </activity>
    • <provider android:name=&quot;.MyContentProvider&quot;
    • android:authorities=&quot;fi.tamk.phonenumber&quot;></provider>
    • </application>
    • <uses-sdk android:minSdkVersion=&quot;8&quot; />
    • </manifest>
  • 339. Querying the ContentProvider
    • Native Content Provider
      • Cursor cur = managedQuery(ContactsContract.Contacts.CO NTENT_URI, null, null, null, null);
    • My own provider
      • Cursor cur = managedQuery(MyContentProvider.CONTENT_UR I, null, null, null, null);
  • 340. Content Providers
    • A content provider makes a specific set of the application's data available to other applications.
      • The data can be stored in the file system, in an SQLite, or in any other manner that makes sense.
    Activity Application Activity Application Activity Content Provider Service Application Data SQLite XML Remote Store Content Resolver Content Resolver Content Resolver
  • 341. 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.
  • 342. 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.
  • 343. Multi-Threading
  • 344. 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.
  • 345. Disadvantages of Multi-Threading
    • Code tends to be more complex
    • Need to detect, avoid, resolve deadlocks
  • 346. Multi-Threading
    • When an application is launched, the system creates a thread called &quot;main&quot; 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.
  • 347. 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 &quot;application not responding&quot; (ANR) dialog
  • 348. 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
  • 349. 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
  • 350. 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.
  • 351. 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
  • 352. 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.
  • 353. Multi-Threading
  • 354. Multi-Threading
  • 355. 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);
  • 356. 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
  • 357. 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.
  • 358. Using the AsyncTask class
  • 359. 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
  • 360. Using the AsyncTask class
  • 361. Using the AsyncTask class
  • 362. Example: Using the AsyncTask class
  • 363. Example: Using the AsyncTask class
  • 364. Example: Using the AsyncTask class
  • 365. Example: Using the AsyncTask class
  • 366. 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
  • 367. 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.
  • 368. 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
  • 369. 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
  • 370. 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.