Codes

Toast:
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
------------------------
Intents:
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
------------------------

Service

Most confusion about the Service class actually revolves around what it is not:

-A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
-A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:
A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Service Lifecycle :
There are two reasons that a service can be run by the system.

If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl. A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Audio and Video

Android includes a comprehensive Media Player to simplify the playback of audio and video.

Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case,
the file format and type of multimedia being played is abstracted from you as a developer.

The Media Player’s management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows:
- Initialize the Media Player with media to play.
- Prepare the Media Player for playback.
- Start the playback
- Pause or stop the playback prior to its completing.
- Playback complete.

To play a media resource you need to create a new MediaPlayer instance, initialize it with a media
source, and prepare it for playback.

Initializing Audio Content for PlaybackTo play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.

To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following:
- A resource identifier
- A URI to a local file using the file:// schema
- A URI to an online audio resource as a URL
- A URI to a local Content Provider row

Initializing audio content for playback
Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext,R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext,Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext,Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext,Settings.System.DEFAULT_RINGTONE_URI);

Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.

When using the setDataSource method it is vital that you call prepare on the Media Player before you
begin playback.

Using setDataSource and prepare to initialize audio playback
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();

In each case, once you’ve finished playback, callrelease on your Media Player object to free the associated resources:
mediaPlayer.release();

Android supports a limited number of simultaneous Media Player objects; not releasing them can cause runtime exceptions when the system runs out of resources.

Preparing for Video Playback
Playback of video content is slightly more involved than audio. To show a video, you must specify a display surface on which to show it. The following sections describe two alternatives for the playback of video content.

The first, using the Video View control, encapsulates the creation of a display surface and allocation and preparation of video content within a Media Player. The second technique allows you to specify your own display surface and manipulate the underlying Media Player instance directly.

Playing Video Using the Video ViewThe simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback.

The Video View supports the playback of local or streaming video as supported by the Media Player
component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play simply call setVideoPath or setVideoUri to specify the path to a local file, or the URI of a ContentProvider or remote video stream:
streamingVideoView.setVideoUri("http://www.mysite.com/videos/myvideo.3gp");
localVideoView.setVideoPath("/sdcard/test2.3gp");

Once initialized, you can control playback using the start, stopPlayback, pause, and seekTo methods. The Video View also includes the setKeepScreenOn method to apply a screen Wake Lock that will prevent the screen from being dimmed while playback is in progress.

Video playback using a Video View
VideoView videoView = (VideoView)findViewById(R.id.surface);
videoView.setKeepScreenOn(true);
videoView.setVideoPath("/sdcard/test2.3gp");
if (videoView.canSeekForward())
videoView.seekTo(videoView.getDuration()/2);
videoView.start();
[ . . . do something . . . ]
videoView.stopPlayback();
 
Setting up a Surface for Video Playback
The first step to using the Media Player to view video content is to prepare a Surface onto which the
video will be displayed. TheMedia Player requires a SurfaceHolder object for displaying video content,
assigned using the setDisplay method.


Sample layout including a Surface View
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
 

The Surface View is a wrapper around the Surface Holder object, which in turn is a wrapper around the Surface that is used to support visual updates from background threads.

Surface Holders are created asynchronously, so you must wait until the surfaceCreated handler has been fired before assigning the returned Surface Holder object to the Media Player.

Initializing and assigning a Surface View to a Media Player
public class MyActivity extends Activity implements SurfaceHolder.Callback
{
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());

} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
}



Initializing Video Content for Playback
Once you have created and assigned the Surface Holder to your Media Player, use the setDataSource method to specify the path, URL, or Content Provider URI of the video resource to play.

As with audio playback, if you’re passing a URL to an online media file, the file must be capable of
progressive download using the RTSP or HTTP protocols.

Once you’ve selected your media source, callprepare to initialize the Media Player in preparation for
playback.

Initializing video for playback using the Media Player
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("/sdcard/test2.3gp");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}

Notification

Your applications can use Notifications to alert users without using an Activity. Notifications are handled by the Notification Manager, and currently have the ability to:
- Create new status bar icons
- Display additional information (and launch an Intent) in the extended status bar window
- Flash the lights/LEDs
- Vibrate the phone
- Sound audible alerts (ringtones, Media Store audio)


Using Notifications is the preferred way for invisible application components (Broadcast Receivers, Services, and inactive Activities) to alert users that events have occurred that may require attention. They are also used to indicate ongoing background Services — particularly Services that have been
set to foreground priority.

As a user interface metaphor, Notifications are particularly well suited to mobile devices. It’s likely that your users will have their phones with them at all times but quite unlikely that they will be paying attention to them, or your application, at any given time. Generally users will have several applications open in the background, and they won’t be paying attention to any of them.

In this environment it’s important that your applications be able to alert users when specific events occur that require their attention. Notifications can be persisted through insistent repetition, being marked ongoing, or simply by displaying an icon on the status bar. Status bar icons can be updated regularly or expanded to show additional information using the expanded status bar window

Permissions

Permissions are an application-level security mechanism that lets you restrict access to application components. Permissions are used to prevent malicious applications from corrupting data, gaining access to sensitive information, or making excessive (or unauthorized) use of hardware resources or external communication channels.

The native permission strings used by native Android Activities and Services can be found as static constants in the android.Manifest.permission class. To use permission-protected components, you need to add <uses-permission> tags to application manifests, specifying the permission string that each application requires.

When an application package is installed, the permissions requested in its manifest are analyzed and granted (or denied) by checks with trusted authorities and user feedback.

