You are on page 1of 41

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:

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

The Android Development Tools (ADT) plug-in for Eclipse is an extension to the Eclipse IDE that supports the creation and

debugging of Android applications. Using the ADT, you will be able to do the following in Eclipse: o Create new Android application projects. o Access the tools for accessing your Android emulators and devices. o Compile and debug Android applications. o Export Android applications into Android Packages (APK). o Create digital certificates for code-signing your APK. Application Fundamentals: Android applications are written in the Java programming language. The Android SDK tools compile the codealong with any data and resource filesinto an Android package, an archive file with an .apk suffix. By using the aapt tool, the data and resources bundled into a package. aapt- android asset packaging tool. Apk- android package kit. The .apk file is used to install the applications on Android-powered devices. Each Android application lives in its own world: By default, every application runs in its own Linux process Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed or when some system resources are required by other applications. Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications. By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only to that user, and to the application itself. 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, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.

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. To create a new android application use the Eclipse new-project wizard to

Creating a Project: create a new Android application. Project Structure: Root Contents

When you create a new Android project (e.g., via android create project), you get several items in the project's root directory, including: AndroidManifest.xml, which is an XML file describing the application being built and what components activities, services, etc. are being supplied by that application build.xml, which is an Ant script for compiling the application and installing it on the device default.properties and local.properties, property files used by the Ant build script assets/, which hold other static files you wish packaged with the application for deployment onto the device bin/, which holds the application once it is compiled gen/, where Android's build tools will place source code that they generate libs/, which holds any third-party Java JARs your application requires src/, which holds the Java source code for the application res/, which holds "resources", such as icons, GUI layouts, and the like, that get packaged with the compiled Java in the application Android 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 and some depend on each other, but each one exists as its own entity and plays a specific role There are four different types of application components in android. And they are as follows: 1. Activities. 2. Services. 3. Content Providers.

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

Playing the music while the user is in a different application. Fetching the data over the network without disturbance. Each service extends the Service base class. A service runs in the main thread of its hosting processthe service does not create its own thread and does not run in a separate process. Broadcast Receivers: A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements. Broadcast announcements are of two types. They are as follows: System originated. Applications initiated. System Originated: Following are the examples of system originated broadcast announcements. The screen has turned off. Battery is low. Picture has been captured. The time zone has changed.

Application initiated: Applications can also initiate the broadcast announcements. Announcing to other applications that some data has been downloaded to the device and is available for them to use.

A broadcast receiver is just a gate way to other components and intended to do a very minimal amount of work. Example: It might initiate a service to perform some work based on an event. Content Providers: A content provider makes a specific set of the application's data available to other applications.

You can store the data in file system, an SQLite Database, on the web or any other persistent storage location your application can access. 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. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any inter process communication that's involved. Activity Lifecycle: An Activity has three states. They are as follows: Running/Resumed Paused Stopped Resumed: The activity is in the foreground of the screen and has user focus. (At top of the activity stack) Paused: In this state an activity has lost focus but is still visible to the user. 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, but can be killed by the system in extremely low memory situations. Stopped: The activity is completely obscured by another activity. A stopped activity is also still alive. The activity object is retained in memory and it maintains all state and member information. However, 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.

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

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

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

onResume() Called when the activity starts interacting with the user. onPause() Called when the current activity is being paused and the previous activity is being resumed. 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. Services in Android

A service does not have a visual user interface. 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. 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(). Once the service has started it will run in the back ground, even if the component that started the service is destroyed. A started service performs only a single operation and does not return any result. For example, download or upload a file over the network. When the operation is done, the service should stop itself. Bound: A service is "bound" when an application component binds to it by calling bindService (). A bound service offers a client-server interface that allows components to interact with the service. A bound service runs only as long as another application component is bound to it.

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

Unbounded

Bounded

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

Call Log Stores data such as missed calls, call details, and so on. Settings Stores the devices settings and preferences. Media Store Stores media files such as audio, video and images.

