Android  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. In 2005, Google buys Android. In 2007, the Open Handset Alliance is announced. Android is officially open sourced. Android Versions & Levels: Versions Android 1.1 Android 1.5 Android 1.6 Android 2.0 Android 2.0.1 Android 2.1 Android 2.2 Android 2.3 Android 2.3.3 Android 2.3.4 Android 3.0 Android 3.1 Android 3.2 Android 4.0,4.0.1 Android 4.0.3  API Level 2 3 4 5 6 7 8 9 10 10 11 12 13 14 15 Name Petit Four Cup Cake Donut Éclair Éclair Éclair Froyo Gingerbread Released in Feb 2009 Apr 2009 Sep 2009 Oct 2009 Dec 2009 Jan 2010 May 2010 Dec 2010 Feb 2011 May 2011 Feb 2011 May 2011 July 2011 Oct 2011 Dec 2011

  

Honey Comb

Ice Cream Sandwich

Features of Android: Android itself supports the following features:  Storage — Uses SQLite, a lightweight relational database, for data storage.  Application framework enabling reuse and replacement of components  Dalvik virtual machine optimized for mobile devices  Integrated browser based on the open source Webkit engine

 Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)  Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)  GSM Telephony (hardware dependent)  Bluetooth, EDGE, 3G, and Wi-Fi (hardware dependent)  Camera, GPS, compass, and accelerometer (hardware dependent)  Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plug-in for the Eclipse IDE Android Architecture  The following diagram shows the various layers that make up the Android operating system (OS).

Architecture of Android Operating System

Linux Kernel:  Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model.  The kernel also acts as an abstraction layer between the hardware and the rest of the software stack. Android Runtime:  Core Libraries: Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.  Dalvik Virtual machine:  Every Android application runs in its own process, with its own instance of the Dalvik virtual machine.  Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint.  The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.  The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Libraries:  Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:  System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linuxbased devices  Media Libraries - based on PacketVideo's OpenCORE; 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

 Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications  LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view  SGL - the underlying 2D graphics engine  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  FreeType - bitmap and vector font rendering  SQLite - a powerful and lightweight relational database engine available to all applications  Application Framework:  Android offers developers the ability to build extremely rich and innovative applications.  Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.  Full access to the same framework APIs used by the core applications.  The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities. Platform Services Hardware Services Telephony Service Activity Manager Bluetooth Service Package Manager Wi-Fi Service Window Manager USB Service Resource Manager Sensor Service Content Providers View System

Applications:  Applications are the general applications that are pre shipped with the phone or downloaded and installed from the market. Example:

documentation.  If you have not programmed in Java before. contacts. JAVA SDK The Android SDK makes use of the Java SE Development Kit (JDK). and others. a multi-language software development environment featuring an extensible plugin system.  You can download the Android SDK from http://developer. the recommended IDE is SMS program.  Applications make use of Application Framework. you should start by downloading the JDK from ww. browser. Android SDK  The Android SDK contains a calendar. Android Development Tools( ADT )  The next important piece of software you need is Android SDK. In the case of Android.  Android programming is done using Java syntax. you probably should learn how that works before attempting to dive into programming for Android.  Prerequisites: If you are interested in programming for Android.    The Android Development Tools (ADT) plug-in for Eclipse is an extension to the Eclipse IDE that supports the creation and . an emulator. sample code. maps. you will need at least basic understanding of how to program in Java.A set of core applications including an email client. if your computer does not have the JDK plus a class library that resembles a subset of the Java SE library (plus Android-specific extensions). however. and tutorials. you need to download the required tools and SDKs. and install Eclipse The first step towards developing any applications is obtaining the integrated development environment(IDE).  All applications are written using the Java programming language. Obtaining the Required Tools: Before you write your fi rst app. libraries.

  .apk suffix. sharing the same VM. each application is assigned a unique Linux user ID. the data and resources bundled into a package.  Permissions are set so that the application's files are visible only to that user.debugging of Android applications.apk file is used to install the applications on Android-powered devices. Application Fundamentals:   Android applications are written in the Java programming asset packaging tool. o Create digital certificates for code-signing your APK.  By using the aapt tool. you will be able to do the following in Eclipse: o Create new Android application projects. and to the application itself. o Export Android applications into Android Packages (APK). o Compile and debug Android applications. and shuts down the process when it's no longer needed or when some system resources are required by other applications. o Access the tools for accessing your Android emulators and devices.  By default. The .android package kit. in which case they will be able to see each other's files. The Android SDK tools compile the code—along with any data and resource files—into an Android package. an archive file with an .  aapt. Each Android application lives in its own world:  By default. Using the ADT. so application code runs in isolation from the code of all other applications.  Each process has its own virtual machine (VM).  There are ways to export them to other applications as well:  It's possible to arrange for two applications to share the same user ID.  To conserve system resources.  Apk. every application runs in its own Linux process  Android starts the process when any of the application's code needs to be executed. applications with the same ID can also arrange to run in the same Linux process. which holds any third-party Java JARs your application requires  src/. and more. And they are as follows: 1. etc. To create a new android application use the Eclipse new-project wizard to Creating a Project:  create a new Android application. SMS messages. including:  AndroidManifest. the mountable storage (SD card).xml. 3.. that get packaged with the compiled Java in the application Android Application Components:   Application components are the essential building blocks of an Android application.g. such as icons. but each one exists as its own entity and plays a specific role There are four different types of application components in android. Services. An application can request permission to access device data such as the user's contacts. Not all components are actual entry points for the user and some depend on each other. and the like. – are being supplied by that application  build. property files used by the Ant build script  assets/. which is an XML file describing the application being built and what components – activities. via android create project). where Android's build tools will place source code that they generate  libs/. which holds the Java source code for the application  res/. which hold other static files you wish packaged with the application for deployment onto the device  bin/. Content Providers. Bluetooth. GUI layouts. Project Structure:  Root Contents When you create a new Android project (e. Each component is a different point through which the system can enter your application. camera. services.  . which holds the application once it is compiled  gen/. Activities. All application permissions must be granted by the user at install and local. which holds "resources". you get several items in the project's root directory. which is an Ant script for compiling the application and installing it on the device  default. 2.

 A service is a component that runs in the background to perform long running operations or to perform work for remote processes. For example consider an Email application. Example: .  Typically.  For example. 2. Android applications have more than one entry point.  Each one is implemented as a subclass of the Activity base class. When a new activity started the previous activity is stopped and pushed on to the back stack. The back stack works on LIFO (Last in First Out) mechanism. Composing a new mail. ( main() is the entry point in java) Activities:  An activity represents a single screen with a user interface.  Typically.  Each activity is independent of the other activity. Broadcast Receivers. Showing list of mails. Camera application can start an activity in the e-mail application that composes a new mail in order to share a picture. Whereas. the window fills the screen. Services:  A service does not have a visual user interface. Reading a mail.  Each activity can start another in order to perform some actions. 4.  Each activity gives a window to draw its user interface. java has only a single entry point. 3.  An application might consist of just a single activity or can contain multiple activities. which is presented to the user when an application is launching for the first time. one activity in an application specified as the main activity. And can work together. but it might be smaller than the screen and may float on top of other windows. 1. the following are called activities.

Broadcast Receivers:  A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements.  Each service extends the Service base class. Example: It might initiate a service to perform some work based on an event. The screen has turned off.  Applications initiated.  Fetching the data over the network without disturbance. System Originated:  Following are the examples of system originated broadcast announcements. Application initiated:  Applications can also initiate the broadcast announcements. Battery is low.  Playing the music while the user is in a different application. They are as follows:  System originated. Content Providers:  A content provider makes a specific set of the application's data available to other applications. Picture has been captured.  A broadcast receiver is just a gate way to other components and intended to do a very minimal amount of work.  .  Broadcast announcements are of two types. Announcing to other applications that some data has been downloaded to the device and is available for them to use.  A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process. The time zone has changed.

Rather they use a ContentResolver object and call its methods instead. Activity Lifecycle:  An Activity has three states. it cooperates with the provider to manage any inter process communication that's involved. an SQLite Database. A ContentResolver can talk to any content provider. it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere. on the web or any other persistent storage location your application can access. another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. applications do not call these methods directly.  That is. .  A stopped activity is also still alive. You can store the data in file system. They are as follows:  Running/Resumed  Paused  Stopped Resumed:  The activity is in the foreground of the screen and has user focus.  However.  However. but can be killed by the system in extremely low memory situations. Stopped:  The activity is completely obscured by another activity.  A paused activity is completely alive. The activity object is retained in memory and it maintains all state and member information. (At top of the activity stack) Paused:  In this state an activity has lost focus but is still visible to the user.  The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls.

Entire Lifetime: The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). as the activity alternates between being visible and hidden to the user. Visibility Lifetime: The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). When the activity is opened again. Foreground Lifetime: .  Visibility Lifetime.  Even if an application has only one activity and the activity is killed. During this time.  Foreground Lifetime. the user can see the activity on-screen. and unregister it in onStop() when the user can no longer see what you are displaying. if it has a thread running in the background to download data from the network. the system can drop it from memory either by asking it to finish method. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity. it may create that thread in onCreate () and then stop the thread in onDestroy(). you can maintain resources that are needed to show the activity to the user. and releases all remaining resources in onDestroy(). though it may not be in the foreground and interacting with the user. For example. Between these two methods. the application will still be running in memory  Lifetime of an Activity:  Entire Lifetime. For example. An activity does all its initial setup of "global" state in onCreate(). it must be completely restarted and restored to its previous state. If an activity is paused or stopped. or simply killing its process. you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI.