Declaring and Enforcing Permissions:
 <uses-permission
        android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission
        android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.INTERNET" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SECURE_SETTINGS" />
    <uses-permission
        android:name="android.permission.READ_CONTACTS" />
    <uses-permission
        android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_STATS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SYNC_SETTINGS" />


To include permission requirements for your own application components, use the permission attribute in the application manifest. Permission constraints can be enforced throughout your application, most usefully at application interface boundaries, for example:- Activities Add a permission to limit the ability of other applications to launch an Activity.
- Broadcast Receivers Control which applications can send broadcast Intents to your Receiver.
- Content Providers Limit read access and write operations on Content Providers.
- Services Limit the ability of other applications to start, or bind to, a Service.

In each case, you can add a permission attribute to the application component in the manifest, specifying a required permission string to access each component

Content Providers let you set readPermission and writePermission attributes to offer a more granular
control over read/write access.

Android Database

SQLite offers a powerful SQL database library that provides a robust persistence layer over which you have total control. Using SQLite you can create independent relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the /data/data/<package_name>/databases folder on your device (or emulator). By default all databases are private, accessible only by the application that created them.

Content Providers offer a generic interface to any data source by decoupling the data storage layer from the application layer. Content Providers offer a standard interface your applications can use to share data with and consume data from other applications— including many of the native data stores.

SQLite is a well regarded relational database management system (RDBMS). It is Open-source, Standards-compliant, Lightweight & Single-tier.

CURSORS AND CONTENT VALUES:ContentValues are used to insert new rows into tables. Each Content Values object represents a single
table row as a map of column names to values.

Queries in Android are returned as Cursor objects. Rather than extracting and returning a copy of the result values, Cursors are pointers to the result set within the underlying data. Cursors provide a managed way of controlling your position (row) in the result set of a database query.
The Cursor class includes a number of navigation functions including, but not limited to, the following:
moveToFirst Moves the cursor to the first row in the query result
moveToNext Moves the cursor to the next row
moveToPrevious Moves the cursor to the previous row
getCount Returns the number of rows in the result set
getColumnIndexOrThrow Returns the index for the column with the specified name (throwing
an exception if no column exists with that name)
getColumnName Returns the name of the specified column index
getColumnNames Returns a string array of all the column names in the current Cursor
moveToPosition Moves the Cursor to the specified row
getPosition Returns the current Cursor position

Android provides a convenient mechanism for simplifying the management of Cursors within your Activities. The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.

Querying a Database
To execute a query on a database use the query method, passing in:
- An optional Boolean that specifies if the result set should contain only unique values.
- The name of the table to query.
- A projection, as an array of strings, that lists the columns to include in the result set.
- A ‘‘where’’ clause that defines the rows to be returned. You can include ? wildcards that will
be replaced by the values passed in through the selection argument parameter.
- An array of selection argument strings that will replace the ?’s in the where clause.
- A ‘‘group by’’ clause that defines how the resulting rows will be grouped.
- A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause.
- A string that describes the order of the returned rows.
- An optional string that defines a limit for the number of returned rows.

// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order);

Extracting values from a Cursor
int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;

// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();

Because SQLite database columns are loosely typed, you can cast individual values into valid types as
required.

SAVING AND LOADING FILES

It’s good practice to use Shared Preferences or a database to store your application data, but there are still times when you’ll want to use files directly rather than rely on Android’s managed mechanisms. As well as the standard Java I/O classes and methods, Android offers openFileInput and openFileOuput to simplify reading and writing streams from and to local files.

Saving and loading files
String FILE_NAME = "tempfile.tmp";
// Create a new output file stream that’s private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fis = openFileInput(FILE_NAME);

These methods support only those files in the current application folder; specifying path separators will cause an exception to be thrown. If the file name you specify when creating a FileOutputStream does  not exist, Android will create it for you.

INCLUDING STATIC FILES AS RESOURCES
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.

To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the file name (without extension) as the variable name from the R.raw class, as shown in the following skeleton code:

Resources myResources = getResources();
InputStream myFile = myResources.openRawResource(R.raw.myfilename);

Adding raw files to your resources hierarchy is an excellent alternative for large, preexisting data sources (such as dictionaries) for which it’s not desirable (or even possible) to convert them into Android databases.

Android’s resource mechanism lets you specify alternative resource files for different languages, locations, and hardware configurations. You could, for example, create an application that loads a different dictionary resource based on the user’s language settings.

FILE MANAGEMENT TOOLS
Android supplies some basic file management tools to help you deal with the file system. Many of these utilities are located within the standard java.io.File package.

➤ deleteFile Enables you to remove files created by the current application.
➤ fileList Returns a string array that includes all the files created by the current application.

These methods are particularly useful for cleaning up temporary files left behind if your application
crashes or is killed unexpectedly.

Shared Preferences

Using the SharedPreferences class you can create named maps of key/value pairs within your application that can be shared among application components running in the same application context.

Shared Preferences support the primitive types Boolean, string, float, long, and integer, making them an ideal means of quickly storing default values, class instance variables, the current UI state, and user preferences. They are most commonly used to persist data across user sessions and to share settings among application components.

Activities also offer the onSaveInstanceState handler. It’s designed specifically to persist UI state when the Activity becomes eligible for termination by a resource-hungry run time.

The handler works like the Shared Preference mechanism. It offers a Bundle parameter that represents a key/value map of primitive types that can be used to save the Activity’s instance values. This Bundle is then made available as a parameter passed in to the onCreate and onRestoreInstanceState method handlers.

This UI state Bundle should be used to record the values needed for an Activity to present an identical UI when it’s displayed after an unexpected close.

