Android Application Development
Upcoming SlideShare
Loading in...5
×
 

Android Application Development

on

  • 7,852 views

Training on Android SDK.

Training on Android SDK.

Statistics

Views

Total Views
7,852
Views on SlideShare
7,812
Embed Views
40

Actions

Likes
39
Downloads
301
Comments
3

3 Embeds 40

http://www.linkedin.com 38
http://pinterest.com 1
https://si0.twimg.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Android Application Development Android Application Development Presentation Transcript

  • ANDROID APPLICATION DEVELOPMENT
    Ramesh Prasad
  • INTRODUCTION
  • Android Devices
  • Mobile Operating System ?
  • A BRIEF HISTORY OF ANDROID
  • History
    Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by Andy Rubin and others
    Googleacquired Android Inc. in August 2005, making Android Inc. a wholly owned subsidiary of Google Inc.
    On November 5, 2007, the Open Handset Alliance, a consortium of several companies which include Broadcom Corporation, Google, HTC, Intel, LG, Marvell Technology Group, Motorola, Nvidia, Qualcomm, Samsung Electronics, Sprint Nextel, T-Mobile and Texas Instruments unveiled itself.
  • Licensing
    With the exception of brief update periods, Android has been available under a free software/open source license since October, 21 2008. Google published the entire source code (including network and telephony stacks) under an Apache License.
    Even though the software is open-source, device manufacturers cannot use Google's Android trademark unless Google certifies that the device complies with their Compatibility Definition Document (CDD).
    In early 2011, Google chose to temporarily withhold the source code to the tablet-only Honeycomb release.
    Honeycomb source code would not be released until after it was merged with the Gingerbread release in Ice Cream Sandwich.
  • Code Access
    Parts
    Kernel
    Android Open Source Project (AOSP)
    Kernel
    Should have access to latest shipped version => GPL requirement
    Google-maintained forks at android.git.kernel.org
    AOSP
    Usually Code-drops every 6 months
    Official AOSP branches at android.git.kernel.org
  • Code Licenses
    Kernel
    GNU General Public License (a.k.a. GPL)
    AOSP
    Mostly Apache License 2.0 (a.k.a. ASL)
    Having GPL-free user-space was a design goal
    A few GPL and LGPL parts: mainly BlueZ and DBUS
    Some key components in BSD: Bionic and Toolbox
    “external/” directory contains a mixed bag of licenses, incl. lots of GPL
  • Versions
    Ice Cream Sandwich
  • Version History
    2008 - Sept.: Android 1.0 is released
    2009 - Feb.: Android 1.1
    2009 - Apr.: Android 1.5 / Cupcake
    2009 - Sept.: Android 1.6 / Donut
    2009 - Oct.: Android 2.0/2.1 / Eclair
    2010 - May: Android 2.2 / Froyo
    2010 - Dec.: Android 2.3 / Gingerbread
    2011 - Jan : Android 3.0 / Honeycomb – Tablet-optimized
    2011 – May: Android 3.1 – USB host support
    2011 – Dec: Android 4.0 / Ice-Cream Sandwich – merge Gingerbread and Honeycomb
  • ANDROID BASICS
  • What is Android
    Android is a software stack for mobile devices that includes an operating system, middleware and key applications.
    The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
    The Android NDK is a toolset that lets you embed components that make use of native code (C/C++) in your Android applications.
  • Android Software Stack
  • Linux kernel
    Android built on Linux 2.6 kernel
    Provides security, memory management, process management, network stack, and driver model
    Abstraction layer between hardware and the software stack
  • Linux kernel – Androidsm
  • Libraries
    A set of C/C++ libraries exposed to developers through the application framework
  • Libraries
    System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
    Media Libraries - based on PacketVideo'sOpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Libraries
    Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
    FreeType - bitmap and vector font rendering
  • Libraries
    LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
    SGL - the underlying 2D graphics engine
  • Libraries
    3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
    SQLite - a powerful and lightweight relational database engine available to all applications
  • Dalvik Virtual Machine
    Runtime libraries provide most of the functionality in the core Java libraries
    Each app has a process and an instance of Dalvik VM
    Uses Dalvik Executable (.dex) format – low memory footprint
    VM is register based runs compiled Java classes
    The linux kernel provides Dalvik with needed functionality
  • Application Framework
    The framework allows developers to build cool apps
  • Application Framework
    Core System services
    Activity manager (manages application lifecycle)
    Package manager (loads apk files)
    Window manager (handles applications window manager interaction
    with surface flinger)
    Resource manager (handles media resources)
    Content providers (provides data to application)
    View system (provides widgets, views, layouts to applications)
    Hardware services
    Provides low-level access to hardware device
    Location manager
    Telephony manager
    Bluetooth service
    WiFi service / USB service / Sensor service
  • Applications
    AOSP and Non-AOSP Apps
  • Applications
    The non-AOSP apps
    Android Market
    YouTube
    Maps and Navigation
    Gmail
    Voice
    SkyMap
    ...
    Require
    CTS/CDD Compliance
    Signed agreement w/ Google
  • ANDROID APPLICATION FUNDAMENTALS
  • Application - User Interaction
  • Screen Characteristics
    Screen size
    Screen density
    Orientation
    Resolution
    Density-independent pixel (dp)
  • Screen size & Density
    Actual physical size, measured as the screen's diagonal.
    The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen.
  • Orientation
    Landscape
    Portrait
  • Resolution
    The total number of physical pixels on a screen.
    When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.
  • Density-independent pixel (dp)
    A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.
    The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen.
    At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use.
    The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels.
    You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.
  • Density Dependence
    Example application without support for different densities, as shown on low, medium, and high density screens.
    Example application with good support for different densities (it's density independent), as shown on low, medium, and high density screens
  • Alternative drawables
    36x36 for low-density
    48x48 for medium-density
    72x72 for high-density
    96x96 for extra high-density
    3:4:6:8 scaling ratio
    res/drawable-mdpi/my_icon.png        // bitmap for medium densityres/drawable-hdpi/my_icon.png        // bitmap for high densityres/drawable-xhdpi/my_icon.png       // bitmap for extra high density
  • Screen Configuration
  • Screen Configuration
  • Application Fundamentals
    Android applications are written in the Java programming language.
    The Android SDK tools compile the code—along with any data and resource files—into an Android package, an archive file with an .apk suffix.
    All the code in a single .apk file is considered to be one application and is the file that Android-powered devices use to install the application.
  • Security Sandbox
    Once installed on a device, each Android application lives in its own security sandbox:
    The Android operating system is a multi-user Linux system in which each application is a different user.
    By default, the system assigns each application a unique Linux user ID (the ID is used only by the system and is unknown to the application). The system sets permissions for all the files in an application so that only the user ID assigned to that application can access them.
    Each process has its own virtual machine (VM), so an application's code runs in isolation from other applications.
    By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.
  • Sharing Data
    However, there are ways for an application to share data with other applications and for an application to access system services:
    It's possible to arrange for two applications to share the same Linux user ID, in which case they are able to access each other's files. To conserve system resources, applications with the same user ID can also arrange to run in the same Linux process and share the same VM (the applications must also be signed with the same certificate).
    An application can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All application permissions must be granted by the user at install time.
  • What makes an Android Application
    The core framework components that define your application.
    The manifest file in which you declare components and required device features for your application.
    Resources that are separate from the application code and allow your application to gracefully optimize its behavior for a variety of device configurations.
  • Application Components
    Application components are the essential building blocks of an Android application.
    Each component is a different point through which the system can enter your application.
    Not all components are actual entry points for the user
    Each one exists as its own entity and plays a specific role—each one is a unique building block that helps define your application's overall behavior.
  • Types of application components
    Activities
    Services
    Content providers
    Broadcast receivers
  • Activities
    An activity represents a single screen with a user interface
    Example of Activities in Email Application-
    Email List
    Compose
    Read
    Etc..
    Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others.
    A different application can start any one of these activities (if the email application allows it)
    For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture.
  • Activities
  • Services
    A service is a component that runs in the background to perform long-running operations or to perform work for remote processes.
    A service does not provide a user interface.
    For example, a service might play music in the background while the user is in a different application
  • Services
  • Content Provider
    A content provider manages a shared set of application data.
    You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your application can access.
    Through the content provider, other applications can query or even modify the data (if the content provider allows it).
    For example, the Android system provides a content provider that manages the user's contact information. As such, any application with the proper permissions can query part of the content provider to read and write information about a particular person.
  • Broadcast Receiver
    A broadcast receiver is a component that responds to system-wide broadcast announcements.
    Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured.
    Applications can also initiate broadcasts
    Although broadcast receivers don't display a user interface, they may create a status bar notificationto alert the user when a broadcast event occurs.
  • Androidism
    Any application can start another application’s component.
    No “main()” function
    Intent
  • Start Another Application
    A unique aspect of the Android system design is that any application can start another application’s component.
    For example, if you want the user to capture a photo with the device camera, there's probably another application that does that and your application can use it, instead of developing an activity to capture a photo yourself.
    You don't need to incorporate or even link to the code from the camera application.
    Instead, you can simply start the activity in the camera application that captures a photo.
    When complete, the photo is even returned to your application so you can use it.
    To the user, it seems as if the camera is actually a part of your application.
  • Start Another Application
    FACEBOOK APP
    (PROCESS P1)
    FACEBOOK APP
    (PROCESS P1)
    CAMERA APP
    (PROCESS P2)
  • No MAIN()
    When the system starts a component, it starts the process for that application (if it's not already running) and instantiates the classes needed for the component.
    For example, if your application starts the activity in the camera application that captures a photo, that activity runs in the process that belongs to the camera application, not in your application's process. Therefore, unlike applications on most other systems, Android applications don't have a single entry point (there's no main() function, for example).
  • No MAIN()
    APP 2
    (PROCESS P2)
    APP 1
    (PROCESS P1)
    Camera Settings
    Some Activity
    Capture Photo
    Save Photo
    Use Photo
  • Intent
    Because the system runs each application in a separate process with file permissions that restrict access to other applications, your application cannot directly activate a component from another application.
  • Intent
    Intent to Download
  • Activating Components
    Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous message called an intent.
    Intents bind individual components to each other at runtime (you can think of them as the messengers that request an action from other components), whether the component belongs to your application or another.
  • Activating Components
    For activities and services, an intent defines the action to perform (for example, to "view" or "send" something) and may specify the URI of the data to act.
    For example, an intent might convey a request for an activity to show an image or to open a web page.
    In some cases, you can start an activity to receive a result, in which case, the activity also returns the result in an Intent
    For broadcast receivers, the intent simply defines the announcement being broadcast
  • Activating Components
    Content provider, is not activated by intents.
    It is activated when targeted by a request from a ContentResolver.
    The content resolver handles all direct transactions with the content provider so that the component that's performing transactions with the provider doesn't need to and instead calls methods on the ContentResolver object.
    This leaves a layer of abstraction between the content provider and the component requesting information (for security).
  • Manifest File
    Before the Android system can start an application component, the system must know that the component exists by reading the application's AndroidManifest.xml file (the "manifest" file).
    Your application must declare all its components in this file, which must be at the root of the application project directory.
    Activities, services, and content providers that you include in your source but do not declare in the manifest are not visible to the system and, consequently, can never run.
    However, broadcast receivers can be either declared in the manifest or created dynamically in code.
  • Manifest File
    The manifest does a number of things in addition to declaring the application's components, such as:
    Identify any user permissions the application requires, such as Internet access or read-access to the user's contacts.
    Declare the minimum API Level required by the application, based on which APIs the application uses.
    Declare hardware and software features used or required by the application, such as a camera, bluetooth services, or a multitouch screen.
    API libraries the application needs to be linked against (other than the Android framework APIs), such as the Google Maps library.
    And more
  • Declaring components
  • Declaring components
    You must declare all application components this way:
    <activity> elements for activities
    <service> elements for services
    <receiver> elements for broadcast receivers
    <provider> elements for content providers
  • Declaring component capabilities
    You can use an Intent to start activities, services, and broadcast receivers.
    Can be done by explicitly naming the target component (using the component class name) in the intent.
    However, the real power of intents lies in the concept of intent actions.
    With intent actions, you simply describe the type of action you want to perform (and optionally, the data upon which you’d like to perform the action) and allow the system to find a component on the device that can perform the action and start it.
    If there are multiple components that can perform the action described by the intent, then the user selects which one to use.
  • Declaring component capabilities
    The way the system identifies the components that can respond to an intent is by comparing the intent received to the intent filtersprovided in the manifest file of other applications on the device.
    When you declare a component in your application's manifest, you can optionally include intent filters that declare the capabilities of the component so it can respond to intents from other applications.
    For example, an email application with an activity for composing a new email might declare an intent filter in its manifest entry to respond to "send" intents (in order to send email). An activity in your application can then create an intent with the “send” action (ACTION_SEND), which the system matches to the email application’s “send” activity and launches it when you invoke the intent with startActivity().
  • Declaring application requirements
    There are a variety of devices powered by Android and not all of them provide the same features and capabilities.
    In order to prevent your application from being installed on devices that lack features needed by your application, it's important that you clearly define a profile for the types of devices your application supports by declaring device and software requirements in your manifest file.
    Most of these declarations are informational only and the system does not read them, but external services such as Android Market do read them in order to provide filtering for users when they search for applications from their device.
  • Declaring application requirements
    Important device characteristics
    Screen size and density
    Input configurations
    Device features
    Platform Version
  • Screen size and density
    In order to categorize devices by their screen type, Android defines two characteristics for each device:
    screen size (the physical dimensions of the screen) and
    screen density (the physical density of the pixels on the screen, or dpi—dots per inch).
    To simplify all the different types of screen configurations, the Android system generalizes them into select groups that make them easier to target. The screen sizes are: small, normal, large, and extra large.
    The screen densities are: low density, medium density, high density, and extra high density.
    By default, your application is compatible with all screen sizes and densities, because the Android system makes the appropriate adjustments to your UI layout and image resources.
    However, you should create specialized layouts for certain screen sizes and provide specialized images for certain densities, using alternative layout resources, and by declaring in your manifest exactly which screen sizes your application supports with the <supports-screens> element.
  • Input configurations
    Many devices provide a different type of user input mechanism, such as a hardware keyboard, a trackball, or a five-way navigation pad. If your application requires a particular kind of input hardware, then you should declare it in your manifest with the <uses-configuration> element.
  • Device features
    There are many hardware and software features that may or may not exist on a given Android-powered device, such as a camera, a light sensor, bluetooth, a certain version of OpenGL, or the fidelity of the touchscreen.
    You should never assume that a certain feature is available on all Android-powered devices (other than the availability of the standard Android library), so you should declare any features used by your application with the <uses-feature> element.
  • Platform Version
    Different Android-powered devices often run different versions of the Android platform, such as Android 1.6 or Android 2.3.
    Each successive version often includes additional APIs not available in the previous version. In order to indicate which set of APIs are available, each platform version specifies an API Level
    If you use any APIs that were added to the platform after version 1.0, you should declare the minimum API Level in which those APIs were introduced using the <uses-sdk> element.
  • API Level
    API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.
    The framework API consists of:
    A core set of packages and classes
    A set of XML elements and attributes for declaring a manifest file
    A set of XML elements and attributes for declaring and accessing resources
    A set of Intents
    A set of permissions that applications can request, as well as permission enforcements included in the system
  • API Level
    Updates to the framework API are designed so that the new API remains compatible with earlier versions of the API. That is, most changes in the API are additive and introduce new or replacement functionality.
    The framework API that an Android platform delivers is specified using an integer identifier called "API Level".
    Each Android platform version supports exactly one API Level, although support is implicit for all earlier API Levels (down to API Level 1).
  • API Level
  • Application Resources
    An Android application is composed of more than just code—it requires resources that are separate from the source code, such as images, audio files, and anything relating to the visual presentation of the application.
    you should define animations, menus, styles, colors, and the layout of activity user interfaces with XML files.
    Using application resources makes it easy to update various characteristics of your application without modifying code and—by providing sets of alternative resources—enables you to optimize your application for a variety of device configurations (such as different languages and screen sizes).
  • Application Resources
    For every resource that you include in your Android project, the SDK build tools define a unique integer ID, which you can use to reference the resource from your application code or from other resource
    One of the most important aspects of providing resources separate from your source code is the ability for you to provide alternative resources for different device configurations. sources defined in XML.
    For example, by defining UI strings in XML, you can translate the strings into other languages and save those strings in separate files. Then, based on a language qualifier that you append to the resource directory's name (such as res/values-fr/ for French string values) and the user's language setting, the Android system applies the appropriate language strings to your UI.
  • Application Resources
    Same ID (R.ID)
    but different Resource
  • DEVELOPING APPLICATIONS
  • Tools
    Eclipse
    Android Development Tools (ADT)
    SDK
    NDK
  • Steps
    Set up Android Virtual Devices or hardware devices
    Create an Android project
    Build and run your application
    Debug your application with the SDK debugging and logging tools
    Test your application with the Testing and Instrumentation framework
  • Tutorial
    Hello World
  • ACTIVITIES
  • Activity
    An Activity is an application component that provides a screen with which users can interact in order to do something
    Each activity is given a window in which to draw its user interface.
    The window typically fills the screen, but may be smaller than the screen and float on top of other windows.
  • Activity
    An application usually consists of multiple activities that are loosely bound to each other
    Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time.
    Each activity can then start another activity in order to perform different actions.
  • Back Stack
    Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack").
    When a new activity starts, it is pushed onto the back stack and takes user focus.
    The back stack abides to the basic "last in, first out" queue mechanism, so, when the user is done with the current activity and presses the BACK key, it is popped from the stack (and destroyed) and the previous activity resumes.
  • Back Stack
  • Back Stack
    Two tasks: Task A is in the background, waiting to be resumed, while Task B receives user interaction in the foreground
  • Back Stack
    A single activity is instantiated multiple times
  • Creating Activity
    Subclasss the Activity class
    Implement User Interface
    Declare Activity in the manifest
  • Sub class
    To create an activity, you must create a subclass of Activity (or an existing subclass of it).
    In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed.
  • Implement UI
    The user interface for an activity is provided by a hierarchy of views—objects derived from the View class.
    Each view controls a particular rectangular space within the activity's window and can respond to user interaction.
    For example, a view might be a button that initiates an action when the user touches it.
  • Implement UI
    Android provides a number of ready-made views that you can use to design and organize your layout.
    "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image.
    "Layouts" are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout.
    You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.
  • View & View Groups
    Widget
    Layout
  • Define UI
    The most common way to define a layout using views is with an XML layout file saved in your application resources.
    This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior.
  • Define UI
  • Creating Activity – Manifest
    You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element.
    <manifest ... >
    <application ... >
    <activity android:name=".ExampleActivity" /> ... </application ... >
    ... </manifest >
  • Creating Activity – 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.
    The android:name attribute is the only required attribute—it specifies the class name of the activity.
  • Intent Filters
    An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.
    When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:
    <activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).
  • Intent Filters
    If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example.
    Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).
    However, 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.
    For each type of intent to which you want to respond, you must include an <intent-filter> that includes an <action> element and, optionally, a <category> element and/or a <data> element. These elements specify the type of intent to which your activity can respond.
  • Lab
    Hello World Tutorial
  • 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 (and the system selects the appropriate activity for you, which can even be from a different application).
    An intent can also carrysmall amounts of data to be used by the activity that is started.
  • Starting an Activity
    When working within your own application, you'll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name.
    For example, here's how one activity starts another activity named SignInActivity:
    Intent intent = new Intent(this, SignInActivity.class);
    startActivity(intent);
  • Lab
    Create a new activity
    Start a new activity from the Main activity
  • Starting an Activity
    your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity
    Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
    startActivity(intent);
  • Lab
    Create a new activity
    Start the new activity from Main activity
    Pass data to new activity
  • 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.
  • Shutting Down an Activity
    You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().
    Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.
  • Lab
    Create a new activity
    Start the new activity for result from Main activity
    Get result from new activity
  • Managing the Activity Lifecycle
    An activity can exist in essentially three states:
    Resumed The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)
    Paused Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. 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), but can be killed by the system in extremely low memory situations.
    Stopped The activity is completely obscured by another activity (the activity is now in the "background"). 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). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.
  • Implementing the lifecycle callbacks
    When an activity transitions into and out of the different states described above, it is notified through various callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes.
  • Implementing the lifecycle callbacks
  • Activity Lifecycle
  • Saving persistent Data
    The activity is killable after-
    onPause()
    onStop()
    onDestroyed()
    onPause() is the last method that's guaranteed to be called before the process can be killed—if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called.
    Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage.
    However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.
  • Lab
    Saving Activity Data
    LunarLander
  • Saving activity state
    when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it "resumes"), those changes are still there.
    However, 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. Instead, the system must recreate the Activity object if the user navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was.
  • Saving activity state
  • Saving activity state
    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.
    The Bundle is where you can store state information about the activity as name-value pairs, using methods such as putString().
    Then, if the system kills your activity's process and the user navigates back to your activity, the system passes the Bundle to onCreate() so you can restore the activity state you saved during onSaveInstanceState().
    If there is no state information to restore, then the Bundle passed to onCreate() is null.
  • Saving activity state
    Even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState().
    Specifically, the default implementation calls onSaveInstanceState() for every View in the layout, which allows each view to provide information about itself that should be saved.
    Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated.
    For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state.
    If a widget does not have an ID, then it cannot save its state.
  • Handling configuration changes
    Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language).
    When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed immediately by onCreate()).
    The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided.
    The best way to handle a configuration change, such as a change in the screen orientation, is to simply preserve the state of your application using onSaveInstanceState() and onRestoreInstanceState() (or onCreate())
  • Lab
    Saving Activity State
    Default onSaveInstanceState() Behavior
  • Handling Runtime Changes
    Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()).
    The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources.
    Your application should be able to restart at any time without loss of user data or state
  • Handling Runtime Changes
    If restarting your Activity requires that you recover large sets of data, re-establish a network connection, or perform other intensive operations, then a full restart due to a configuration change might be an unpleasant user experience.
    Also, it may not be possible for you to completely maintain your Activity state with the Bundle that the system saves for you during the Activity lifecycle—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow.
    In such a situation, you can alleviate the burden of reinitializing your Activity by retaining a stateful Object when your Activity is restarted due to a configuration change.
  • Handling Runtime Changes
    To retain an Object during a runtime configuration change:
    Override the onRetainNonConfigurationInstance() method to return the Object you would like to retain.
    Android calls onRetainNonConfigurationInstance() between onStop() and onDestroy() when it shuts down your Activity due to a configuration change.
    When your Activity is created again, call getLastNonConfigurationInstance() to recover your Object.
  • Handling Runtime Changes
  • Activity Summary
    Activity Lifecycle
    Save persistent data
    Save persistent state
    Handle runtime configuration changes
  • USER INTERFACE
  • User Interface
    In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the View class.
    View objects are the basic units of user interface expression on the Android platform.
    The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons.
    The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative.
  • User Interface
    A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen.
    A View object handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides.
    As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events.
  • View & View Groups
    Widget
    Layout
  • View Hierarchy
  • View Hierarchy
    In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the setContentView() method and pass a reference to the root node object. The Android system receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests that its child nodes draw themselves — in turn, each view group node is responsible for calling upon each of its own child views to draw themselves.
    Android parses the elements of your layout in-order (from the top of the hierarchy tree), instantiating the Views and adding them to their parent(s). Because these are drawn in-order, if there are elements that overlap positions, the last one to be drawn will lie on top of others previously drawn to that space.
  • 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.
    You can declare your layout in two ways:
    Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
    Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
  • Layout
    The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it 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.
    Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML.
  • Declaring Layout
    The most common way to define your layout and express the view hierarchy is with an XML layout file.
    Each element in XML is either a View or ViewGroup object (or descendant thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree
  • Declaring Layout
  • Declaring Layout
    The name of an XML element is respective to the Java class that it represents. So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group.
    When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout.
  • Declaring Layout
    Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout.
    After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile.
  • Loading Layout
    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.
    Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name
    For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:
    public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout);
    }
  • XML Attributes
    Every View and ViewGroup object supports their own variety of XML attributes.
    Some attributes are specific to a View object (for example, TextView supports the textSize attribute)
    Some are common to all View objects, because they are inherited from the root View class (like the id attribute).
    And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.
  • ID
    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.
    This is an XML attribute common to all View objects (defined by the View class) and you will use it very often.
    The syntax for an ID, inside an XML tag is:
    android:id="@+id/my_button"
    The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource.
    The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file).
  • Android Framework 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, like so:
    android:id="@android:id/empty"
    With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.
  • Defining & Accessing Views
    In order to create views and reference them from the application, a common pattern is to:
    Define a view/widget in the layout file and assign it a unique ID:
    <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/>
    Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):
    Button myButton = (Button) findViewById(R.id.my_button);
  • Layout Parameters
    Visualization of a view hierarchy with layout parameters associated with each view.
  • 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 LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children.
    All view groups include a width and height (layout_width and layout_height), and each view is required to define them.
    Many LayoutParams also include optional margins and borders.
  • Layout Parameters
    You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or 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.
    In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes.
  • Layout Position
    The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.
    It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.
    In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth().
  • Layout Position
    getTop()
    getBottom()
    getLeft()
    View
    getRight()
    Parent
  • Size, Padding and Margins
  • Size, Padding and Margins
    The size of a view is expressed with a width and a height. A view actually possess pairs of width and height values.
    The pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. The width and height can be obtained by calling getWidth() and getHeight().
    To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().
  • Common layout Objects
  • Common layout Objects
  • Linear layout
  • Table Layout
  • Relative Layout
  • Lab
    XML & Layout Window
    Layouts
    Linear
    Relative
    Table
    Grid
    Tab
    List
  • Widgets
    A widget is a View object that serves as an interface for interaction with the user. Android provides a set of fully implemented widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI.
    Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kinds of widgets provided by the Android platform.
    If you'd like to do something more customized and create your own actionable elements, you can, by defining your own View object or by extending and combining existing widgets.
  • Widgets
  • Lab
    Widgets
    • Date Picker
    • Time Picker
    • Form Stuff
    • Spinner
    • Auto Complete
    • Gallery
    • Web View
  • UI Events
    Once you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, so you can perform actions. To be informed of UI events, you need to do one of two things:
    Define an event listener and register it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On<something>Listener, each with a callback method called On<something>(). For example, View.OnClickListener (for handling "clicks" on a View), View.OnTouchListener (for handling touch screen events in a View), and View.OnKeyListener (for handling device key presses within a View). So if you want your View to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define its onClick() callback method (where you perform the action upon click), and register it to the View with setOnClickListener().
    Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it.
  • Event Listener
    An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
    Included in the event listener interfaces are the following callback methods:
    onClick() From View.OnClickListener. This is called when the user either touches the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses the suitable "enter" key or presses down on the trackball.
    onLongClick() From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).
    onFocusChange() From View.OnFocusChangeListener. This is called when the user navigates onto or away from the item, using the navigation-keys or trackball.
    onKey() From View.OnKeyListener. This is called when the user is focused on the item and presses or releases a key on the device.
    onTouch() From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).
    onCreateContextMenu() From View.OnCreateContextMenuListener. This is called when a Context Menu is being built (as the result of a sustained "long click").
  • Example register an on-click listener for a Button
  • Example - OnClickListener as a part of your Activity
  • Listener Return Value
    Notice that the onClick() callback in the above example has no return value, but some other event listener methods must return a boolean. The reason depends on the event. For the few that do, here's why:
    onLongClick() - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, returntrue to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-click listeners.
    onKey() - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, return true to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-key listeners.
    onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.
  • Touch Mode
    When a user is navigating a user interface with directional keys or a trackball, it is necessary to give focus to actionable items (like buttons) so the user can see what will accept input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, then it is no longer necessary to highlight items, or give focus to a particular View. Thus, there is a mode for interaction named "touch mode."
    For a touch-capable device, once the user touches the screen, the device will enter touch mode. From this point onward, only Views for which isFocusableInTouchMode() is true will be focusable, such as text editing widgets. Other Views that are touchable, like buttons, will not take focus when touched; they will simply fire their on-click listeners when pressed.
    Any time a user hits a directional key or scrolls with a trackball, the device will exit touch mode, and find a view to take focus. Now, the user may resume interacting with the user interface without touching the screen.
  • Menus
    Menus reveals application functions and settings.
    The most common application menu is revealed by pressing the MENU key on the device.
    However, you can also add Context Menus, which may be revealed when the user presses and holds down on an item.
  • Menus
  • 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, then inflate the menu resource (load it as a programmable object) in your application code.
    Using a menu resource to define your menu is a good practice because it separates the content for the menu from your application code.
    It's also easier to visualize the structure and content of a menu in XML.
  • Creating a Menu Resource
  • Creating a Menu Resource
    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> 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.
  • 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().
  • Creating an Options Menu
    The Options Menu is where you should include basic activity actions and necessary navigation items
    the Options Menu appears at the bottom of the screen
    When opened, the first visible portion of the Options Menu is the icon menu. It holds the first six menu items.
    If you add more than six items to the Options Menu, Android places the sixth item and those after it into the overflow menu, which the user can open by touching the "More" menu item.
  • Creating an Options Menu
    When the Android system creates the Options Menu for the first time, it calls your activity's onCreateOptionsMenu() method.
    Override this method in your activity and populate the Menu that is passed into the method, Menu by inflating a menu
  • Responding to user action
    When the user selects a menu item from the Options Menu
    the system calls your activity's onOptionsItemSelected() method. This method passes the MenuItem that the user selected. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource).
    You can match this ID against known menu items and perform the appropriate action.
    Menu selection
    handled
    Menu selection
    Not handled
  • Lab
    Create menu from XML
    Handle user action
  • Creating a Context Menu
    A context menu is conceptually similar to the menu displayed when the user performs a "right-click" on a PC.
    You should use a context menu to provide the user access to actions that pertain to a specific item in the user interface.
    On Android, a context menu is displayed when the user performs a "long press" (press and hold) on an item.
  • Creating a Context Menu
    In order for a View to provide a context menu, you must "register" the view for a context menu. Call registerForContextMenu() and pass it the View you want to give a context menu. When this View then receives a long-press, it displays a context menu.
    To define the context menu's appearance and behavior, override your activity's context menu callback methods, onCreateContextMenu() and onContextItemSelected().
  • Creating a Context Menu
    Get info for the selected item
  • Lab
    Create a context Menu
    Handle user action
  • 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.).
  • Creating Submenus
    When creating your menu resource, you can create a submenu by adding a <menu> element as the child of an <item>.
  • Responding to user action
    When the user selects an item from a submenu, the parent menu's respective on-item-selected callback method receives the event.
    For instance, if the above menu is applied as an Options Menu, then the onOptionsItemSelected() method is called when a submenu item is selected.
  • Lab
    Create sub menu
    Handle user action
  • 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 (such as a progress bar or a login prompt).
  • Dialogs
    The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the following subclasses:
    AlertDialog A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type.
    ProgressDialog A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons.
    DatePickerDialog A dialog that allows the user to select a date. See the Hello DatePicker tutorial. TimePickerDialog A dialog that allows the user to select a time.
  • Creating an AlertDialog
    An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it 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)
  • Creating an AlertDialog & Adding Buttons
    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().
    User cannot
    cancel it by
    back button
  • Adding a List
  • Adding checkboxes and radio buttons
    No item should
    be selected by Default
  • Creating a ProgressDialog
    A ProgressDialog is an extension of the AlertDialog class that can display 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.
    The dialog can also provide buttons, such as one to cancel a download.
    Opening a progress dialog can be as simple as calling ProgressDialog.show().
    ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true);
    The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progress is indeterminate
  • Showing a progress bar
    To show the progression with an animated progress bar:
    Initialize the ProgressDialog with the class constructor, ProgressDialog(Context).
    Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other properties, such as the message.
    When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback.
    You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far.
  • Lab
    OK Cancel Dialog with a message
    List Dialog
    Progress Dialog
    Single choice list
  • User Notification
    User different technique:
    A Toast Notification, for brief messages that come from the background.
    A Status Bar Notification, for persistent reminders that come from the background and request the user's response.
    A Dialog Notification, for Activity-related notifications.
  • Creating Toast Notifications
    A toast notification is a message that pops up on the surface of the window.
    It only fills the amount of space required for the message and the user's current activity remains visible and interactive.
    The notification automatically fades in and out, and does not accept interaction events.
    A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service, it appears in front of the Activity currently in focus.
  • Creating Toast Notifications
    You can also chain your methods and avoid holding on to the Toast object, like this:
  • Lab
    Create Toast
  • Status Bar Notifications
  • Status Bar Notifications
    A status bar notification adds an icon to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window.
    When the user selects the expanded message, Android fires an Intent that is defined by the notification (usually to launch an Activity).
    You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.
  • Status Bar Notifications
    A status bar notification should be used for any case in which a background Service needs to alert the user about an event that requires a response.
    A background Service should never launch an Activity on its own in order to receive user interaction.
    The Service should instead create a status bar notification that will launch the Activity when selected by the user.
  • Creating Status Bar Notifications
    Get a reference to the NotificationManager:
  • Creating Status Bar Notifications
    Instantiate the Notification:
  • Creating Status Bar Notifications
    Define the Notification's expanded message and Intent:
  • Creating Status Bar Notifications
    Pass the Notification to the NotificationManager:
  • Adding Sound, vibration etc
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;
  • Lab
    App->Notification
  • Adapters
    Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, you want to bind your view to an external source of data.
    To do this, you use an AdapterView as your view group and each child View is initialized and populated with data from the Adapter.
  • AdapterView
    Gallery, ListView, and Spinner are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way.
    AdapterView objects have two main responsibilities:
    Filling the layout with data
    Handling user selections
  • SimpleCursorAdapter
  • SimpleCursorAdapter
    SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
    This adapter converts a
    row in the cursor to a child view for the container control. The definition of the child view is defined in an XML resource (layout parameter).
    A row in the cursor might have many columns, you tell the SimpleCursorAdapter which columns you want to select from the row by specifying an array of column names (using the from parameter).
    Similarly, because each column you select is mapped to a TextView, you must specify the IDs in the to parameter. There’s a one-to-one mapping between the column that you select and a TextView that displays the data in the column, so the from and to parameters must be the same size.
  • ArrayAdapter
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,new string[]{"sayed","satya"});
    code creates an ArrayAdapter where the TextView controls’ data is represented by strings.
    android.R.layout.simple_list_item_1 points to a TextView defined by the Android SDK.
  • Lab
    Data for the list comes from an array of strings
    Data comes from a cursor
    Data comes from a custom ListAdapter
    Data comes from a custom ListAdapter and handling user selection
  • Styles and Themes
    Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some of your own styles and themes.
    A style is a set of one or more formatting attributes that you can apply as a unit to individual elements in your layout. For example, you could define a style that specifies a certain text size and color, then apply it to only specific View elements.
    A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in an application, or just a single activity. For example, you could define a theme that sets specific colors for the window frame and the panel background, and sets text sizes and colors for menus. This theme can then be applied to specific activities or the entire application.
  • 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.
  • Style
  • Defining Style
    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.
  • Lab
    Style
  • APPLICATION MANIFEST
  • Application Manifest
    Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory.
    The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code.
  • Application Manifest
    The manifest does the following:
    It names the Java package for the application. The package name serves as a unique identifier for the application.
    It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
    It determines which processes will host application components.
    It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
    It also declares the permissions that others are required to have in order to interact with the application's components.
    It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
    It declares the minimum level of the Android API that the application requires.
    It lists the libraries that the application must be linked against.
  • Structure of the Manifest File
  • Elements of Manifest File
    <action><activity><activity-alias><application><category><data><grant-uri-permission><instrumentation><intent-filter><manifest><meta-data><permission><permission-group><permission-tree><provider><receiver><service><supports-screens><uses-configuration><uses-feature><uses-library><uses-permission><uses-sdk>
  • Manifest Editor
    Lab
  • APPLICATION RESOURCES
  • Application Resources
    You should always externalize resources such as images and strings from your application code, so that you can maintain them independently.
    Externalizing your resources also allows you to provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more
    Android-powered devices become available with different configurations. In order to provide compatibility with different configurations, you must organize resources in your project's res/ directory, using various sub-directories that group resources by type and configuration.
  • Application Resources
    Two different devices, both using default resources
    Two different devices, one using alternative resources
  • Providing Resources
  • Providing Resources
  • Providing Resources
  • Providing Resources
  • Providing Alternative Resources
    Screen size
    smallnormallargexlarge
    Screen aspect
    longnotlong
    • Screen orientation portland
    • Screen pixel density (dpi)
    • ldpimdpihdpixhdpinodpi
  • Accessing Resources
    When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory.
    Although the R class is where resource IDs are specified, you should never need to look there to discover a resource ID. A resource ID is always composed of:
    The resource type: Each resource is grouped into a "type," such as string, drawable, and layout.
    The resource name, which is either: the filename, excluding the extension; or the value in the XML
  • Accessing Resources
    There are two ways you can access a resource:
    In code: Using an static integer from a sub-class of your R class, such as: R.string.hello string is the resource type and hello is the resource name. There are many Android APIs that can access your resources when you provide a resource ID in this format.
    In XML: Using a special XML syntax that also corresponds to the resource ID defined in your R class, such as: @string/hello string is the resource type and hello is the resource name. You can use this syntax in an XML resource any place where a value is expected that you provide in a resource.
  • Accessing Resources in Code
    Here's the syntax to reference a resource in code:
    [<package_name>.]R.<resource_type>.<resource_name>
    <package_name> is the name of the package in which the resource is located (not required when referencing resources from your own package).
    <resource_type> is the R subclass for the resource type.
    <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).
  • Use cases
  • Accessing Resources from XML
    Here is the syntax to reference a resource in an XML resource:
    @[<package_name>:]<resource_type>/<resource_name>
    <package_name> is the name of the package in which the resource is located (not required when referencing resources from the same package)
    <resource_type> is the R subclass for the resource type
    <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).
  • Use Cases
  • INTENTS
  • Intents
    Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents.
    Intent messaging is a facility for late run-time binding between components in the same or different applications.
    The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed — or, often in the case of broadcasts, a description of something that has happened and is being announced.
  • Delivering Intents
    There are separate mechanisms for delivering intents to each type of component:
    An Intent object is passed to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new. (It can also be passed to Activity.setResult() to return information to the activity that called startActivityForResult().)
    An Intent object is passed to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Similarly, an intent can be passed to Context.bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running.
    Intent objects passed to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code.
  • Delivering Intents
    In each case, the Android system finds the appropriate activity, service, or set of broadcast receivers to respond to the intent, instantiating them if necessary.
    There is no overlap within these messaging systems: Broadcast intents are delivered only to broadcast receivers, never to activities or services.
    An intent passed to startActivity() is delivered only to an activity, never to a service or broadcast receiver, and so on.
  • Intent Objects
    An Intent object is a bundle of information.
    It contains information of interest to-
    the component that receives the intent (such as the action to be taken and the data to act on)
    information of interest to the Android system (such as the category of component that should handle the intent and instructions on how to launch a target activity).
  • Intent Objects
    Principally, Intent Object can contain the following:
    Component name
    Action
    Data
    Category
    Extras
    Flags
  • Component Name
    The name of the component that should handle the intent.
    This field is a ComponentName object — a combination of –
    the fully qualified class name of the target component (for example "com.example.project.app.FreneticActivity") and
    the package name set in the manifest file of the application where the component resides (for example, "com.example.project").
  • Component Name
    The 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
    The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().
  • Action
    A string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported
    See the Intent class description for a list of pre-defined constants for generic actions.
  • Action
    You can also define your own action strings for activating the components in your application.
    Those you invent should include the application package as a prefix —
    for example: "com.example.project.SHOW_COLOR".
  • Action
    The action largely determines how the rest of the intent is structured — particularly the data and extras fields
    The action in an Intent object is set by the setAction() method and read by getAction().
  • Data
    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. For example,
    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.
  • Data
    When matching an intent to a component that is capable of handling the data, it's often important to know the type of data (its MIME type) in addition to its URI. For example, a component able to display image data should not be called upon to play an audio file.
    The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().
  • Category
    A string containing additional information about the kind of component that should handle the intent. Any number of category descriptions can be placed in an Intent object.
    See the Intent class description for the full list of categories.
  • Category
    The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object.
  • Extras
    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. For example, an ACTION_TIMEZONE_CHANGED intent has a "time-zone" extra that identifies the new time zone, and ACTION_HEADSET_PLUG has a "state" extra indicating whether the headset is now plugged in or unplugged, as well as a "name" extra for the type of headset.
    If you were to invent a SHOW_COLOR action, the color value would be set in an extra key-value pair. The Intent object has a series of put...() methods for inserting various types of extra data and a similar set of get...() methods for reading the data.
    the extras can be installed and read as a Bundle using the putExtras() and getExtras() methods.
  • Flags
    Flags of various sorts.
    Many instruct the Android system how to launch an activity (for example, which task the activity should belong to)
    how to treat it after it's launched (for example, whether it belongs in the list of recent activities).
    All these flags are defined in the Intent class.
  • Intent Resolution
    Intents can be divided into two groups:
    Explicit intentsdesignate the target component by its name. Since component names 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.
    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 intentsdo not name a target (the field for the component name is blank). Implicit intents are often used to activate components in other applications.
  • Implicit Intent Resolution
    the Android system must find the best component (or components) to handle the intent —
    a single activity or service to perform the requested action
    set of broadcast receivers to respond to the broadcast announcement.
    It does so by comparing the contents of the Intent object to intent filters, structures associated with components that can potentially receive intents.
    Filters advertise the capabilities of a component and delimit the intents it can handle.
    They open the component to the possibility of receiving implicit intents of the advertised type.
  • Implicit Intent Resolution
    Only three aspects of an Intent object are consulted when the object is tested against an intent filter:
    action
    data (both URI and data type)
    category
    The extras and flags play no part in resolving which component receives an intent.
  • 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 object or the filter does not specify an action, the results are as follows:
    If the filter fails to list any actions, 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.
  • 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.
    In principle, therefore, an Intent object with no categories should always pass this test, regardless of what's in the filter.
  • Data test
    Each <data> element can specify a URI and a data type (MIME media type).
    There are separate attributes — scheme, host, port, and path — for each part of the URI:
    scheme://host:port/path
    For example, in the following URI,
    content://com.example.project:200/folder/subfolder/etc
    host
    port
    scheme
    path
    authority
  • Data test
    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. However, a path specification in the filter can contain wildcards to require only a partial match of the path.
  • Data test
    The type attribute of a <data> element specifies the MIME type of the data.
    It's more common in filters than a URI.
    Both the Intent object and the filter can use a "*" wildcard for the subtype field — for example, "text/*" or "audio/*" — indicating any subtype matches.
    The data test compares both the URI and the data type in the Intent object to a URI and data type specified in the filter.
  • Data test
    The rules are as follows:
    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 (and a type cannot be inferred from the URI) 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 (or a data type can be inferred from the URI) 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. In other words, a component is presumed to support content: and file: data if its filter lists only a data type.
  • Lab
    Create Intents to Launch system activities
    Browser
    Phone Dialer
    Make Phone call
  • SERVICES
  • Service Lifetime
  • Lab
    Lab
  • DATA STORAGE
  • Data Storage
    Android provides several options for you to save persistent application data.
    The solution you choose depends on your specific needs, such as whether-
    the data should be private to your application or
    accessible to other applications (and the user) and
    how much space your data requires.
  • Data Storage
    Your data storage options are the following:
    Shared Preferences Store private primitive data in key-value pairs.
    Internal Storage Store private data on the device memory.
    External Storage Store public data on the shared external storage.
    SQLite Databases Store structured data in a private database.
    Network Connection Store data on the web with your own network server.
  • Shared Preferences
    The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.
    You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
    This data will persist across user sessions (even if your application is killed).
  • Using Shared Preferences
    To get a SharedPreferences object for your application, use one of two methods:
    getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
    getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
  • Using Shared Preferences
    To write values:
    Call edit() to get a SharedPreferences.Editor.
    Add values with methods such as putBoolean() and putString().
    Commit the new values with commit()
    To read values, use SharedPreferences methods such as getBoolean() and getString().
  • Using Shared Preferences
    Shared Preference
    file name
    Get Shared Preference
    Each getter takes a key and a default value
    (used when no value has yet been saved
    for that key)
    Restore data
    in your code
    Read your data
    Save data
  • Lab
    Shared Preferences
  • Internal Storage
    You can save files directly on the device's internal storage.
    By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user).
    When the user uninstalls your application, these files are removed.
  • Using the Internal Storage
    To create and write a private file to the internal storage
    Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
    Write to the file with write().
    Close the stream with close().
  • Using the Internal Storage
    MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
    MODE_APPEND Append to a file
    MODE_WORLD_READABLE World Readable
    MODE_WORLD_WRITEABLE World readable/writable
  • Using the Internal Storage
    To read a file from internal storage:
    Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
    Read bytes from the file with read().
    Then close the stream with close().
  • Lab
    Internal Storage
  • Using the External Storage
    Every Android-compatible device supports a shared "external storage" that you can use to save files.
    This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.
    Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
  • Checking media availability
  • Accessing files on external storage
    use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files.
    This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
    This method will create the appropriate directory if necessary.
    By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music).
    If the user uninstalls your application, this directory and all its contents will be deleted.
  • Saving files that should be shared
    If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage.
    These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.
  • Saving files that should be shared
    Music/ - Media scanner classifies all media found here as user music.
    Podcasts/ - Media scanner classifies all media found here as a podcast.
    Ringtones/ - Media scanner classifies all media found here as a ringtone.
    Alarms/ - Media scanner classifies all media found here as an alarm sound.
    Notifications/ - Media scanner classifies all media found here as a notification sound.
    Pictures/ - All photos (excluding those taken with the camera).
    Movies/ - All movies (excluding those taken with the camcorder).
    Download/ - Miscellaneous downloads.
  • Lab
    External Storage
  • Using Databases
    Android provides full support for SQLite databases.
    Any databases you create will be accessible by name to any class in the application, but not outside the application.
  • Using Databases
  • Using Databases
    You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined.
    To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.
    You can execute SQLite queries using the SQLiteDatabasequery() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others.
    For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convenient methods for building queries.
    Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.
  • Examining sqlite3 Databases from a Remote Shell
    $ adb -s emulator-5554 shell
    # sqlite3/data/data/com.example.google.rss.rssexample/databases/rssitems.db
    (Emulator/device instances store SQLite3 databases in the folder data/data/<package_name>/databases/. )
    .dump to print out the contents of a table
    .schema to print the SQL CREATE statement for an existing table
    sqlite> .exit
  • Lab
    SQLite Db
  • Using a Network Connection
    You can use the network (when it's available) to store and retrieve data on your own web-based services.
    To do network operations, use classes in the following packages:
    java.net.*
    android.net.*
  • Lab
    Network Connection
    ReadTwitterFeed
  • CONTENT PROVIDER
  • 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. You can query these providers for the data they contain (although, for some, you must acquire the proper permission to read the data).
    If you want to make your own data public, you have two options: You can create your own content provider (a ContentProvider subclass) or 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.
  • Content Provider Basics
    How a content provider actually stores its data under the covers is up to its designer. But all content providers implement a common interface for querying the provider and returning results — as well as for adding, altering, and deleting data.
    It's an interface that clients use indirectly, most generally through ContentResolver objects. You get a ContentResolver by calling getContentResolver() from within the implementation of an Activity or other application component:
    ContentResolvercr = getContentResolver();
    You can then use the ContentResolver's methods to interact with whatever content providers you're interested in.
  • The Data Model
    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.
    • Every record includes a numeric _ID field that uniquely identifies the record within the table.
    • IDs can be used to match records in related tables — for example, to find a person's phone number in one table and pictures of that person in another.
    • A query returns a Cursor object that can move from record to record and column to column to read the contents of each field.
    • Cursor has specialized methods for reading each type of data. So, to read a field, you must know what type of data the field contains.
  • URIs
    Each content provider exposes a public URI (wrapped as a Uri object) that uniquely identifies its data set.
    A content provider that controls multiple data sets (multiple tables) exposes a separate URI for each one.
    All URIs for providers begin with the string "content://". The content: scheme identifies the data as being controlled by a content provider.
    <standard_prefix>://<authority>/<data_path>/<id> content://browser/bookmarkscontent://contacts/peoplecontent://contacts/people/3
  • URIs
    If you're defining a content provider, it's a good idea to also define a constant for its URI, to simplify client code and make future updates cleaner.
    Android defines CONTENT_URI constants for all the providers that come with the platform. For example, the URI for the table that matches phone numbers to people and the URI for the table that holds pictures of people (both controlled by the Contacts content provider) are:
    android.provider.Contacts.Phones.CONTENT_URIandroid.provider.Contacts.Photos.CONTENT_URI
    The URI constant is used in all interactions with the content provider. Every ContentResolver method takes the URI as its first argument. It's what identifies which provider the ContentResolver should talk to and which table of the provider is being targeted.
  • Querying a Content Provider
    You need three pieces of information to query a content provider:
    The URI that identifies the provider
    The names of the data fields you want to receive
    The data types for those fields
  • Creating Your Own Content Providers
    Extend the Content Provider Class and Override the Methods
    Declare the Constant Content Provider Values.
    Implement the business logic in the override methods.
    Create a Database Helper to Create database Schema
    Register the Content Provider
  • Lab
  • MEDIA
  • SurfaceView
    Provides a dedicated drawing surface embedded inside of a view hierarchy.
    You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen
    Access to the underlying surface is provided via the SurfaceHolder interface, which can be retrieved by calling getHolder().
    The Surface will be created for you while the SurfaceView's window is visible; you should implement surfaceCreated(SurfaceHolder) and surfaceDestroyed(SurfaceHolder) to discover when the Surface is created and destroyed as the window is shown and hidden.
  • Camera
    The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.
    To access the device camera, you must declare the CAMERA permission in your Android Manifest. Also be sure to include the <uses-feature> manifest element to declare camera features used by your application. For example, if you use the camera and auto-focus feature, your Manifest should include the following:
  • Camera
    To take pictures with this class, use the following steps:
    Obtain an instance of Camera from open(int).
    Get existing (default) settings with getParameters().
    If necessary, modify the returned Camera.Parameters object and call setParameters(Camera.Parameters).
    If desired, call setDisplayOrientation(int).
    Important: Pass a fully initialized SurfaceHolder to setPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.
    Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture.
    When you want, call takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback) to capture a photo. Wait for the callbacks to provide the actual image data.
    After taking a picture, preview display will have stopped. To take more photos, call startPreview() again first.
    Call stopPreview() to stop updating the preview surface.
    Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume()).
  • Lab
    Camera APIs
    Camera Demo
  • MediaPlayer
    The Android multimedia framework includes support for encoding and decoding a variety of common media types, so that you can easily integrate audio, video and images into your applications.
    You can play audio or video from media files stored in your application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection, all using MediaPlayer APIs.
  • Android Supported Media Formats
    The following network protocols are supported for audio and video playback:
    RTSP (RTP, SDP)
    HTTP progressive streaming
    HTTP live streaming draft protocol (Android 3.0 and above)
  • Using MediaPlayer
    One of the most important components of the media framework is the MediaPlayer class.
    An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:
    Local resources
    Internal URIs, such as one you might obtain from a Content Resolver
    External URLs (streaming)
  • Using MediaPlayer
    Here is an example of how to play audio that's available as a local raw resource (saved in your application's res/raw/ directory):
    MediaPlayermediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
    mediaPlayer.start(); // no need to call prepare(); create() does that
  • Using MediaPlayer
    here is how you might play from a URI available locally in the system (that you obtained through a Content Resolver, for instance):
  • Using MediaPlayer
    Playing from a remote URL via HTTP streaming looks like this:
  • Asynchronous Preparation
    the call to prepare() can take a long time to execute, because it might involve fetching and decoding media data.
    To avoid hanging your UI thread, spawn another thread to prepare the MediaPlayer and notify the main thread when done.
    However, while you could write the threading logic yourself, this pattern is so common when using MediaPlayer that the framework supplies a convenient way to accomplish this task by using the prepareAsync() method.
    This method starts preparing the media in the background and returns immediately.
    When the media is done preparing, the onPrepared() method of the MediaPlayer.OnPreparedListener, configured through setOnPreparedListener() is called.
  • Releasing the MediaPlayer
    A MediaPlayer can consume valuable system resources.
    Therefore, you should always take extra precautions to make sure you are not hanging on to a MediaPlayer instance longer than necessary.
    When you are done with it, you should always call release() to make sure any system resources allocated to it are properly released.
  • Retrieving Media from a Content Resolver
    Another feature that may be useful in a media player application is the ability to retrieve music that the user has on the device.
    You can do that by querying the ContentResolver for external media:
  • Retrieving Media from a Content Resolver
    To use this with the MediaPlayer, you can do this:
    Request Specific content
  • Lab
    Media Player
  • TELEPHONY
  • Working with Telephony Manager
    The telephony APIs also include the telephony manager(android.telephony.TelephonyManager), which you can use to obtain information about the telephony services on the device, get subscriber information, and register for telephony state changes.
    A common telephony use case requires that an application execute business logic upon incoming phone calls.
    For example, a music player might pause itself for an incoming call, and resume when the call has been completed.
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  • Working with Telephony Manager
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    TelephonyManagerteleMgr =
    (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    teleMgr.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }
  • Working with Telephony Manager
    class MyPhoneStateListener extends PhoneStateListener
    {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
    super.onCallStateChanged(state, incomingNumber);
    switch(state)
    {
    case TelephonyManager.CALL_STATE_IDLE:
    Log.d(TAG, "call state idle...incoming number is["+ incomingNumber+"]");break;
    case TelephonyManager.CALL_STATE_RINGING:
    Log.d(TAG, "call state ringing...incoming number is["+ incomingNumber+"]");break;
    case TelephonyManager.CALL_STATE_OFFHOOK:
    Log.d(TAG, "call state Offhook...incoming number is["+ incomingNumber+"]");break;
    default:
    Log.d(TAG, "call state ["+state+"]incoming number is["+ incomingNumber+"]");break;
    }
    }
    }
  • SMS
    In many circumstances you may find it easier to pass on the responsibility for sending SMS messages to another application, rather than implementing a full SMS client within your app.
    To do so, call startActivity using an Intent with the Intent.ACTION_SENDTO action.
    Specify a target
    numberusing sms: schema notation as the Intent data.
    Include the message you want to send within the Intent payload using an sms_body extra
  • Sending SMS Messages Manually
    SMS messaging in Android is handled by the SmsManager.
    Get a reference to the SMS Manager using-
    SmsManagersmsManager = SmsManager.getDefault();
    To send SMS messages, your applications must specify the SEND_SMS uses-permission.
    To request this permission, add it to the manifest as shown below:
    <uses-permission android:name="android.permission.SEND_SMS"/>
  • Sending SMS Messages Manually
    To send a text message, use sendTextMessage from the SMS Manager, passing in the address (phone number) of your recipient and the text message you want to send
    String sendTo = "5551234";
    String myMessage = "Android supports programmatic SMS messaging!";
    smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
    SMSC to use
    (Null = use default)
    Intents to track the transmission
    and successful delivery
  • Tracking and Confirming SMS Message Delivery
    To track the transmission and delivery success of your outgoing SMS messages, implement and register Broadcast Receivers that listen for the actions you specify when creating the Pending Intents you pass in to the sendTextMessage method.
    The first Pending Intent parameter, sentIntent, is fired when the message either is successfully sent or fails to send. The result code for the Broadcast Receiver that receives this Intent will be one of the following:
    Activity.RESULT_OK To indicate a successful transmission
    SmsManager.RESULT_ERROR_GENERIC_FAILURE To indicate a nonspecific failure
    SmsManager.RESULT_ERROR_RADIO_OFF When the phone radio is turned off
    SmsManager.RESULT_ERROR_NULL_PDU To indicate a PDU (protocol description unit) failure
    The second Pending Intent parameter, deliveryIntent, is fired only after the destination recipient receives your SMS message.
  • Lab
    Send and receive SMS Using Emulator
    SMSMessaging Project
  • WIFI, BLUETOOTH & NETWORKING
  • Bluetooth
  • Bluetooth
    The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices.
    The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs.
    These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.
    Using the Bluetooth APIs, an Android application can perform the following:
    Scan for other Bluetooth devices
    Query the local Bluetooth adapter for paired Bluetooth devices
    Establish RFCOMM channels
    Connect to other devices through service discovery
    Transfer data to and from other devices
    Manage multiple connections
  • Bluetooth
    All of the Bluetooth APIs are available in the android.bluetooth package.
    Here's a summary of the classes and interfaces you will need to create Bluetooth connections:
    BluetoothAdapter Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-point for all Bluetooth interaction. Using this, you can discover other Bluetooth devices, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for communications from other devices.
    BluetoothDevice Represents a remote Bluetooth device. Use this to request a connection with a remote device through a BluetoothSocket or query information about the device such as its name, address, class, and bonding state.
  • Bluetooth
    BluetoothSocket Represents the interface for a Bluetooth socket (similar to a TCP Socket). This is the connection point that allows an application to exchange data with another Bluetooth device via InputStream and OutputStream.
    BluetoothServerSocket Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket). In order to connect two Android devices, one device must open a server socket with this class. When a remote Bluetooth device makes a connection request to the this device, the BluetoothServerSocket will return a connected BluetoothSocket when the connection is accepted.
    BluetoothClass Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set of properties that define the device's major and minor device classes and its services. However, this does not reliably describe all Bluetooth profiles and services supported by the device, but is useful as a hint to the device type.
  • Bluetooth
    BluetoothProfile An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile.
    BluetoothHeadset Provides support for Bluetooth headsets to be used with mobile phones. This includes both Bluetooth Headset and Hands-Free (v1.5) profiles.
    BluetoothA2dp Defines how high quality audio can be streamed from one device to another over a Bluetooth connection. "A2DP" stands for Advanced Audio Distribution Profile.
    BluetoothProfile.ServiceListener An interface that notifies BluetoothProfile IPC clients when they have been connected to or disconnected from the service (that is, the internal service that runs a particular profile).
  • Bluetooth Permissions
    In order to use Bluetooth features in your application, you need to declare at least one of two Bluetooth permissions:
    BLUETOOTH and
    BLUETOOTH_ADMIN.
    You must request the BLUETOOTH permission in order to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
    You must request the BLUETOOTH_ADMIN permission in order to initiate device discovery or manipulate Bluetooth settings.
  • Setting Up Bluetooth
    Get the BluetoothAdapter
    Enable Bluetooth
  • Querying paired devices
  • Discovering devices
    Call startDiscovery()
    startDiscovery()
    Register Broadcast Receiver
  • Enabling discoverability
    Duration for which
    to be discoverable
    To change default
    discoverability time of
    120 seconds
  • Connecting Devices - Server
    Get a
    BluetoothServerSocket
    arbitrary
    Universally Unique Identifier (UUID)
    (128 Bits)
    Blocking
    User Processing
  • Connecting Devices - Client
    must match the
    server UUID
    Blocking
    Application data
    processing
  • Managing Connection
    Blocking
    Blocking if flow
    control happens
  • Lab
    Bluetooth Chat
  • SENSORS
  • USING SENSORS AND THE SENSOR MANAGER
    The Sensor Manager is used to manage the sensor hardware available on Android devices. Use getSystemService to return a reference to the Sensor Manager Service, as shown in the following snippet:
    String service_name = Context.SENSOR_SERVICE;
    SensorManagersensorManager = (SensorManager)getSystemService(service_name);
  • Supported Android Sensors
    ➤ Sensor.TYPE_ACCELEROMETERA three-axis accelerometer sensor that returns the current acceleration along three axes in m/s2.
    ➤ Sensor.TYPE_GYROSCOPEA gyroscopic sensor that returns the current device orientation on three axes in degrees.
    ➤ Sensor.TYPE_LIGHT An ambient light sensor that returns a single value describing the ambient illumination in lux. A light sensor is commonly used to dynamically control the screen brightness.
    ➤ Sensor.TYPE_MAGNETIC_FIELDA magnetic field sensor that finds the current magnetic field
    in microteslas along three axes.
    ➤ Sensor.TYPE_ORIENTATION An orientation sensor that returns the device orientation on
    three axes in degrees.
    ➤ Sensor.TYPE_PRESSURE A pressure sensor that returns a single value, the current pressure
    exerted on the device in kilopascals.
    ➤ Sensor.TYPE_PROXIMITY A proximity sensor that indicates the distance between the device
    and the target object in meters. How a target object is selected, and the distances supported,
    will depend on the hardware implementation of the proximity detector. A typical use for the
    proximity sensor is to detect when the device is being held up against the user’s ear and to
    automatically adjust screen brightness or initiate a voice command.
    ➤ Sensor.TYPE_TEMPERATURE A thermometer that returns temperature in degrees Celsius. The
    temperature returned may be the ambient room temperature, device battery temperature, or
    remote sensor temperature, depending on the hardware implementation.
  • Finding Sensors
    returns the default gyroscope
    Sensor defaultGyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    to return a list of all the available Sensors of a given type
    List<Sensor> pressureSensors = sensorManager.getSensorList(Sensor.TYPE_PRESSURE);
    To find every Sensor available on the host platform
    List<Sensor> allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
  • Using Sensors
    Get sensor manager
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    Register listener
    mSensorManager.registerListener(mySensorEventListener,
    SensorManager.SENSOR_ACCELEROMETER |
    SensorManager.SENSOR_MAGNETIC_FIELD |
    SensorManager.SENSOR_ORIENTATION,
    SensorManager.SENSOR_DELAY_FASTEST);
    Unregister Listener
    mSensorManager.unregisterListener(mySensorEventListener);
  • Using Sensors
    final SensorEventListener mySensorEventListener = new SensorEventListener() {
    public void onSensorChanged(int sensor, float[] values) {
    // TODO Monitor Sensor changes.
    }
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO React to a change in Sensor accuracy.
    }
    };
  • Using Sensors
    The accuracy value represents feedback from the monitored Sensor’s accuracy, usingone of the following constants:
    ➤ SensorManager.SENSOR_STATUS_ACCURACY_LOW Indicates that the Sensor is reporting with low accuracy and needs to be calibrated
    ➤ SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM Indicates that the Sensor data is of average accuracy, and that calibration might improve the readings
    ➤ SensorManager.SENSOR_STATUS_ACCURACY_HIGH Indicates that the Sensor is reporting with the highest possible accuracy
    ➤ SensorManager.SENSOR_STATUS_UNRELIABLE Indicates that the Sensor data is unreliable, meaning that either calibration is required or readings are not currently possible
  • INTERPRETING SENSOR VALUES
  • Lab
    Sensors Lab
  • LOCATION & MAPS
  • Introducing Map View and Map Activity
    MapView is theMap View control.
    MapActivity is the base class you extend to create a new Activity that can include a MapView.
    The MapActivity class handles the application life cycle and background service management required for displaying maps.
    As a result you can use Map Views only within MapActivity-derived Activities.
    Overlay is the class used to annotate your maps. Using Overlays, you can use a Canvas to draw onto any number of layers that are displayed on top of a Map View.
    MapController is used to control the map, enabling you to set the center location and zoom levels.
  • Getting Map Keys
    In order to use a Map View in your application you must first obtain an API key from the Android developer web site at http://code.google.com/android/maps-api-signup.html.
    Getting Your Development/Debugging MD5 Fingerprint
    Typically the debug keystore is stored in the following platform-specific locations:
    ➤ Windows Vista users<username>.androiddebug.keystore
    ➤ Windows XP Documents and Settings<username>.androiddebug.keystore
    ➤ Linux or Mac ∼/.android/debug.keystore
    To find the MD5 fingerprint of your debug certificate use the keytool command from your Java installation, as shown here:
    keytool -list -alias androiddebugkey -keystorekeystore_location>debug.keystore -storepass android -keypass android
  • Creating a Map-Based Activity
    <uses-library android:name="com.google.android.maps"/>
    <uses-permission android:name="android.permission.INTERNET"/>
  • Creating a Map-Based Activity
  • Creating a Map-Based Activity
  • Configuring and Using Map Views
    mapView.setSatellite(true);
    mapView.setStreetView(true);
    mapView.setTraffic(true);
    intmaxZoom = mapView.getMaxZoomLevel();
    GeoPoint center = mapView.getMapCenter();
    intlatSpan = mapView.getLatitudeSpan();
    intlongSpan = mapView.getLongitudeSpan();
    mapView.setBuiltInZoomControls(true);
    Default View
  • Using the Map Controller
    Use the Map Controller to pan and zoom a MapView.
    MapControllermapController = myMapView.getController();
    Map locations in the Android mapping classes are represented by GeoPoint objects, which contain latitude and longitude measured in microdegrees.
    To convert degrees to microdegrees, multiply by 1E6 (1,000,000).
    Double lat = 37.422006*1E6;
    Double lng = -122.084095*1E6;
    GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
  • Using the Map Controller
    Re-center and zoom the Map View using the setCenter and setZoom methods available on the Map View’sMapController.
    mapController.setCenter(point);
    mapController.setZoom(1);
    When you are using setZoom, 1 represents the widest (or most distant) zoom and 21 the tightest (nearest) view.
    The setCenter method will ‘‘jump’’ to a new location; to show a smooth transition use-
    mapController.animateTo(point);
  • Creating and Using Overlays
    Overlays enable you to add annotations and click handling to MapViews.
    Each Overlay lets you draw 2D primitives, including text, lines, images, and shapes, directly onto a canvas, which is then overlaid onto a Map View.
    You can add several Overlays onto a single map. All the Overlays assigned to a Map View are added as layers, with newer layers potentially obscuring older ones.
    User clicks are passed through the stack until they are either handled by an Overlay or registered as clicks on the Map View itself.
  • Creating New Overlays
    Each Overlay is a canvas with a transparent background that is layered onto a Map View and used to handle map touch events.
    To add a new Overlay create a new class that extends Overlay.
    Override the draw method to draw the annotations you want to add, and override onTap to react to user clicks (generally made when the user taps an annotation added by this Overlay).
  • Projections
    The canvas used to draw Overlay annotations is a standard Canvas that represents the visible display surface.
    To add annotations based on physical locations, you need to convert between geographical points and screen coordinates.
    The Projection class lets you translate between latitude/longitude coordinates (stored as GeoPoints) and x/y screen pixel coordinates (stored as Points).
  • Adding & Removing Overlays
  • Lab
    Set GPS coordinates in emulator and read them
    Where Am I – 1 Project
    Receive coordinate update
    Where Am I – 2 Project
    Geocoding
    Where Am I – 3 Project
    Use google maps
    Where Am I – 4
    Create overlay over map
    Where Am I – 5
  • DEBUGGING
  • DDMS
    DDMS Lab
  • References
    Android developers guide
    Professional Android 2 – Wrox Press
    Pro Android 2 - Apress
    Mobile Programming - Scott King
    Embedded Android Workshop – KarimYaghmour
  • The Endramesh130@gmail.com