.The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). An activity can frequently transition between the resumed and paused states. The code in onPause() and onResume() methods should be fairly lightweight.  The following diagram illustrates the life cycle of an activity. onResume() is called when an activity result or a new intent is delivered. the activity is in front of all other activities on screen and is interacting with the user. onPause() is called when the device goes to sleep or when a new activity is started.  For example. At this time.

.  onStart() — Called when the activity becomes visible to the user. The Activity class defines the following events:  onCreate() — Called when the activity is first created.Life cycle of an Activity  The Activity base class defines a series of events that governs the life cycle of an activity.

 A bound service offers a client-server interface that allows components to interact with the service. Services in Android  A service does not have a visual user interface. even if the component that started the service is destroyed. . Bound:  A service is "bound" when an application component binds to it by calling bindService ().  For example.  Once the service has started it will run in the back ground.  A service is a component that runs in the background to perform long running operations or to perform work for remote processes.  Another application component (Activity/Receiver/Provider) can start a service and it will continue to run in the background even if the user switches to another application.  When the operation is done. download or upload a file over the network. the service should stop itself. onPause() — Called when the current activity is being paused and the previous activity is being resumed.  A service can take two forms:  Started  Bound Started:  A service is "started" when an application component (such as an activity) starts it by calling startService().  A bound service runs only as long as another application component is bound to it.     onResume() — Called when the activity starts interacting with the user. onStop() — Called when the activity is no longer visible to the user onDestroy() — Called before the activity is destroyed by the system (either manually or by the system to conserve memory) onRestart() — Called when the activity has been stopped and is restarting again.  A started service performs only a single operation and does not return any result.

is called each time the service is started via startService().  entire lifetime:  The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns.  onDestroy() – is called as the service is being shut down. and releases all remaining resources in onDestroy().  Like an activity. Multiple components can bind to the service at once.  It is important to put all long-running code into a separate thread. The music service would open the Intent to discover which music to play. a music playback service could create the thread where the music will be played in onCreate() and then stop the thread in onDestroy().  Life cycle methods of a service is as follows:  onCreate() .  Active Lifetime:  The active lifetime of a service begins with a call to onStart(). a service does its initial setup in onCreate().  Each method is handed the Intent that was passed to either startService() or bindService().  For Example.  onStart () .  When all of the components bound to it are unbind. . the service will be destroyed. so that it does not tie up the application that calls it.  For example. and begin the called when the service process is created.

Content Providers in Android  Content providers are one of the primary building blocks of Android applications. . browser history. and so on. Example: contacts  Built-in Content Providers in Android are as follows:  Contacts — Stores contact details.Unbounded Bounded Figure-1 the Service Lifecycle  In Figure-1 the left side diagram shows the lifecycle when the service is created with startService().  A content provider is used to share the data between multiple applications.  The right diagram shows the lifecycle when the service is created with bindService(). providing content to applications.  Browser — Stores data such as browser bookmarks.

and so on.providers or Com.Returns a list of all the images stored on the external storage (e.  content://media/external/images . video and images. Format of the query URI is like: <standard_prefix> ://< authority>/<data_path>/<id>  The various parts of the URI are as follows:  The standard prefix for content providers is always content://. call details.Returns a list of all calls registered in the Call Log. Settings — Stores the device’s settings and preferences.. Media store.  To query a content provider.Returns a list of bookmarks stored in the browser.provider.  content://call_log/calls .  The id specifies the specific record They are as follows: . Media Store — Stores media files such as audio.  content://browser/bookmarks . Call log.  Some more other examples of query strings:  content://media/internal/images . SD card) on the device.wrox. Then the URI will be like content://contacts/people.  Third-party providers – com.Returns a list of all the internal images on the device. Example:  Built-in Providers – Contacts.snigdha.  The authority specifies the name of the content provider.  The data path specifies the kind of data requested. Broadcast announcements are of two types. Example: Getting the contacts from Contacts content provider. Broadcast Receivers in Android   A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements.g. we should specify the query string in the form of an URI.   Call Log — Stores data such as missed calls.

 As each receiver executes in turn. it can propagate a result to the next receiver.  Example: It might initiate a service to perform some work based on an event. The Intent broadcast mechanism is completely separate from Intents that are used to start Activities.  The time zone has changed. or it can completely abort the broadcast so that it won't be passed to other receivers.  Receivers with the same priority will be run in an arbitrary order.      . System originated.  Picture has been captured.  The screen has turned off. A broadcast receiver is just a gate way to other components and intended to do a very minimal amount of work.  All receivers of the broadcast are run in an undefined order.  Applications initiated. Normal broadcasts:  These are completely asynchronous.  The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter. often at the same time. Ordered broadcasts:  These broadcasts are delivered to one receiver at a time. They are  Normal broadcasts. System Originated:  Following are the examples of system originated broadcast announcements.  Announcing to other applications that some data has been downloaded to the device and is available for them to use.  Ordered broadcasts.  Battery is low. There are two types of broadcasts available. Application initiated:  Applications can also initiate the broadcast announcements.

Intents and Intent Filters Intents:  Intent is an asynchronous message.  There is no overlap within these messaging systems. Starting an Activity with Intent is a foreground operation that modifies what the user is currently interacting with. never to activities or services. startActivityForResult() – get an existing activity to do something new.  Broadcasting an Intent is a background operation that the user is not normally aware of. o Intent is nothing but a description of an operation to be performed. and so on.  Activities. Only call back method in Receiver. bindService() – Intent object is passed to establish a connection between the calling component and a target service.  There are separate mechanisms for delivering intents to each type of component. And it contains: . startActivity() – to launch an activity.  Services: startService() –Intent object is passed to initiate a service or deliver new instructions to an ongoing service. They are as follows:  Activity: An Intent object is passed to the following methods.  Intent Objects: An Intent object is a bundle of information.  Intent messaging is a facility for late run-time binding between components in the same or different applications. An intent passed to an Activity is delivered only to an activity. services and broadcast receivers are activated through the intents. never to a service or broadcast receiver.  Broadcast Receivers: Intent objects passed to any of the broadcast methods are delivered to all interested broadcast receivers. Intent). which return some result.  Broadcast Receiver lifecycle:  A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context.  Broadcast intents are delivered only to broadcast receivers.