CREATING AND SAVING PREFERENCES
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("wholeNumber", 2);
editor.putLong("aNumber", 3l);
editor.putString("textEntryValue", "Not Empty");
// Commit the changes.
editor.commit();
}

RETRIEVING SHARED PREFERENCES
public static String MY_PREFS = "MY_PREFS";
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
long aNumber = mySharedPreferences.getLong("aNumber", 0);
String stringPreference = mySharedPreferences.getString("textEntryValue", "");
}

The Preference Activity framework consists of three parts:
- Preference Screen Layout: An XML file that defines the hierarchy displayed in your Preference Activity. It specifies the controls to display, the values to allow, and the Shared Preference keys to use for each UI control.
-Preference Activity: An extension of PreferenceActivity that will be used to host your application preference screens.
- Shared Preference Change Listener: An implementation of the onSharedPreferenceChangeListener class used to listen for changes to Shared Preferences.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="My Preference Category"/>
<CheckBoxPreference android:key="PREF_CHECK_BOX" android:title="Check Box Preference"
android:summary="Check Box Preference Description" android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>

Native Preference Controls:
Android includes several preference controls to build your Preference Screens:
- CheckBoxPreference: A standard preference checkbox control. Used to set preferences to true or false.
- EditTextPreference: Allows users to enter a string value as a preference. Selecting the preference text will display a text entry dialog.
- ListPreference: The preference equivalent of a spinner. Selecting this preference will display a dialog
box containing a list of values from which to select. You can specify different arrays to contain the display text and selection values.
- RingtonePreference: A specialized List Preference that presents the list of available ringtones for user selection. This is particularly useful when you’re constructing a screen to configure notification settings.

Dialog

Dialog boxes are a common UI metaphor in desktop, web, and mobile applications. They’re used to help users answer questions, make selections, and confirm actions, and to display warning or error  messages. Dialog boxes in Android are partially transparent, floating Activities that partially obscure the Activities that launched them.

There are three ways to implement a dialog in Android: .

- Using the Dialog class: As well as the general-purpose AlertDialog class, Android includes a number of specialist classes that extend Dialog. Each is designed to provide specific dialog box functionality. A Dialog-class-based screen is constructed entirely within its calling Activity, so it doesn’t need to be registered in the manifest as its life cycle is controlled entirely by the calling Activity.

- Dialog-themed Activities: You can apply the dialog theme to a regular Activity to give it the appearance of a standard dialog box.

- Toasts: Toasts are special non-modal transient message boxes, often used by Broadcast Receivers and Services to notify users of events occurring in the background.

The Alert Dialog Class
The AlertDialog class is one of the most versatile Dialog-class implementations. It offers a number of
options that let you construct screens for some of the most common dialog-box use cases, including:

- Presenting a message to the user offering them one to three options in the form of buttons. This functionality is probably familiar to you if you’ve done any desktop programming for which the buttons presented are usually a combination of OK, Cancel, Yes, and No.
- Offering a list of options in the form of checkboxes or radio buttons.
- Providing a text entry box for user input.

To construct the Alert Dialog user interface, create a new AlertDialog.Builder object as follows:
AlertDialog.Builder ad = new AlertDialog.Builder(context);

You can then assign values for the title and message to display, and optionally assign values to be used
for any buttons, selection items, and text input boxes you wish to display. That includes setting event
listeners to handle user interaction.

Specialist Input Dialogs
One of the major uses of dialog boxes is to provide an interface for user input. Android includes several
specialist dialog boxes that encapsulate controls designed to facilitate common user-input requests.

They include the following:
- CharacterPickerDialog: Lets users select an accented character based on a regular character source.
- DatePickerDialog: Lets users select a date from a DatePicker View. The constructor includes a callback listener to alert your calling Activity when the date has been set.
-TimePickerDialog: Similar to the Date Picker Dialog, this dialog lets users select a time from a TimePicker View.
- ProgressDialog: A dialog that displays a progress bar beneath a message text box. Perfect for keeping the user informed of ongoing progress of a time-consuming operation.

Configuring an Alert Dialog
Context context = MyActivity.this;
String title = "It is Pitch Black";
String message = "You are likely to be eaten by a grue.";
String button1String = "Go Back";
String button2String = "Move Forward";
AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle(title);
ad.setMessage(message);
ad.setPositiveButton(button1String,new OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
eatenByGrue();
} });
ad.setNegativeButton(button2String,
new OnClickListener(){
public void onClick(DialogInterface dialog, int arg1) {
// do nothing
}
});
ad.setCancelable(true);
ad.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
eatenByGrue();
}
});

To display an Alert Dialog that you’ve created callshow:
ad.show();

A better alternative is using your Activity’sonCreateDialog and onPrepareDialog handlers to create dialog instances that can persist state.

Adapters

Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface. The adapter is responsible for creating the child Views used to represent each item within the parent View, and providing access to the underlying data. Views that support Adapter binding must extend the AdapterView abstract class.

- ListAdapter: Extended Adapter that is the bridge between a ListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

- ArrayAdapter: A listAdapter that manages a ListView backed by an array of arbitrary objects. By default, this class expects  that the provided resource id references a single text view.

- CursorAdapter: Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.

- HeaderViewListAdapter: ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.

- SourceCursorAdapter: It is used to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views

- SimpleAdapter: It is used to to map static data to views defined in an XML file.

- SpinnerAdapter: It  is the bridge between a Spinner and its data. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.

- WrappedListAdapter: List adapter that wraps another list adapter. The wrapped adapter can be retrieved by calling getWrappedAdapter().

