SlideShare une entreprise Scribd logo
1  sur  368
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 ,[object Object]
Time Picker
Form Stuff
Spinner
Auto Complete
Gallery
Web View,[object Object]
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 ,[object Object]
Screen pixel density (dpi)
ldpimdpihdpixhdpinodpi,[object Object]
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
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT
ANDROID APP DEVELOPMENT

Contenu connexe

Tendances

Android versions
Android versionsAndroid versions
Android versionssriramakhil
 
Android Apps Development Basic
Android Apps Development BasicAndroid Apps Development Basic
Android Apps Development BasicMonir Zzaman
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialmaster760
 
Android app development
Android app developmentAndroid app development
Android app developmentTanmoy Roy
 
Mobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osamaMobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osamaOsama Ghandour Geris
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to androidzeelpatel0504
 
Short notes of android
Short notes of androidShort notes of android
Short notes of androidMohamed Fathy
 
Android Programming Seminar
Android Programming SeminarAndroid Programming Seminar
Android Programming SeminarNhat Nguyen
 
Android summer training report
Android summer training reportAndroid summer training report
Android summer training reportShashendra Singh
 
Android seminar report
Android seminar reportAndroid seminar report
Android seminar reportdgpune
 
My presentation on Android in my college
My presentation on Android in my collegeMy presentation on Android in my college
My presentation on Android in my collegeSneha Lata
 
Android fundamentals and tutorial for beginners
Android fundamentals and tutorial for beginnersAndroid fundamentals and tutorial for beginners
Android fundamentals and tutorial for beginnersBoom Shukla
 

Tendances (20)

Android versions
Android versionsAndroid versions
Android versions
 
Android overview
Android overviewAndroid overview
Android overview
 
Android Apps Development Basic
Android Apps Development BasicAndroid Apps Development Basic
Android Apps Development Basic
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android Platform Architecture
Android Platform ArchitectureAndroid Platform Architecture
Android Platform Architecture
 
ANDROID
ANDROIDANDROID
ANDROID
 
Android app development
Android app developmentAndroid app development
Android app development
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Android report
Android reportAndroid report
Android report
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Introduction to Android Environment
Introduction to Android EnvironmentIntroduction to Android Environment
Introduction to Android Environment
 
Android Report
Android ReportAndroid Report
Android Report
 
Mobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osamaMobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osama
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Short notes of android
Short notes of androidShort notes of android
Short notes of android
 
Android Programming Seminar
Android Programming SeminarAndroid Programming Seminar
Android Programming Seminar
 
Android summer training report
Android summer training reportAndroid summer training report
Android summer training report
 
Android seminar report
Android seminar reportAndroid seminar report
Android seminar report
 
My presentation on Android in my college
My presentation on Android in my collegeMy presentation on Android in my college
My presentation on Android in my college
 
Android fundamentals and tutorial for beginners
Android fundamentals and tutorial for beginnersAndroid fundamentals and tutorial for beginners
Android fundamentals and tutorial for beginners
 

En vedette

Android vs Others Operating System
Android vs Others Operating SystemAndroid vs Others Operating System
Android vs Others Operating SystemShemul Hossain
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfacesC.o. Nieto
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding MenuKan-Han (John) Lu
 
Android Advanced Techniques
Android Advanced TechniquesAndroid Advanced Techniques
Android Advanced TechniquesAndrei Catinean
 
Menu in android
Menu in androidMenu in android
Menu in androidDurai S
 
Using Keywords in YouTube Videos and Virtual Tours for Real Estate
Using Keywords in YouTube Videos and Virtual Tours for Real EstateUsing Keywords in YouTube Videos and Virtual Tours for Real Estate
Using Keywords in YouTube Videos and Virtual Tours for Real EstateFlorida Mobile Fusion
 
Trek
TrekTrek
Trekgfaux
 
Supporting multiple screens on android
Supporting multiple screens on androidSupporting multiple screens on android
Supporting multiple screens on androidLi SUN
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Nehil Jain
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureNicheTech Com. Solutions Pvt. Ltd.
 
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...Paul Hunt
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Android architecture
Android architectureAndroid architecture
Android architectureHari Krishna
 

En vedette (18)

Android vs Others Operating System
Android vs Others Operating SystemAndroid vs Others Operating System
Android vs Others Operating System
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Android animation in android-chapter17
Android animation in android-chapter17Android animation in android-chapter17
Android animation in android-chapter17
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding Menu
 