the Intent object is delivered to an instance of the designated class. Name  The name of the component that should handle the intent. A headset has been plugged into the device. ACTION_SYNC activity ACTION_BATTERY_LOW ACTION_HEADSET_PLUG broadcast receiver broadcast receiver . Android uses other information in the Intent object to locate a suitable target.  The component name is optional.  Action  Action is a string naming the action to be performed.  If it is set. Synchronize data on a server with data on the mobile device. or unplugged from it. If it is not set. with no data input and no returned output. Display data for the user to edit.  An Action in an Intent Object is set by the setAction() method and read by getAction()  Predefined action constants: Constant ACTION_CALL ACTION_EDIT ACTION_MAIN Target component activity activity activity Action Initiate a phone call. Start up as the initial activity of a task. A warning that the battery is low.

SHOW_COLOR". After that we should include the application package as a prefix.  Data  The URI of the data to be acted on and the MIME type of that data.  The URI is read by getData() and the type by getType().example.  We can add a Category to Intent Object by calling addCategory() method.  The following table illustrates the some of category constants defines by Intent class. we can remove a category from the intent object.  By calling removeCategory() method. and setDataAndType() specifies it as both a URI and a MIME type. The setting for the time zone has changed.  We can also define our own action strings for activating the components in our application.project. If the action is ACTION_CALL.  Category  A string containing additional information about the kind of component that should handle the intent. setType() specifies it only as a MIME type.  Any number of category descriptions can be placed in an Intent object. the data field would be a tel: URI with the number to call. .  For example.  Using getCategories() we can get the set of all the categories in the Intent Object. the data field would contain the URI of the document to be displayed for editing. if the action field is ACTION_EDIT.  The setData() method specifies data only as a URI. For example: "com.ACTION_SCREEN_ON ACTION_TIMEZONE_CHANGED broadcast receiver broadcast receiver The screen has been turned on.

the first screen the user sees when the device is turned on or when the HOME key is pressed. an image or an e-mail message. etc  The Intent object has a series of put. () methods for inserting various types of extra data and a similar set of get."time-zone" extra ACTION_HEADSET_PLUG .. body.. we could also include extra pieces of data here to supply a subject. () methods for reading the data. The activity can be embedded inside of another activity that hosts gadgets.  Same as Bundle.  For example. an ACTION_TIMEZONE_CHANGED .―state‖ extra. . The activity can be the initial activity of a task and is listed in the top-level application launcher.  Many flags instruct the Android system how to launch an activity and how to treat it after it's launched. The activity displays the home screen. extras can be inserted into Intent Object using putExtras() and read using getExtras().. Flags:  Flags are of various sorts.Constant CATEGORY_BROWSABLE Meaning The target activity can be safely invoked by the browser to display data referenced by a link — for example. if we have a action to send an e-mail message. CATEGORY_GADGET CATEGORY_HOME CATEGORY_LAUNCHER CATEGORY_PREFERENCE Extras:  Key-value pairs for additional information that should be delivered to the component handling the intent.. The target activity is a preference panel.