Intents

Intents are used as a message-passing mechanism that works both within your application, and between
applications. Intents can be used to:

- Declare your intention that an Activity or Service be started to perform an action, usually with (or on) a particular piece of data.
- Broadcast that an event (or action) has occurred.
- Explicitly start a particular Service or Activity.

You can use Intents to support interaction among any of the application components installed on an Android device, no matter which application they’re a part of. This turns your device from a platform containing a collection of independent components into a single interconnected system.

One of the most common uses for Intents is to start new Activities, either explicitly (by specifying the class to load) or implicitly (by requesting that an action be performed on a piece of data).
 
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);


Starting an Activity for a result
private static final int SHOW_SUBACTIVITY = 1;
Intent intent = new Intent(this, MyOtherActivity.class);
startActivityForResult(intent, SHOW_SUBACTIVITY);

Intents can also be used to broadcast messages across the system. Any application can register Broadcast Receivers to listen for, and react to, these broadcast Intents. This lets you create event-driven applications based on internal, system, or third-party-application events.

Android broadcasts Intents to announce system events, like changes in Internet connection status or battery charge levels. The native Android applications, such as the phone dialer and SMS manager, simply register components that listen for specific broadcast Intents — such as ‘‘incoming phone call’’ or ‘‘SMS message received’’ — and react accordingly.

Using Intents to propagate actions — even within the same application — is a fundamental Android design principle. It encourages the decoupling of components, to allow the seamless replacement of application elements. It also provides the basis of a simple model for extending an application’s functionality.

Menu

Menus offer a way to expose application functions without sacrificing valuable screen space. Each Activity can specify its own menu that’s displayed when the device’s menu button is pressed. Android also supports context menus that can be assigned to any View. Context menus are normally triggered when a user holds the middle D-pad button, depresses the trackball, or long-presses the touchscreen for around three seconds when the View has focus.

Activity and context menus support submenus, checkboxes, radio buttons, shortcut keys, and icons.

To improve the usability of application menus, Android features a three-stage menu system optimized
for small screens:

-The icon menu appears along the bottom of the screen when the menu button is pressed. It displays the icons and text for a limited number of Menu Items (typically six). This icon menu does not display checkboxes, radio buttons, or the shortcut keys for MenuItems.

If the Activity menu contains more than the maximum number of visible Menu Items, a More Menu Item is displayed. When selected, it displays the expanded menu. Pressing the back button closes the icon menu.

-The expanded menu The expanded menu is triggered when a user selects the More Menu Item from the icon menu. It displays a scrollable list of only theMenu Items that weren’t visible in the icon menu. This menu displays full text, shortcut keys, and checkboxes/radio buttons. It does not, however, display icons. Pressing back from the expanded menu returns you to the icon menu.

Submenus The traditional expanding hierarchical tree can be awkward to navigate using a mouse, so it’s no surprise that this metaphor is particularly ill-suited for use on mobile devices. The Android
alternative is to display each submenu in a floating window.

Since Android does not support nested submenus, you can’t add a submenu to a submenu. As with the extended menu, icons are not displayed in the submenu.

Defining a menu in XML
<menu xmlns:android="http://schemas.android.com/apk/res/android" android:name="Context Menu">
<item android:id="@+id/item01" android:icon="@drawable/menu_item" android:title="Item 1">
</item>
<item android:id="@+id/item02" android:checkable="true" android:title="Item 2">
</item>
<item android:id="@+id/item03" android:numericShortcut="3" android:alphabeticShortcut="3"
android:title="Item 3">
</item>
<item android:id="@+id/item04" android:title="Submenu">
<menu>
<item android:id="@+id/item05" android:title="Submenu Item">
</item>
</menu>
</item>
</menu>

To use your Menu resource, use the MenuInflator class within your onCreateOptionsMenu or onCreateContextMenu event handlers. Inflating an XML menu resource:

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
menu.setHeaderTitle("Context Menu");
}

Drawable Resources

There are several new types of Drawables resources — including shapes and transformative and composite Drawables — and be shown how to use these resources to create user interfaces that are independent of screen size and resolution.

Drawables: Color,Shape,Gradient, Composite, Transformative, Layer, State List, LevelList, NinePatch

Color Drawable:
A ColorDrawable, the simplest of the XML-defined Drawables, lets you specify an image asset based on a single solid color. Color Drawables are defined as XML files using the <color> tag in the Drawable resources folder.
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="#FF0000"/>

Shape Drawable:
Shape Drawable resources let you define simple primitive shapes by defining their dimensions, background, and stroke/outline using the <shape> tag.

Each shape consists of a type (specified via the shape attribute), attributes that define the dimensions of
that shape, and subnodes to specify padding, stroke (or outline), and background color values.
Android currently supports the following shape types as values for the shape attribute:
oval A simple oval shape.
 rectangle Also supports a <corners> subnode that uses a radius attribute to create a rounded rectangle.
ring Supports the innerRadius and thickness attributes to let you specify, respectively, the inner radius of the ring shape and its thickness. Alternatively, you can use innerRadiusRatio and/or thicknessRatio to define the ring’s inner radius and thickness as a proportion of its width.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#f0600000"/>
<stroke android:width="10dp" android:color="#00FF00"/>
<corners android:radius="15dp" />
<padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp"/>
</shape>

Gradient Drawable:
A GradientDrawable lets you design complex gradient fills. Each gradient defines a smooth transition
between two or three colors in a linear, radial, or sweep pattern.