Android Advanced Techniques
Android Advanced TechniquesAndroid Advanced Techniques
Android Advanced Techniques
 
Menu in android
Menu in androidMenu in android
Menu in android
 
Android ui menu
Android ui menuAndroid ui menu
Android ui menu
 
Using Keywords in YouTube Videos and Virtual Tours for Real Estate
Using Keywords in YouTube Videos and Virtual Tours for Real EstateUsing Keywords in YouTube Videos and Virtual Tours for Real Estate
Using Keywords in YouTube Videos and Virtual Tours for Real Estate
 
Trek
TrekTrek
Trek
 
Supporting multiple screens on android
Supporting multiple screens on androidSupporting multiple screens on android
Supporting multiple screens on android
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
 
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...
Creating an FAQ for end users, An evolution of an idea - SharePoint Saturday ...
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Android architecture
Android architectureAndroid architecture
Android architecture
 

Similaire à ANDROID APP DEVELOPMENT

01 what is android
01 what is android01 what is android
01 what is androidC.o. Nieto
 
Ch1 hello, android
Ch1 hello, androidCh1 hello, android
Ch1 hello, androidJehad2012
 
Google android white paper
Google android white paperGoogle android white paper
Google android white paperSravan Reddy
 
Unit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assUnit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assARVIND SARDAR
 
Introduction to everything around Android
Introduction to everything around AndroidIntroduction to everything around Android
Introduction to everything around AndroidBipin Jethwani
 
Android..overwiew
Android..overwiewAndroid..overwiew
Android..overwiewSai Teja
 
Getting started with android
Getting started with androidGetting started with android
Getting started with androidamitgb
 
Android 1-intro n architecture
Android 1-intro n architectureAndroid 1-intro n architecture
Android 1-intro n architectureDilip Singh
 
Android seminar-report-body.doc
Android seminar-report-body.docAndroid seminar-report-body.doc
Android seminar-report-body.docDeepak Yadav
 
Software training report
Software training reportSoftware training report
Software training reportNatasha Bains
 
Evolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s VersionsEvolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s Versionsijtsrd
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1DHIRAJ PRAVIN
 
Android : Architecture & Components
Android : Architecture & ComponentsAndroid : Architecture & Components
Android : Architecture & ComponentsAkash Bisariya
 
Android overview
Android overviewAndroid overview
Android overviewHas Taiar
 

Similaire à ANDROID APP DEVELOPMENT (20)

01 what is android
01 what is android01 what is android
01 what is android
 
Ch1 hello, android
Ch1 hello, androidCh1 hello, android
Ch1 hello, android
 
Android
AndroidAndroid
Android
 
Android
Android Android
Android
 
Google android white paper
Google android white paperGoogle android white paper
Google android white paper
 
Unit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assUnit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-ass
 
Introduction to everything around Android
Introduction to everything around AndroidIntroduction to everything around Android
Introduction to everything around Android
 
Android..overwiew
Android..overwiewAndroid..overwiew
Android..overwiew
 
Getting started with android
Getting started with androidGetting started with android
Getting started with android
 
Android 1-intro n architecture
Android 1-intro n architectureAndroid 1-intro n architecture
Android 1-intro n architecture
 
Android seminar-report-body.doc
Android seminar-report-body.docAndroid seminar-report-body.doc
Android seminar-report-body.doc
 
Android
AndroidAndroid
Android
 
Software training report
Software training reportSoftware training report
Software training report
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Evolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s VersionsEvolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s Versions
 
Android...by raziel lucagbo
Android...by raziel lucagboAndroid...by raziel lucagbo
Android...by raziel lucagbo
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1
 
Android overview
Android overviewAndroid overview
Android overview
 
Android : Architecture & Components
Android : Architecture & ComponentsAndroid : Architecture & Components
Android : Architecture & Components
 
Android overview
Android overviewAndroid overview
Android overview
 

Plus de Ramesh Prasad

Multimedia on android
Multimedia on androidMultimedia on android
Multimedia on androidRamesh Prasad
 
Managing sales using CRM
Managing sales using CRMManaging sales using CRM
Managing sales using CRMRamesh Prasad
 
Signal processing in smartphones - 4G perspective
Signal processing in smartphones - 4G perspectiveSignal processing in smartphones - 4G perspective
Signal processing in smartphones - 4G perspectiveRamesh Prasad
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application DevelopmentRamesh Prasad
 
Sdk For Firmware Development
Sdk For Firmware DevelopmentSdk For Firmware Development
Sdk For Firmware DevelopmentRamesh Prasad
 