structures associated with components that can potentially receive intents.  Android does so by comparing the contents of the Intent object to intent filters. services. Because the developers of other applications may not known to this application component names.  They are often used to activate components in other applications.  Activities.  Implicit Intents:  Implicit intents do not name a target. . it can receive only explicit intents. the Android system must find the best component (or components) to handle the intent. All the flags are defined in the Intent class.  If a component does not have any intent filters.  They open the component to the possibility of receiving implicit intents of the advertised type.  A component with filters can receive both explicit and implicit intents. and broadcast receivers can have one or more intent filters.  In the absence of a designated target.  Intent Filters:  Used to inform the system which implicit intents they can handle. Intent Resolution:  Intents can be divided into two groups:  Explicit intents  Implicit intents  Explicit Intents:  Explicit intents designate the target component by its name  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. Filters advertise the capabilities of a component and delimit the intents it can handle.  No special strategy is required for explicit intents.

ViewGroup. Examples of ViewGroups include LinearLayout and FrameLayout. All child elements of the Frame Layout are pinned to the top left corner of the screen.View. labels. 4. Table Layout. Common Layout Objects: The more common types of layout objects to use in android applications are as follows: 1. 2. and text boxes. Relative Layout. . 3. Examples of views are buttons.  Frame Layout:    Frame Layout is a blank space on the screen that we can later fill with a single object. cannot specify a location for a child views.view.view.    A component has separate filters for each job it can do. Frame Layout. A ViewGroup (which is itself a special type of view) provides the layout in which you can order the appearance and sequence of views. A ViewGroup derives from the base class android. Linear Layout:  Linear Layout aligns all children in a single direction — vertically or horizontally. A view is a widget that has an appearance on screen.  One or more views can be grouped together into a ViewGroup. An intent is filtered by:  Action  Category  Data User Interface Views and ViewGroups: An activity contains Views and ViewGroups. Linear Layout. A view derives from the base class android . depending on how you define the orientation attribute. Intent filters are set up in application's manifest file. Later child views will simply be drawn over earlier ones. A component can have multiple intent filters. each face it can present to the user.

An AdapterView is a view whose children are determined by an Adapter. So you can align two elements by right border. and a horizontal list will only be one row high (the height of the tallest child. or cells. centered in the screen. centered left. and gallery are commonly used subclasses of AdapterView. Table Layout:   TableLayout containers do not display border lines for their rows. and so on. Relative Layout:  parent view or to each other (specified by ID). but cells cannot span columns. plus padding). Kind of Adapters available in android are as follows: o Array adapter . so a vertical list will only have one child per row.  Adapters:      . gridView. Spinner. The Adapter provides access to the data items.  A table can leave cells empty.The easiest adapter to use o Cursor Adapter Relative Layout lets child views specify their position relative to the Table Layout positions its children into rows and columns. The Adapter is also responsible for making a View for each item in the data set.All children are stacked one after the other. no matter how wide they are. Some other Important View Groups:       Gallery GridView ListView ScrollView Spinner TabHost An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. or make one below another. columns. as they can in HTML. ListView. The table will have as many columns as the row with the most cells.

Spinner View:   Spinner is a widget similar to a drop-down list. it places them into the Overflow menu The user can open overflow menu by touching the "More" menu item. In Android. In Android. you activate the options menu by pressing the MENU key. Displays one item at a time. Grid View:  Grid view shows items in two-dimensional scrolling grid. Options Menu:        It appears when the user touches the MENU button Cannot display a checkbox or radio button Options Menu appears at the bottom of the screen visible portion of the Options Menu is the Icon menu It holds the first six menu items.  It positions the current selection at the center of the view. to activate a context menu you tap and hold on to it.  Context menu — Displays information related to a particular view on an activity. If you add more than six items.o Simple Cursor Adapter  The ArrayAdapter constructor takes three parameters: • The Context to use (typically this will be your activity instance) • The resource ID of a view to use (such as a built-in system resourceID) • The actual array or list of items to show Gallery View:  Gallery displays items in a horizontally scrolling list. List View:  View displays a list of items in a vertically scrolling list. Menus in Android  Menus are useful for displaying additional options that are not directly visible on the main UI of an application. Context Menu:  It’s a list of menu items that appears when the user touches and holds (Long press) a view. .  There are two main types of menus in Android:  Options menu — Displays information related to the current activity.

 May contain a nested <menu> element in order to create a submenu.  To create a menu resource. you must "register" the view for a context menu by calling registerForContextMenu()  To define the context menu's appearance and behavior. or three buttons . which represents a single item in a menu. create an XML file inside your project's res/menu/ directory  the menu build with the following elements:  Menu  Item  group Menu:  Is a container for menu items. invisible container for <item> elements  Allows you to categorize menu items Dialogs  A Dialog is a small window that appears in front of the current Activity. Group:  An optional. Item:  Creates a MenuItem.Conceptually similar to a ―right-click‖ on a PC Items in a context menu do not support icons or shortcut keys.  Must be the root node for the file  Can hold one or more <item>and <group> elements.  Alert Dialogs use any of the following features:  A title  A text message  One.  Used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress. onCreateContextMenu() and onContextItemSelected() Creating a menu resource. To provide a context menu for a view .  Various kind of dialogs are as follows:  AlertDialog  ProgressDialog  DatePickerDialog  TimePickerDialog AlertDialog  Is the most suggested Dialog type.     define a menu and all its items in an XML menu resource  inflate the menu resource (load it as a programmable object) in your application code. two.