Gradient Drawables are defined using the <gradient> tag as a subnode within a Shape Drawable definition. Each Gradient Drawable requires at least a startColor and endColor attribute and supports an optional middleColor.

Using the type attribute you can define your gradient as one of the following:
linear The default gradient type, it displays a straight color transition from startColor to endColor at an angle defined by the angle attribute.
radial Draws a circular gradient from startColor to endColor from the outer edge of the shape to the center. It requires a gradientRadius attribute that specifies the radius of the gradient transition in pixels. It also optionally supports centerX and centerY to offset the location of the center of the gradient. Because the gradient radius is defined in pixels it will not be dynamically scaled for different pixel densities. To minimize banding, you may need to specify different gradient radius values for different screen resolutions.
sweep Draws a sweep gradient that transitions from startColor to endColor along the outer edge of the parent shape (typically a ring).


Composite Drawables:
Use composite Drawables to combine and manipulate other Drawable resources. Any Drawable  resource can be used within the following composite resource definitions, including bitmaps, shapes, and colors. Similarly, these new Drawables can be used within each other and assigned to Views in the same way as all other Drawable assets.


Transformative Drawables:
You can scale and rotate existing Drawable resources using the aptly named ScaleDrawable and RotateDrawable classes. These transformative Drawables are particularly useful for creating progress bars or animating Views.

ScaleDrawable Within the <scale> tag, use the scaleHeight and scaleWidth attributes to define the target height and width relative to the bounding box of the original Drawable. Use the scaleGravity attribute to control the anchor point for the scaled image.
RotateDrawable Within the <rotate> tag, use fromDegrees and toDegrees to define the start and end rotation angle around a pivot point. Define the pivot using the pivotX and pivotY attributes,

<!-- Rotation Drawable Resource -->
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/icon" android:fromDegrees="0" android:toDegrees="90"
android:pivotX="50%" android:pivotY="50%" />

<!-- Scale Drawable Resource -->
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/icon" android:scaleHeight="100%" android:scaleWidth="100%"/>

Applying rotation and scale Drawable transformations in code
ImageView rotatingImage = (ImageView)findViewById(R.id.RotatingImageView);
ImageView scalingImage = (ImageView)findViewById(R.id.ScalingImageView);
// Rotate the image 50% of the way to its final orientation.
rotatingImage.setImageLevel(5000);
// Scale the image to 50% of its final size.
scalingImage.setImageLevel(5000);

Layer Drawable:
A LayerDrawable lets you composite several Drawable resources on top of one another. If you define an array of partially transparent Drawables you can stack them on top of one another to create complex
combinations of dynamic shapes and transformations.

Similarly, you can use Layer Drawables as the source for the transformative Drawable resources
described in the preceding section, or the State List and Level List Drawables that follow.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bottomimage"/>
<item android:drawable="@drawable/image2"/>
<item android:drawable="@drawable/image3"/>
<item android:drawable="@drawable/topimage"/>
</layer-list>


State List Drawables:
A State List Drawable is a composite resource that enables you to specify a different Drawable to display based on the state of the View to which it has been assigned. Most native Android Views use State List Drawables, including the image used on Buttons and the background used for standard List View items.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:drawable="@drawable/widget_bg_normal"/>
<item android:state_pressed="true" android:drawable="@drawable/widget_bg_pressed"/>
<item android:state_focused="true" android:drawable="@drawable/widget_bg_selected"/>
<item android:drawable="@drawable/widget_bg_normal"/>
</selector>

Level List Drawables:
Using a Level List Drawable you can effectively overlay several Drawable resources, specifying an
integer index value for each layer.

To select which image to display in code call setImageLevel on the View displaying the Level List
Drawable resource, passing in the index of the Drawable you wish to display.
imageView.setImageLevel(5);

The View will display the image corresponding to the index with an equal or greater value to the one
specified. Level List Drawables are particularly useful when creating Widget layouts.

NinePatch Drawable:
NinePatch (or stretchable) images are PNG files that mark the parts of an image that can be stretched.
NinePatch images must be properly defined PNG files that end in .9.png. The resource identifier for
NinePatches is the file name without the trailing .9.png.

A NinePatch is a variation of a PNG image that uses a one-pixel border to define the area of the image
that can be stretched if the image is enlarged. To create a NinePatch, draw single-pixel black lines that
represent stretchable areas along the left and top borders of your image. The unmarked sections won’t
be resized, and the relative size of each of the marked sections will remain the same as the image size
changes.

Layouts

Layout managers are extensions of the ViewGroup class used to position child controls for your UI. Layouts can be nested, letting you create arbitrarily complex interfaces using a combination of layouts.

-FrameLayout: The simplest of the Layout Managers, the Frame Layout simply pins each child view to the top left corner. Adding multiple children stacks each new child on top of the one before, with each new View obscuring the last.

-LinearLayout: A Linear Layout aligns each child View in either a vertical or a horizontal line. A vertical layout has a column of Views, while a horizontal layout has a row of Views. The Linear Layout manager enables you to specify a ‘‘weight’’ for each child View that controls the relative size of each within the available space.

- RelativeLayout: The most flexible of the native layouts, the Relative Layout lets you define the positions of each child View relative to the others and to the screen boundaries.

-TableLayout: The Table Layout lets you lay out Views using a grid of rows and columns. Tables can span multiple rows and columns, and columns can be set to shrink or grow.

- Gallery: A Gallery Layout displays a single row of items in a horizontally scrolling list.

The Android Widget Toolbox (view)

Android supplies a toolbox of standard Views to help you create simple interfaces. By using these controls (and modifying or extending them as necessary), you can simplify your development and provide consistency between applications.