To query a content provider, we should specify the query string in the form of an URI. 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://. The authority specifies the name of the content provider. Example: Built-in Providers Contacts, Media store, Call log. Third-party providers com.android.snigdha.providers or Com.wrox.provider. The data path specifies the kind of data requested. Example: Getting the contacts from Contacts content provider. Then the URI will be like content://contacts/people. The id specifies the specific record requested. Some more other examples of query strings: content://media/internal/images - Returns a list of all the internal images on the device. content://media/external/images - Returns a list of all the images stored on the external storage (e.g., SD card) on the device. content://call_log/calls - Returns a list of all calls registered in the Call Log. content://browser/bookmarks - Returns a list of bookmarks stored in the browser. Broadcast Receivers in Android A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements. Broadcast announcements are of two types. They are as follows:

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

Starting an Activity with Intent is a foreground operation that modifies what the user is currently interacting with. Broadcasting an Intent is a background operation that the user is not normally aware of. Broadcast Receiver lifecycle: A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Only call back method in Receiver.

Intents and Intent Filters Intents: Intent is an asynchronous message. Activities, services and broadcast receivers are activated through the intents. Intent messaging is a facility for late run-time binding between components in the same or different applications. o Intent is nothing but a description of an operation to be performed. There are separate mechanisms for delivering intents to each type of component. They are as follows: Activity: An Intent object is passed to the following methods. startActivity() to launch an activity. startActivityForResult() get an existing activity to do something new, which return some result. Services: startService() Intent object is passed to initiate a service or deliver new instructions to an ongoing service. bindService() Intent object is passed to establish a connection between the calling component and a target service. Broadcast Receivers: Intent objects passed to any of the broadcast methods are delivered to all interested broadcast receivers. 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 an Activity 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. And it contains:

Name The name of the component that should handle the intent. 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. Action Action is a string naming the action to be performed. 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. Display data for the user to edit. Start up as the initial activity of a task, with no data input and no returned output. Synchronize data on a server with data on the mobile device. A warning that the battery is low. A headset has been plugged into the device, or unplugged from it.

ACTION_SYNC

activity

ACTION_BATTERY_LOW ACTION_HEADSET_PLUG

broadcast receiver broadcast receiver

ACTION_SCREEN_ON ACTION_TIMEZONE_CHANGED

broadcast receiver broadcast receiver

The screen has been turned on. The setting for the time zone has changed.

We can also define our own action strings for activating the components in our application. After that we should include the application package as a prefix. For example: "com.example.project.SHOW_COLOR".

Data The URI of the data to be acted on and the MIME type of that data. 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. 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. We can add a Category to Intent Object by calling addCategory() method. By calling removeCategory() method, we can remove a category from the intent object. Using getCategories() we can get the set of all the categories in the Intent Object. The following table illustrates the some of category constants defines by Intent class.

Constant CATEGORY_BROWSABLE

Meaning The target activity can be safely invoked by the browser to display data referenced by a link for example, an image or an e-mail message. The activity can be embedded inside of another activity that hosts gadgets. The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed. The activity can be the initial activity of a task and is listed in the top-level application launcher. The target activity is a preference panel.

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. For example, an ACTION_TIMEZONE_CHANGED - "time-zone" extra ACTION_HEADSET_PLUG - state extra. if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc 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. Same as Bundle, extras can be inserted into Intent Object using putExtras() and read using getExtras(). Flags: Flags are of various sorts. Many flags instruct the Android system how to launch an activity and how to treat it after it's launched.

All the flags are defined in the Intent class. 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. Because the developers of other applications may not known to this application component names. Android delivers an explicit intent to an instance of the designated target class. No special strategy is required for explicit intents. Implicit Intents: Implicit intents do not name a target. They are often used to activate components in other applications. In the absence of a designated target, the Android system must find the best component (or components) to handle the intent. Android 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. If a component does not have any intent filters, it can receive only explicit intents. A component with filters can receive both explicit and implicit intents. Intent Filters: Used to inform the system which implicit intents they can handle. Activities, services, and broadcast receivers can have one or more intent filters.

A component has separate filters for each job it can do, each face it can present to the user. Intent filters are set up in application's manifest file. A component can have multiple intent filters. An intent is filtered by: Action Category Data User Interface

Views and ViewGroups: An activity contains Views and ViewGroups. A view is a widget that has an appearance on screen. Examples of views are buttons, labels, and text boxes. A view derives from the base class android .view.View. One or more views can be grouped together into a ViewGroup. A ViewGroup (which is itself a special type of view) provides the layout in which you can order the appearance and sequence of views. Examples of ViewGroups include LinearLayout and FrameLayout. A ViewGroup derives from the base class android.view.ViewGroup. Common Layout Objects: The more common types of layout objects to use in android applications are as follows: 1. 2. 3. 4. Frame Layout. Linear Layout. Table Layout. Relative Layout.