Time Picker Dialog  A dialog that allows the user to select a time. Internal Storage. 2. Data Storage in android  Android provides several options to save persistent application data. A list of selectable items (with optional checkboxes or radio buttons) Progress Dialog  Display a progress animation in the form of a spinning wheel (or) progress bar  The progress dialog can also provide buttons. and year. 5. . 4. Network Connections.  The Time Picker widget allows the user to select the hour and minute. Date Picker Dialog  Date picker dialog allows the user to select the date. SQLite Database. Shared Preferences. The data storage options are as follows: 1.  The Date Picker widget allows the user to select the month. External storage. day.  progress bar:  Will show the progression with an animated progress bar. 3.  spinning wheel:  The default style of a progress dialog is the spinning wheel.

Birthday date. Example: Log file with coordinates of locations that a user has to share with others.  SQLite Database is used to store the relational data. driving license number. Shared Preferences used to store primitive data. Primitive data: Booleans. float. Example: Storing the data like images. Boolean etc. Shared Preferences is the simplest way to store the data for long term usage by an activity. string. (Primitive values: int. external storage the best way to store the data. Shared Preferences is used to store private primitive data in key value pairs. other applications will not be able to access it. Shared Preferences allows us to store and retrieve persistent primitive data in key-value pairs. To share large amount of data with other users. floats. And this data will be persist across user sessions even is our application is killed. longs. Example: To store the results of all the students in a school... music and simple data file and persisting them for later use.) Example: Data such as user ID. and strings. ints. .  Internal Storage is used to store the private data on device memory. The database that we create for an application is only accessible to itself. gender etc. Shared Preferences in Android      Shared Preferences used to store small chunk of data. Preferences may be for single activity or shared among the activities in an application. It is good to store ad-hoc data.  External Storage is used to store the public data on external storage media like SD card.

. Steps involved :  Create internal storage.  GetPreferences() – We use this when we need only single preferences file for our activity.Editor() – Editor class allows to save key-value pairs to preferences file. Files saved to the internal storage are private to that particular application and other applications cannot access those files.  Methods allowed by an Editor to save key-value pairs:  putBoolean()  putInt()  putFloat()  putString()  putLong()  Save the changes by calling commit(). Here. because it is only the preferences file for an activity. The file stored in the data/data/<package-name>/files folder. it doesn’t supply a name. The shared preferences file is saved as an XML file in the data/data/<package-name>/shared_prefs folder. File System in Android  Internal Storage:      Internal Storage is used to store the private data on device memory.  Writing the values:  Call edit() to get a SharedPreferences. It allows passing the name of the shared preferences file. They are:  getSharedPreferences()  getPreferences()  getSharedPreferences() – We use this when we need multiple preferences files (identify by the name). When the user uninstalls the application. those files are removed forever. There are two methods to get the Shared Preferences object in to our application.

 Write a file to the internal memory. External Storage:  External Storage is used to store the public data on external storage media like SD card. next step is to adding that SD card to emulator.  Give the path up to tools at command prompt (D:\Android\android-sdk-windows\tools).  When you click on sdcard you will get a window.     . To store large amount of files like images and videos we use this.  >mksdcard <size> 512M <location where do you want to create sdcard> D:\gvr. Adding SD card to emulator: After injecting files to the name to AVD.  SD card..under this select file radio button and browse your SD card created earlier..  Read a file from internal storage....  Target.img Injecting files to SD card:  Then install win image s/w in your system to inject the data to sdcard. Following are the fields we can see  Name.  open eclipse --> windows -->android SDK AVD manager  Click on New – a new window will be opened to create an AVD.  Later click on sdcard image in D drive to inject files to it. By storing files on SD card of the device users can easily transfer the data to other devices for use later.exe  Open command prompt. there select "image" tab under that select "inject‖ option to send data to sdcard. Creating SD card: Following are the steps involved in creating SD card  go to android sdk --> tools --> adb.  Click on create of the sdk.