The following list highlights some of the more familiar toolbox controls:
-TextView: A standard read-only text label. It supports multiline display, string formatting, and automatic word wrapping.
 
-EditText: An editable text entry box. It accepts multiline entry, word-wrapping, and hint text.
 
-ListView: A View Group that creates and manages a vertical list of Views, displaying them as rows within the list. The simplest List View displays the toString value of each object in an array, using a Text View for each item.
 
- Spinner: A composite control that displays a Text View and an associated List View that lets you select an item from a list to display in the textbox. It’s made from a Text View displaying the current selection, combined with a button that displays a selection dialog when pressed.

- Button: A standard push-button.
-CheckBox: A two-state button represented by a checked or unchecked box.
-RadioButton: A two-state grouped button. A group of these presents the user with a number of binary options of which only one can be enabled at a time.

-ViewFlipper: A View Group that lets you define a collection of Views as a horizontal row in which only one View is visible at a time, and in which transitions between visible views are animated.

-QuickContactBadge: Displays a badge showing the image icon assigned to a contact you specify using a phone number, name, e-mail address, or URI. Clicking the image will display the quick contact bar, which provides shortcuts for contacting the selected contact—including calling, sending an SMS, e-mail, and IM.

Android also supports several more advanced View implementations, including date-time pickers, auto-complete input boxes, maps, galleries, and tab sheets.

The Activity Life Cycle

A good understanding of the Activity life cycle is vital to ensure that your application provides a seamless user experience and properly manages its resources.

Android applications do not control their own process lifetimes; the Android run time manages the process of each application, and by extension that of each Activity within it. While the run time handles the termination and management of an Activity’s process, the Activity’s state helps determine the priority of its parent application. The application priority, in turn, influences the likelihood that the run time will terminate it and the Activities running within it.


The state of each Activity is determined by its position on the Activity stack, a last-in–first-out collection of all the currently running Activities. When a new Activity starts, the current foreground screen is moved to the top of the stack. If the user navigates back using the Back button, or the foreground Activity is closed, the next Activity on the stack moves up and becomes active.

Activity States:
As Activities are created and destroyed they move in and out of the stack. As they do so, they transition through four possible states:

-Active When an Activity is at the top of the stack it is the visible, focused, foreground Activity that is receiving user input. Android will attempt to keep it alive at all costs, killing Activities further down the stack as needed, to ensure that it has the resources it needs. When another Activity becomes active, this one will be paused.

-Paused In some cases your Activity will be visible but will not have focus; at this point it’s paused. This state is reached if a transparent or non-full-screen Activity is active in front of it. When paused, an Activity is treated as if it were active; however, it doesn’t receive user input events. In extreme cases Android will kill a paused Activity to recover resources for the active Activity.When an Activity becomes totally obscured, it is stopped.

-Stopped When an Activity isn’t visible, it ‘‘stops.’’ The Activity will remain in memory,retaining all state information; however, it is now a candidate for termination when the system requires memory elsewhere. When an Activity is stopped it’s important to save data and the current UI state. Once an Activity has exited or closed, it becomes inactive.

-Inactive After an Activity has been killed, and before it’s been launched, it’s inactive. Inactive Activities have been removed from the Activity stack and need to be restarted before they can be displayed and used.

Resources in Android

Application resources are stored under the res/ folder of your project hierarchy. In this folder, each of the available resource types can have a subfolder containing its resources.

There are seven primary resource types that have different folders: simple values, drawables, layouts, animations, XML, styles, and raw resources.

This process also creates an R class file that contains references to each of the resources you include in your project. This lets you reference the resources in your code, with the advantage of design time syntax checking.

In all cases, the resource file-names should contain only lowercase letters, numbers, and the period (.) and underscore (_) symbols.

1) Simple Values:
Supported simple values include strings, colors, dimensions, and string or integer arrays. All simple values are stored within XML files in the res/values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">To Do List</string>
<color name="app_background">#FF0000FF</color>
<dimen name="default_border">5px</dimen>
<array name="string_array">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</array>
<array name="integer_array">
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>



Dimensions are most commonly referenced within style and layout resources. They’re useful for creating layout constants such as borders and font heights. To specify a dimension resource use the <dimen> tag, specifying the dimension value, followed by an identifier describing the scale of your dimension:
px (screen pixels), in (physical inches), pt (physical points), mm (physical millimeters), dp (density-independent pixels relative to a 160-dpi screen), sp (scale-independent pixels)

Styles and Themes:
Style resources let your applications maintain a consistent look and feel by enabling you to specify the
attribute values used by Views. The most common use of themes and styles is to store the colors and
fonts for an application.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="BaseText">
<item name="android:textSize">14sp</item>
<item name="android:textColor">#111</item>
</style>
<style name="SmallText" parent="BaseText">
<item name="android:textSize">8sp</item>
</style>
</resources>

Drawables:
Drawable resources include bitmaps and NinePatch (stretchable PNG) images. They also include complex composite Drawables, such as LevelListDrawables and StateListDrawables that can be defined in XML. 


Layouts:
Layout resources let you decouple your presentation layer by designing user interface layouts in XML rather than constructing them in code. The most common use of a layout is for defining the user interface for an Activity. Once defined in XML, the layout is ‘‘inflated’’ within an Activity using setContentView, usually within the onCreate method.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>



Animations:
Android supports two types of animation. Tweened animations can be used to rotate, move, stretch and fade a View; or you can create frame-by-frame animations to display a sequence of Drawable images.