Frame Layout: Frame Layout is a blank space on the screen that we can later fill with a single object. All child elements of the Frame Layout are pinned to the top left corner of the screen, cannot specify a location for a child views. Later child views will simply be drawn over earlier ones.

Linear Layout: Linear Layout aligns all children in a single direction vertically or horizontally, depending on how you define the orientation attribute.

All children are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row high (the height of the tallest child, plus padding). Table Layout: TableLayout containers do not display border lines for their rows, columns, or cells. The table will have as many columns as the row with the most cells. A table can leave cells empty, but cells cannot span columns, as they can in HTML. Relative Layout: parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on. 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. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set. An AdapterView is a view whose children are determined by an Adapter. ListView, gridView, Spinner, and gallery are commonly used subclasses of AdapterView. Kind of Adapters available in android are as follows: o Array adapter - 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.

Adapters:

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. It positions the current selection at the center of the view. Grid View: Grid view shows items in two-dimensional scrolling grid. List View: View displays a list of items in a vertically scrolling list. Spinner View: Spinner is a widget similar to a drop-down list. Displays one item at a time.

Menus in Android
Menus are useful for displaying additional options that are not directly visible on the main UI of an application. There are two main types of menus in Android: Options menu Displays information related to the current activity. In Android, you activate the options menu by pressing the MENU key. Context menu Displays information related to a particular view on an activity. In Android, to activate a context menu you tap and hold on to it. 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. If you add more than six items, it places them into the Overflow menu The user can open overflow menu by touching the "More" menu item.

Context Menu: Its a list of menu items that appears when the user touches and holds (Long press) a view.

Conceptually similar to a right-click on a PC Items in a context menu do not support icons or shortcut keys. To provide a context menu for a view , you must "register" the view for a context menu by calling registerForContextMenu() To define the context menu's appearance and behavior, onCreateContextMenu() and onContextItemSelected() Creating a menu resource; define a menu and all its items in an XML menu resource inflate the menu resource (load it as a programmable object) in your application code. To create a menu resource, create an XML file inside your project's res/menu/ directory the menu build with the following elements: Menu Item group Menu: Is a container for menu items. Must be the root node for the file Can hold one or more <item>and <group> elements. Item: Creates a MenuItem, which represents a single item in a menu. May contain a nested <menu> element in order to create a submenu. Group: An optional, 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. Used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress. Various kind of dialogs are as follows: AlertDialog ProgressDialog DatePickerDialog TimePickerDialog AlertDialog Is the most suggested Dialog type. Alert Dialogs 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)

Progress Dialog Display a progress animation in the form of a spinning wheel (or) progress bar The progress dialog can also provide buttons. spinning wheel: The default style of a progress dialog is the spinning wheel.

progress bar: Will show the progression with an animated progress bar.

Date Picker Dialog Date picker dialog allows the user to select the date. The Date Picker widget allows the user to select the month, day, and year. Time Picker Dialog A dialog that allows the user to select a time. The Time Picker widget allows the user to select the hour and minute. Data Storage in android Android provides several options to save persistent application data. The data storage options are as follows: 1. Shared Preferences. 2. Internal Storage. 3. External storage. 4. SQLite Database. 5. Network Connections.

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

There are two methods to get the Shared Preferences object in to our application. They are: getSharedPreferences() getPreferences() getSharedPreferences() We use this when we need multiple preferences files (identify by the name). It allows passing the name of the shared preferences file. GetPreferences() We use this when we need only single preferences file for our activity. Here, it doesnt supply a name, because it is only the preferences file for an activity.

Writing the values: Call edit() to get a SharedPreferences.Editor() Editor class allows to save key-value pairs to preferences file. Methods allowed by an Editor to save key-value pairs: putBoolean() putInt() putFloat() putString() putLong() Save the changes by calling commit(). 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. Files saved to the internal storage are private to that particular application and other applications cannot access those files. When the user uninstalls the application, those files are removed forever. The file stored in the data/data/<package-name>/files folder. Steps involved : Create internal storage.

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