Cursor() – which navigates results from database query and read rows & columns Difference b/w SQLite and other Databases  Data Typing: Irrespective to the data type specification for columns in a CREATE TABLE statement. 2. query () – is used to execute SQLite queries. Now the SD card is virtually inserted in emulator. not across all applications. SQLiteDatabase.  getReadableDatabase() – to read the data from the database.  SQLiteDatabase:  SQLiteDatabase exposes methods to manage a database. you can put whatever data you want in whatever column you want. SQLite Database    SQLite Database is used to store structural data.  Every SQLite query returns a cursor ( simply a row in database). The database cannot be used outside of the application. Creation of SQLiteDatabase:  The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method.       . execute SQL commands and perform other common database tasks. SQLiteOpenHelper. database name must be unique within an application.  SQLiteOpenHelper:  SQLiteOpenHelper is a class to manage database creation and version management.insert. This will throw SQLException. delete. Following are the methods to write and read from the database –  getWritableDatabase() – to write the data to the database. Key classes in SQLite : 1.  Example: putting a String in INTEGER column and vice versa.  It has methods to create. In SQLite Database.  Here onCreate() method is used to execute a SQLite command to create tables in the database.

 Manifest Typing: In Manifest Typing. This is called as Manifest Typing. FOREIGN KEY constraints.  LocationProvider. RIGHT OUTER JOIN and FULL OUTER JOIN and some flavours of ALTER TABLE.  Doesn’t return the location as quickly as user want.  Quickly consumes battery power.  We can utilize GPS and Android’s Network Location Provider to acquire the user location.  Network Location Provider:  Determines the user location using the cell-tower and Wi-Fi signals.  It uses less battery. nested transactions. Like.location package.  LcoationManager provides access to the system location services.  Key classes:  LocationManager. not of the column in which the value is stored. The SQLite database created by user in an application is always stored in the location data/data/<package-name>/databases.  SQLite thus allows the user to store any value of any data type into any column regardless of the declared type of that column.  GPS provider:  GPS is most accurate. Location Based Services  Android gives our applications access to the location services through the classes in the android. the data type is a property of the value itself.  To obtain the user location we can use both GPS and Network Location Provider or just one.  Responds faster. .  It works only outdoors. This is done through getSystemService.  It works indoors and outdoors.  Some of the standard SQL features are not supported by SQLite.

 In order to receive location updates we must request user permissions.ACCESS_FINE_LOCATION.The minimum distance interval for notifications.  minDistance .An object whose onLocationChanged() method will be called for each location update.  GPS_PROVIDER .  listener . This method takes four parameters:  Provider .  onProviderEnabled(String provider) — Called when the provider is enabled by the user.  The methods which we need to implement in our LocationListener class:  onLocationChanged(Location location) — Called when the location has changed.The name of the location provider you wish to use. Bundle extras) — Called when the provider status changes.  onStatusChanged(String provider.  Using DDMS we can simulate location data in several ways through Emulator Controls.The minimum time interval for notifications. Using LocationManager class we can obtain periodic updates of the locations. They are as follows:  Manually send individual longitude/latitude coordinates to the device.permission.  The following statement should be added to the AndroidManifest.  onProviderDisabled(String provider) — Called when the provider is disabled by the user.xml < uses-permission android:name=‖android.  Use a GPX file describing a route for playback to the device.  NETWORK_PROVIDER – ACCESS_COARSE_LOCATION. in milliseconds. then we need to request only the ACCESS_FINE_LOCATION permission.ACCESS_FINE_LOCATION‖ />  If we are using both NETWORK_PROVIDER and GPS_PROVIDER. because it includes permission for both providers. int status.  minTime .  Use a KML file describing individual place marks for sequenced playback to the device.  We can request location updates of devices using requestLocationUpdates() method. . in meters.

 To test Google Maps integration we need an AVD that uses an appropriate target. we need to build a project against the installed Google APIs add-on. Google Maps in Android  Google Maps is an add-on.  Upon this.  In side <application> element should mention a <uses-library> element.xml  INTERNET and ACCESS_COARSE_LOCATION. which displays a map with data obtained from the Google Maps service.maps  The key class in the maps library is it is not the part of the android’s open source which allow the user to click and pan through the map.  In  In Layout for MapActivity subclass we need to add an element named at the time of writing  We should describe the following things in AndroidManifest. we need to have API key for google maps. com.widget namespace.library> element contains the value android: name=”com.ACCESS_FINE_LOCATION permissions to be added.maps”  Above statement indicates that we are using one of the optional android API. That is as follows: Com. This < And the statement android: clickable=‖true‖ in layout.  Obtaining a Maps API key:  We should locate the SDK debug certificate located in the default folder of "C:\Documents and Settings###BOT_TEXT###lt;username>\Local Settings\Application Data\Android"  The file name of the debug key store is  We need this because MapView is not in the google. the Google APIs addon includes Maps external library. . (Available from Window > Show View > Other > Devices). To send location data through DDMS we must be sure that a device selected in the Devices panel.  To add mapping capabilities to our applications.keystore.maps.

google.Using the debug keystore. Now. we need to extract its MD5 fingerprint using the Keytool.exe from the "C:\ProgramFiles\Java###BOT_TEXT###lt;JDK_version_number>\bin" And enter your MD5 certificate fingerprint and click on ―Generate API key‖.keystore" -storepass android -keypass android  Figure-1 showing how to obtain the MD5 certificate fingerprint.  This fingerprint is needed to apply for the free Google Maps key. put the Google Maps key obtained earlier. We can usually find the Keytool.  Now copy the MD5 certificate fingerprint and navigate the web browser to http://code.exe application included with our JDK installation.  We should use <com.maps.  To extract the MD5 fingerprint issue the following command : keytool.mapView> element to display the Google maps in our activity. to obtain the Google Maps key.html .  Figure-1 Obtaining the MD5 fingerprint of the debug keystore  Zoom: .android.exe -list -alias androiddebugkey -keystore "C:\android\debug.  Now accept the terms and conditions by clicking the checkbox. in apiKey attribute.

Then call getOverlays() method on MapView and add() instance of overlay to it. build OverlayItem instances. This takes an integer representing the level of zoom. A level of 16 is a reasonable starting point for you to experiment with on real devices. Step 4: Override createItem() to return OverlayItem instances given an Index. Overlay:  If we want to add any overlay to our map we need to implement that as a subclass of Overlay. By calling setBuiltInZoomControls(true). Step 2: In the constructor.setStreetView(true).By default Google Maps displays in map mode. 1 is the world view and 21 is the tightest zoom we can get.. and call populate() when they are ready for use by the overlay. Publishing on Android Market . Satellite view – by calling setSatellite() method of MapView. you can zoom in or out of a location by simply touching the "+ or "-" buttons on the screen. Changing Views of the Map:    Map view .setSatellite(). the user will be able to zoom in and out of the map via zoom controls found in the bottom center of the map.     We can control the zoom level directly via the setZoom() method on the MapController. Street view . Using the zoom control. mapView. Step 1: override ItemizedOverlay<OverlayItem> as your own subclass. Step 3: Implement size() to return the number of items to be handled by the overlay.  Adding Markers to the Map: Displaying multiple markers to the map by ItemizedOvaerlay includes the following calling setStreetView() mapView.

permission.permission. For example:  <application android:label="@string/app_name" android:icon= "@drawable/myIcon"> Step 3: Configure version manifest data  Pick a version your application using android:versionCode and android:versionName in the manifest XML tag. especially if you’re programming a game o Have I decided on SDK compatibility? Getting your application ready Step 1: Request necessary Android permissions  Make sure that you’re requesting all necessary permissions <usespermission android:name="android.permission. versionCode should have an integer value that .  Buggy code makes for poor sales and a worse reputation o Does my application perform well?  Performance is really important. Publishing on Android Market is a straightforward process that you can do in just a few simple steps— o register o configure o upload o publish The Checklist o Have I tested my application extensively?  rigorous testing on the emulator and real .INTERNET"/> <usespermission android:name="android.VIBRATE"/> <usespermission android:name="android. Physical devices. 1.REBOOT"/> Step 2: Specify a name and icon  Name your application and give it an icon using the android:label and android:icon attribute in the application tag.  test on multiple hardware devices running different versions of the Android OS.   One of the most effective ways to get your application into users' hands is to publish it on an application marketplace like Android Market.

Step 4: Set compatibility options  If you’re utilizing newer Android features that aren’t available in older versions.  targetSdkVersion The API level that your application was design  maxSdkVersion An upper limit for compatibility. old log files. create an XML tag named uses-sdk. private data and unwanted resource files. Don’t set this unless you have a very good reason to. versionName on the other hand represents a userfriendly value. It’s a common practice to start at 1.0b or 2. then you’ll have to specify a set of version requirements. 2. Feel free to set this to whatever you think is appropriate – 0. Step 6: Sign and ZIP-align your application  Select the project and select File > Export.  minSdkVersion The minimum Android platform API level . sign and ZIP-align your application. Step 5: Cleanup files and remove logging  Go through your project and remove any logging calls.1 or 1.  .you must increment for every application update.  Open the Android drop-down and select Export Android Application  Follow the wizard’s steps to compile.1 would all technically work.4. To do this.

which Google will use to contact . fill out all the required information along with your real phone number.Step 7: Becoming a Market publisher  Registration  Register as a publisher and setup your profile. Next.  Pay a registration fee of $25 USD via Google Checkout. you must be a registered developer. Head over tohttp://market.  Read and agree to the Android Market Developer Distribution and sign in with your Google account.  To publish applications on the Android Market.

Lastly. click ―Publish. If you can’t decide on a developer name. You can also choose whether or not you want to release it as a free or paid app – though you need to be a registered Google Checkout Merchant to do the latter and it’s currently only available in a handful of countries. don’t in the event of an emergency or a problem with any of your Android applications. Step 8: Uploading an application  Login to your publisher account and click ―Upload an Application‖.‖ Congratulations. Just use your real name for now – you can always change that later via your profile page. Fill in all of the form data and include screenshots if you can and provide a precise. short and well-formatted description. you’ve just successfully published an application to the Android Market! .