Tweened animation is stored in a separate XML file in the project’s res/anim folder. An animation can be defined for changes in alpha (fading), scale (scaling), translate (movement), or rotate (rotation).

Frame-by-frame animations let you create a sequence of Drawables, each of which will be displayed for a specified duration, on the background of a View.

Menus:
Create menu resources to further decouple your presentation layer by designing your menu layouts in XML rather than constructing them in code. Menu resources can be used to define both Activity and context menus within your applications, and provide the same options you would have when constructing your menus in code. Once defined in XML, a menu is ‘‘inflated’’ within your application via the inflate method of the MenuInflator Service, usually within the onCreateOptionsMenu method.

The Android Application Life Cycle

Unlike most traditional environments, Android applications have no control over their own life cycles.Instead, application components must listen for changes in the application state and react accordingly,taking particular care to be prepared for untimely termination.

The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. An application’s priority is equal to its highest-priority component.Where two applications have the same priority, the process that has been at a lower priority longest will be killed first. Process priority is also affected by interprocess dependencies; if an application has a dependency on a Service or Content Provider supplied by a second application, the secondary application will have at least as high a priority as the application it supports.

All Android applications will remain running and in memory until the system needs its resources for other applications.

Active Processes: Active (foreground) processes are those hosting applications with components currently interacting with the user. These are the processes Android is trying to keep responsive by reclaiming resources. There are generally very few of these processes, and they will be killed only as a last resort.

Active processes include:
- Activities in an “active” state; that is, they are in the foreground and responding to user events.
- Activities, Services, or Broadcast Receivers that are currently executing an onReceive event handler.
- Services that are executing an onStart, onCreate, or onDestroy event handler.

-Visible Processes: Visible, but inactive processes are those hosting “visible” Activities. As the name suggests, visible Activities are visible, but they aren’t in the foreground or responding to user events. This happens when an Activity is only partially obscured (by a non-full-screen or transparent Activity). There are generally very few visible processes, and they’ll only be killed in extreme circumstances to allow active processes to continue.

- Started Service Processes: Processes hosting Services that have been started. Services support ongoing processing that should continue without a visible interface. Because Services don’t interact directly with the user, they receive a slightly lower priority than visible Activities. They are still considered to be foreground processes and won’t be killed unless resources are needed for active or visible processes.

- Background Processes: Processes hosting Activities that aren’t visible and that don’t have any Services that have been started are considered background processes. There will generally be a large number of background processes that Android will kill using a last-seen-first-killed pattern to obtain resources for foreground processes.

-Empty Processes: To improve overall system performance, Android often retains applications in memory after they have reached the end of their lifetimes. Android maintains this cache to improve the start-up time of applications when they’re re-launched. These processes are routinely killed as required.
 ------------------------------------------------------------------------------------------------
The Application class also provides event handlers for application creation and termination, low available memory, and configuration changes. By overriding these methods you can implement your own application-specific behavior for each of these circumstances:
 
- onCreate Called when the application is created. Override this method to initialize your application singleton and create and initialize any application state variables or shared resources.

- onTerminate: Can be called when the application object is terminated. Note that there is no guarantee of this method handler’s being called. If the application is terminated by the kernel in order to free resources for other applications, the process will be terminated without warning and without a call to the application object’s onTerminate handler.

- onLowMemory: Provides an opportunity for well-behaved applications to free additional memory when the system is running low on resources. This will generally only be called when background processes have already been terminated and the current foreground applications are still low on memory. Override this handler to clear caches or release unnecessary resources.

- onConfigurationChanged: Unlike with Activities, your application object is not killed and restarted for configuration changes. Override this handler if it is necessary to handle configuration changes at an application level.

Android Application components

Android applications consist of loosely coupled components, bound using a project manifest that describes each component and how they interact.

There are six components that provide the building blocks for your applications:

- Activities: Your application’s presentation layer. Every screen in your application will be an extension of the Activity class. Activities use Views to form graphical user interfaces that display information and respond to user actions. In terms of desktop development, an Activity is equivalent to a Form.
 
-Services: The invisible workers of your application. Service components run invisibly, updating your data sources and visible Activities and triggering Notifi cations. They’re used to perform regular processing that needs to continue even when your application’s Activities aren’t active or visible.

- Content Providers: A shareable data store. Content Providers are used to manage and share application databases. Content Providers are the preferred way of sharing data across application boundaries. This means that you can confi gure your own Content Providers to permit access from other applications and use Content Providers exposed by others to access their stored data. Android devices include several native Content Providers that expose useful databases like contact information.

- Intents: A simple message-passing framework. Using Intents, you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.

- Broadcast Receivers: Intent broadcast consumers. By creating and registering a Broadcast Receiver, your application can listen for broadcast Intents that match specifi c fi lter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them ideal for event-driven applications.

- Notifications: A user notifi cation framework. Notifi cations let you signal users without stealing focus or interrupting their current Activities. They’re the preferred technique for getting a user’s attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you by fl ashing lights, making sounds, displaying icons, or showing dialog messages. You can trigger these same events from your own applications using Notifications.

By decoupling the dependencies between application components, you can share and interchange
individual pieces, such as Content Providers or Services, with other applications — both your own and
those of third parties.

Hardware-Imposed Design Restrictions

Compared to desktop or notebook computers, mobile devices have relatively:
- Low processing power
- Limited RAM
- Limited permanent storage capacity
- Small screens with low resolution
- Higher costs associated with data transfer
- Slower data transfer rates with higher latency
- Less reliable data connections
- Limited battery life

It’s important to keep these restrictions in mind when creating new applications.

Types of Android Applications