Now the SD card is virtually inserted in emulator. SQLite Database SQLite Database is used to store structural data. The database cannot be used outside of the application. Key classes in SQLite : 1. SQLiteOpenHelper. 2. SQLiteDatabase. SQLiteOpenHelper: SQLiteOpenHelper is a class to manage database creation and version management. This will throw SQLException. SQLiteDatabase: SQLiteDatabase exposes methods to manage a database. It has methods to create,insert, delete, execute SQL commands and perform other common database tasks. Creation of SQLiteDatabase: The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method. Here onCreate() method is used to execute a SQLite command to create tables in the database. Following are the methods to write and read from the database getWritableDatabase() to write the data to the database. getReadableDatabase() to read the data from the database. In SQLite Database, database name must be unique within an application, not across all applications. query () is used to execute SQLite queries. Every SQLite query returns a cursor ( simply a row in database). 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, you can put whatever data you want in whatever column you want. Example: putting a String in INTEGER column and vice versa.

This is called as Manifest Typing. Manifest Typing: In Manifest Typing, the data type is a property of the value itself, not of the column in which the value is stored. SQLite thus allows the user to store any value of any data type into any column regardless of the declared type of that column. Some of the standard SQL features are not supported by SQLite. Like, FOREIGN KEY constraints, nested transactions, RIGHT OUTER JOIN and FULL OUTER JOIN and some flavours of ALTER TABLE. The SQLite database created by user in an application is always stored in the location data/data/<package-name>/databases. Location Based Services

Android gives our applications access to the location services through the classes in the android.location package. We can utilize GPS and Androids Network Location Provider to acquire the user location. GPS provider: GPS is most accurate. It works only outdoors. Quickly consumes battery power. Doesnt return the location as quickly as user want. Network Location Provider: Determines the user location using the cell-tower and Wi-Fi signals. It works indoors and outdoors. Responds faster. It uses less battery. To obtain the user location we can use both GPS and Network Location Provider or just one. Key classes: LocationManager. LocationProvider. LcoationManager provides access to the system location services. This is done through getSystemService.

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

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

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

Figure-1 Obtaining the MD5 fingerprint of the debug keystore Zoom:

We can control the zoom level directly via the setZoom() method on the MapController. This takes an integer representing the level of zoom. 1 is the world view and 21 is the tightest zoom we can get. A level of 16 is a reasonable starting point for you to experiment with on real devices. By calling setBuiltInZoomControls(true);, the user will be able to zoom in and out of the map via zoom controls found in the bottom center of the map. Using the zoom control, 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 - By default Google Maps displays in map mode. Satellite view by calling setSatellite() method of MapView. Street view - by calling setStreetView() mapView.setSatellite(); mapView.setStreetView(true);

Overlay: If we want to add any overlay to our map we need to implement that as a subclass of Overlay. Then call getOverlays() method on MapView and add() instance of overlay to it. Adding Markers to the Map: Displaying multiple markers to the map by ItemizedOvaerlay includes the following steps. Step 1: override ItemizedOverlay<OverlayItem> as your own subclass. Step 2: In the constructor, build OverlayItem instances, and call populate() when they are ready for use by the overlay. Step 3: Implement size() to return the number of items to be handled by the overlay. Step 4: Override createItem() to return OverlayItem instances given an Index. Publishing on Android Market

One of the most effective ways to get your application into users' hands is to publish it on an application marketplace like Android Market. 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 , Physical devices. test on multiple hardware devices running different versions of the Android OS. Buggy code makes for poor sales and a worse reputation o Does my application perform well? Performance is really important, especially if youre programming a game o Have I decided on SDK compatibility?

Getting your application ready Step 1: Request necessary Android permissions Make sure that youre requesting all necessary permissions <usespermission android:name="android.permission.VIBRATE"/> <usespermission android:name="android.permission.INTERNET"/> <usespermission android:name="android.permission.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. 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. 1. versionCode should have an integer value that

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

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

you in the event of an emergency or a problem with any of your Android applications. If you cant decide on a developer name, dont worry. Just use your real name for now you can always change that later via your profile page. Step 8: Uploading an application Login to your publisher account and click Upload an Application. Fill in all of the form data and include screenshots if you can and provide a precise, short and well-formatted description. 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 its currently only available in a handful of countries. Lastly, click Publish. Congratulations, youve just successfully published an application to the Android Market!

You might also like