De Interlacing Techniques
De Interlacing TechniquesDe Interlacing Techniques
De Interlacing TechniquesRamesh Prasad
 

Plus de Ramesh Prasad (6)

Multimedia on android
Multimedia on androidMultimedia on android
Multimedia on android
 
Managing sales using CRM
Managing sales using CRMManaging sales using CRM
Managing sales using CRM
 
Signal processing in smartphones - 4G perspective
Signal processing in smartphones - 4G perspectiveSignal processing in smartphones - 4G perspective
Signal processing in smartphones - 4G perspective
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
Sdk For Firmware Development
Sdk For Firmware DevelopmentSdk For Firmware Development
Sdk For Firmware Development
 
De Interlacing Techniques
De Interlacing TechniquesDe Interlacing Techniques
De Interlacing Techniques
 

ANDROID APP DEVELOPMENT

  • 5. A BRIEF HISTORY OF ANDROID
  • 6. 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.
  • 7. 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.
  • 8. 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
  • 9. 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
  • 10. Versions Ice Cream Sandwich
  • 11. 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
  • 13. 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.
  • 15. 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
  • 16. Linux kernel – Androidsm
  • 17. Libraries A set of C/C++ libraries exposed to developers through the application framework
  • 18. 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
  • 19. 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
  • 20. Libraries LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view SGL - the underlying 2D graphics engine
  • 21. 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
  • 22. 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
  • 23. Application Framework The framework allows developers to build cool apps
  • 24. 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
  • 25. Applications AOSP and Non-AOSP Apps
  • 26. Applications The non-AOSP apps Android Market YouTube Maps and Navigation Gmail Voice SkyMap ... Require CTS/CDD Compliance Signed agreement w/ Google
  • 28. Application - User Interaction
  • 29. Screen Characteristics Screen size Screen density Orientation Resolution Density-independent pixel (dp)
  • 30. 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.
  • 32. 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.
  • 33. 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.
  • 34. 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
  • 35. 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
  • 38. 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.
  • 39. 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.
  • 40. 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.
  • 41. 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.
  • 42. 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.
  • 43. Types of application components Activities Services Content providers Broadcast receivers
  • 44. 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.
  • 46. 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
  • 48. 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.
  • 49. 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.
  • 50. Androidism Any application can start another application’s component. No “main()” function Intent
  • 51. 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.
  • 52. Start Another Application FACEBOOK APP (PROCESS P1) FACEBOOK APP (PROCESS P1) CAMERA APP (PROCESS P2)
  • 53. 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).
  • 54. No MAIN() APP 2 (PROCESS P2) APP 1 (PROCESS P1) Camera Settings Some Activity Capture Photo Save Photo Use Photo
  • 55. 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.
  • 56. Intent Intent to Download
  • 57. 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.
  • 58. 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
  • 59. 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).
  • 60. 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.
  • 61. 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
  • 63. 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
  • 64. 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.
  • 65. 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().
  • 66. 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.
  • 67. Declaring application requirements Important device characteristics Screen size and density Input configurations Device features Platform Version
  • 68. 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.
  • 69. 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.
  • 70. 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.
  • 71. 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.
  • 72. 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
  • 73. 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).
  • 75. 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).
  • 76. 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.
  • 77. Application Resources Same ID (R.ID) but different Resource
  • 79. Tools Eclipse Android Development Tools (ADT) SDK NDK
  • 80. 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
  • 83. 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.
  • 84. 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.
  • 85. 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.
  • 87. Back Stack Two tasks: Task A is in the background, waiting to be resumed, while Task B receives user interaction in the foreground
  • 88. Back Stack A single activity is instantiated multiple times
  • 89. Creating Activity Subclasss the Activity class Implement User Interface Declare Activity in the manifest
  • 90. 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.
  • 91. 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.
  • 92. 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.
  • 93. View & View Groups Widget Layout
  • 94. 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.
  • 96. 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 >
  • 97. 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.
  • 98. 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).
  • 99. 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.
  • 100. Lab Hello World Tutorial
  • 101. 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.
  • 102. 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);
  • 103. Lab Create a new activity Start a new activity from the Main activity
  • 104. 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);
  • 105. Lab Create a new activity Start the new activity from Main activity Pass data to new activity
  • 106. 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.
  • 107. 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.
  • 108. Lab Create a new activity Start the new activity for result from Main activity Get result from new activity
  • 109. 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.
  • 110. 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.
  • 113. 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.
  • 114. Lab Saving Activity Data LunarLander
  • 115. 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.
  • 117. 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.
  • 118. 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.
  • 119. 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())
  • 120. Lab Saving Activity State Default onSaveInstanceState() Behavior
  • 121. 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
  • 122. 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.
  • 123. 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.
  • 125. Activity Summary Activity Lifecycle Save persistent data Save persistent state Handle runtime configuration changes
  • 127. 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.
  • 128. 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.
  • 129. View & View Groups Widget Layout
  • 131. 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.
  • 132. 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.
  • 133. 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.
  • 134. 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
  • 136. 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.
  • 137. 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.
  • 138. 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); }
  • 139. 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.
  • 140. 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).
  • 141. 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.
  • 142. 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);
  • 143. Layout Parameters Visualization of a view hierarchy with layout parameters associated with each view.
  • 144. 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.
  • 145. 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.
  • 146. 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().
  • 147. Layout Position getTop() getBottom() getLeft() View getRight() Parent
  • 148. Size, Padding and Margins
  • 149. 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().
  • 155. Lab XML & Layout Window Layouts Linear Relative Table Grid Tab List
  • 156. 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.
  • 158.
  • 164.
  • 165. 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").
  • 166. Example register an on-click listener for a Button
  • 167. Example - OnClickListener as a part of your Activity
  • 168. 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.
  • 169. 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.
  • 170. 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.
  • 171. Menus
  • 172. 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.
  • 173. Creating a Menu Resource
  • 174. 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.
  • 175. 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().
  • 176. 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.
  • 177. 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
  • 178. 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
  • 179. Lab Create menu from XML Handle user action
  • 180. 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.
  • 181. 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().
  • 182. Creating a Context Menu Get info for the selected item
  • 183. Lab Create a context Menu Handle user action
  • 184. 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.).
  • 185. Creating Submenus When creating your menu resource, you can create a submenu by adding a <menu> element as the child of an <item>.
  • 186. 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.
  • 187. Lab Create sub menu Handle user action
  • 188. 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).
  • 189. 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.
  • 190. 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)
  • 191. 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
  • 193. Adding checkboxes and radio buttons No item should be selected by Default
  • 194. 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
  • 195. 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.
  • 196. Lab OK Cancel Dialog with a message List Dialog Progress Dialog Single choice list
  • 197. 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.
  • 198. 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.
  • 199. Creating Toast Notifications You can also chain your methods and avoid holding on to the Toast object, like this:
  • 202. 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.
  • 203. 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.
  • 204. Creating Status Bar Notifications Get a reference to the NotificationManager:
  • 205. Creating Status Bar Notifications Instantiate the Notification:
  • 206. Creating Status Bar Notifications Define the Notification's expanded message and Intent:
  • 207. Creating Status Bar Notifications Pass the Notification to the NotificationManager:
  • 208. Adding Sound, vibration etc notification.defaults |= Notification.DEFAULT_SOUND; notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_LIGHTS;
  • 210. 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.
  • 211. 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
  • 213. 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.
  • 214. 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.
  • 215. 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
  • 216. 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.
  • 217. 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.
  • 218. Style
  • 219. 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.
  • 222. 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.
  • 223. 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.
  • 224. Structure of the Manifest File
  • 225. 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>
  • 228. 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.
  • 229. Application Resources Two different devices, both using default resources Two different devices, one using alternative resources
  • 234.
  • 236.
  • 237. 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.
  • 238. 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).
  • 240. 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).
  • 243. 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.
  • 244. 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.
  • 245. 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.
  • 246. 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).
  • 247. Intent Objects Principally, Intent Object can contain the following: Component name Action Data Category Extras Flags
  • 248. 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").
  • 249. 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().
  • 250. 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.
  • 251. 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".
  • 252. 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().
  • 253. 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.
  • 254. 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().
  • 255. 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.
  • 256. 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.
  • 257. 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.
  • 258. 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.
  • 259. 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.
  • 260. 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.
  • 261. 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.
  • 262. 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.
  • 263. 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.
  • 264. 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
  • 265. 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.
  • 266. 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.
  • 267. 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.
  • 268. Lab Create Intents to Launch system activities Browser Phone Dialer Make Phone call
  • 273. 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.
  • 274. 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.
  • 275. 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).
  • 276. 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.
  • 277. 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().
  • 278. 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
  • 280. 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.
  • 281. 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().
  • 282. 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
  • 283. 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().
  • 285. 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.
  • 287. 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.
  • 288. 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.
  • 289. 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.
  • 291. 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.
  • 293. 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