Most of the applications you create in Android will fall into one of the following categories:

- Foreground Activity: An application that’s only useful when it’s in the foreground and is effectively suspended when it’s not visible. Games and map mashups are common examples.

- Background Service: An application with limited interaction that, apart from when being configured, spends most of its lifetime hidden. Examples of this include call screening applications or SMS auto-responders.

- Intermittent Activity: Expects some interactivity but does most of its work in the background. Often these applications will be set up and then run silently, notifying users when appropriate. A common example would be a media player.

Complex applications are difficult to put into a single category and can include elements of all three. When creating your application, you need to consider how it’s likely to be used and then design it accordingly.

The ADT Plug-in

The ADT plug-in for Eclipse simplifies your Android development by integrating the developer tools, including the emulator and .class-to-.dex converter, directly into the IDE. While you don’t have to use the ADT plug-in, it does make creating, testing, and debugging your applications faster and easier.

The ADT plug-in integrates the following into Eclipse:
-An Android Project Wizard that simplifies creating new projects and includes a basic application template.
-Forms-based manifest, layout, and resource editors to help create, edit, and validate your XML resources.
-Automated building of Android projects, conversion to Android executables (.dex), packaging to package fi les (.apk), and installation of packages onto Dalvik virtual machines.
- The Android Emulator, including control of the emulator’s appearance, network connection settings, and the ability to simulate incoming calls and SMS messages.
 - The Dalvik Debug Monitoring Service (DDMS), which includes port forwarding; stack, heap, and thread viewing; process details; and screen capture facilities.
- Access to the device or emulator’s filesystem, allowing you to navigate the folder tree and transfer files
- Runtime debugging, so you can set breakpoints and view call stacks
- All Android/Dalvik log and console outputs

If you’re using the ADT plug-in, running or debugging your application:
- Compiles the current project and converts it to an Android executable (.dex).
- Packages the executable and external resources into an Android package (.apk).
- Starts the emulator (if it’s not already running).
- Installs your application onto the emulator.
- Starts your application.

If you’re debugging, the Eclipse debugger will then be attached, allowing you to set breakpoints and debug your code.

ADT Tools from DDMS perspective:
-The Android Emulator: An implementation of the Android virtual machine designed to run on your development computer. You can use the emulator to test and debug your android applications.
- Dalvik Debug Monitoring Service (DDMS): Use the DDMS perspective to monitor and control the Dalvik virtual machines on which you’re debugging your applications.
- Android Asset Packaging Tool (AAPT): Constructs the distributable Android package files (.apk).
- Android Debug Bridge (ADB): The ADB is a client-server application that provides a link to a running emulator. It lets you copy files, install compiled application packages (.apk), and run shell commands.

-SQLite3: A database tool that you can use to access the SQLite database fi les created and used by Android.
-Traceview: Graphical analysis tool for viewing the trace logs from your Android application
-MkSDCard: Creates an SDCard disk image that can be used by the emulator to simulate an external storage card.
 dx Converts Java .class bytecode into Android .dex bytecode.
- activityCreator: Script that builds Ant build fi les that you can then use to compile your Android applications without the ADT plug-in.

The Android Application Architecture

Android’s architecture encourages the concept of component reuse, allowing you to publish and share activities, services, and data with other applications with access managed by the security restrictions you put in place.

The same mechanism that lets you produce a replacement contact manager or phone dialer can let you expose your application components to let other developers create new UI front ends and functionality extensions, or otherwise build on them.

The following application services are the architectural cornerstones of all Android applications, providing the framework you’ll be using for your own software:

- Activity Manager: Controls the life cycle of your activities, including management of the activity stack.

-Views Are used to construct the user interfaces for your activities.

- Notification Manager: Provides a consistent and non-intrusive mechanism for signaling your users.

- Content Providers: Lets your applications share data between applications.

- Resource Manager: Supports non-code resources like strings and graphics to be externalized.

The Android Software Stack

The Android software stack is composed of the elements shown in the figure . Put simply, a Linux kernel and a collection of C/C++ libraries are exposed through an application framework that provides services for, and management of, the run time and applications.

Linux Kernel: Core services (including hardware drivers, process and memory management, security, network, and power management) are handled by a Linux 2.6 kernel. The kernel also provides an abstraction layer between the hardware and the remainder of the stack.

Libraries: Running on top of the kernel, Android includes various C/C++ core libraries such
as libc and SSL, as well as:
-❑ A media library for playback of audio and video media
-❑ A Surface manager to provide display management
-❑ Graphics libraries that include SGL and OpenGL for 2D and 3D graphics
-❑ SQLite for native database support
-❑ SSL and WebKit for integrated web browser and Internet security

Android Run Time: What makes an Android phone an Android phone rather than a mobile is the Linux implementation is the Android run time. Including the core libraries and the Dalvik virtual machine, the Android run time is the engine that powers your applications and, along with the libraries, forms the basis for the application framework.

-Core Libraries: While Android development is done in Java, Dalvik is not a Java VM.
The core Android libraries provide most of the functionality available in the core Java
libraries as well as the Android-specifi c libraries.

Dalvik Virtual Machine: Dalvik is a register-based virtual machine that’s been optimized to ensure that a device can run multiple instances efficiently. It relies on the Linux kernel for threading and low-level memory management.

 Application Framework: The application framework provides the classes used to create Android applications. It also provides a generic abstraction for hardware access and manages the user interface and application resources.

Application Layer: All applications, both native and third party, are built on the application layer using the same API libraries. The application layer runs within the Android run time using the classes and services made available from the application framework.