• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

What Is Android?

Android is a mobile operating system that is based on a modified version of Linux. It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the mobile space, Google purchased Android and took over its development work (as well as its development team).

Google wanted Android to be open and free; hence, most of the Android code was released under the open-source Apache License, which means that anyone who wants to use Android can do so by downloading the full Android source code. Moreover, vendors (typically hardware manufacturers) can add their own proprietary extensions to Android and customize Android to differentiate their products from others. This simple development model makes Android very attractive and has thus piqued the interest of many vendors. This has been especially true for companies affected by the phenomenon of Apple’s iPhone, a hugely successful product that revolutionized the smartphone industry. Such companies include Motorola and Sony Ericsson, which for many years have been developing their own mobile operating systems. When the iPhone was launched, many of these manufacturers had to scramble to find new ways of revitalizing their products. These manufacturers see Android as a solution — they will continue to design their own hardware and use Android as the operating system that powers it.

The main advantage of adopting Android is

  • It offers a unified approach to application development.
  • Developers need only develop for Android, and their applications should be able to run on numerous different devices, as long as the devices are powered using Android. In the world of smart phones, applications are the most important part of the success chain.
  • Device manufacturers therefore see Android as their best hope to challenge the onslaught of the iPhone, which already commands a large base of applications.

Android is a combination of three components:

  • A free, open-source operating system for mobile devices.
  • An open-source development platform for creating mobile applications.
  • Devices, particularly mobile phones, that run the Android operating system and the applications created for it.

Native Android Applications
Android phones will normally come with a suite of generic preinstalled applications that are part of the Android Open Source Project (AOSP), including, but not necessarily limited to:

  • An e-mail client
  • An SMS management application
  • A full PIM (personal information management) suite including a calendar and contacts list A WebKit-based web browser
  • A music player and picture gallery
  • A camera and video recording application A calculator
  • The home screen An alarm clock

In many cases Android devices will also ship with the following proprietary Google mobile applications:

  • The Android Market client for downloading third-party Android applications
  • A fully-featured mobile Google Maps application including StreetView, driving directions and turn-by-turn navigation, satellite view, and traffic conditions
    The Gmail mail client
  • The Google Talk instant-messaging client The YouTube video player.

Android SDK Features

  • The true appeal of Android as a development environment lies in the APIs it provides.
  • No licensing, distribution, or development fees or release approval processes Wi-Fi hardware access
  • GSM, EDGE, and 3G networks for telephony or data transfer, enabling you to make or receive calls or SMS messages, or to send and retrieve data across mobile networks
  • Comprehensive APIs for location-based services such as GPS
  • Full multimedia hardware control, including playback and recording with the camera and microphone
  • APIs for using sensor hardware, including accelerometers and the compass Libraries for using Bluetooth for peer-to-peer data transfer
  • IPC message passing Shared data stores
  • Background applications and processes
  • Home-screen Widgets, Live Folders, and LiveWallpaper
  • The ability to integrate application search results into the system search An integrated open-source HTML5WebKit-based browser
  • Full support for applications that integrate map controls as part of their user interface
  • Mobile-optimized hardware-accelerated graphics, including a path-based 2D graphics library and support for 3D graphics using OpenGL ES 2.0
  • Media libraries for playing and recording a variety of audio/video or still image formats Localization through a dynamic resource framework
  • An application framework that encourages reuse of application components and the replacement of native applications

Android Project Structure

The Android build system is organized around a specific directory tree structure for your Android project, much like any other Java project. The specifics, though, are fairly unique to Android and what it all does to prepare the actual application that will run on the device or emulator.
When you create a new Android project we get five key items in the project’s root directory:

• 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

• bin – which holds the application once it is compiled

• 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

• assets – which hold other static files you wish packaged with the application for deployment onto the device
We will also find that your project has a res/ directory tree. This holds “resources” – static files that are packaged along with your application, either in their original form or, occasionally, in a preprocessed form. Some of the subdirectories you will find or create under res/ include:

• res/drawable/ for images (PNG, JPEG, etc.)

• res/layout/ for XML-based UI layout specifications

• res/raw/ for general-purpose files

• res/values/ for strings, dimensions, and the like

• res/xml/ for other general-purpose XML files you wish to ship

The Dalvik Virtual Machine (DVM)

One of the key elements of Android is the Dalvik Virtual Machine. Rather than use a traditional Java virtual machine (VM) such as Java ME (Java Mobile Edition), Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device. The Dalvik VM uses the device’s underlying Linux kernel to handle low-level functionality including security, threading, and process and memory management. It’s also possible to write C/C++ applications that run directly on the underlying Linux OS.

All Android hardware and system service access is managed using Dalvik as a middle tier. By using a VM to host application execution, developers have an abstraction layer that ensures they never have to worry about a particular hardware implementation. The Dalvik VM executes Dalvik executable files, a format optimized to ensure minimal memory footprint. We create.dex executables by transforming Java language compiled classes using the tools supplied within the SDK.

Android Architecture

1

The Android OS is roughly divided into five sections in four main layers:

Linux kernel — This is the kernel on which Android is based. This layer contains all the lowlevel device drivers for the various hardware components of an Android device.

Libraries — These contain all the code that provides the main features of an Android OS. For example, the SQLite library provides database support so that an application can use it for data storage. The WebKit library provides functionalities for web browsing.
Android runtime — At the same layer as the libraries, the Android runtime provides a set of core libraries that enable developers to write Android apps using the Java programming language.

The Android runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine (Android applications are compiled into the Dalvik executables). Dalvik is a specialized virtual machine designed specifically for Android and optimized for battery-powered mobile devices with limited memory and CPU.

Application framework — Exposes the various capabilities of the Android OS to application developers so that they can make use of them in their applications.
Applications — At this top layer, you will find applications that ship with the Android device (such as Phone, Contacts, Browser, etc.), as well as applications that you download and install from the Android Market.

User Interface Components In Android

The following are the User Interface Components in Android.

Notifications :

What are Notifications? The name itself implies their functionality. They are a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information.

Notification on Android can be done in any of the following ways:

They are

  1. Toast Notification
  2. Status Bar Notification
  3. Dialog Boxes

 

Toast Notifications

A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user’s current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.

First, instantiate a Toast object with one of the makeText() methods. This method takes three parameters:

the application Context, the text message, and the duration for the toast. It returns a properly initialized oast object. You can display the toast notification with show(), as shown in the following example:

Context context = getApplicationContext();

CharSequence text = “Hello toast!”;

int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);

toast.show();

This example demonstrates everything you need for most toast notifications. You should rarely need anything else. You may, however, want to position the toast differently or even use your own layout instead of a simple text message. The following sections describe how you can do these things.

You can also chain your methods and avoid holding on to the Toast object, like this:

Toast.makeText(context, text, duration).show();

 

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

Status Bar Notification

This Notification on Android can be done in any of the following ways:

_ Status Bar Notification

_ Vibrate

_ Flash lights

_ Play a sound

From the Notification, you can allow the user to launch a new activity as well. Now we will look at status bar notification as this can be easily tested on the emulator. To create a status bar notification, you will need to use two classes: Notification and NotificationManager.

_ Notification – defines the properties of the status bar notification like the icon to display,

the test to display when the notification first appears on the status bar and the time to display.

_ NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.

Once you procure this handle, you invoke the notify() method on it by passing the notification object created.

So far, you have all the information to display on the status bar. However, when the user clicks the notification icon on the status bar, what detailed information should you show the user? This is yet to be created. This is done by calling the method setLatestEventInfo() on the notification object.

 

Creating a Notification

A Notification object defines the details of the notification message that is displayed in the status bar and notifications window, and any other alert settings, such as sounds and blinking lights.

A status bar notification requires all of the following:

  • An icon for the status bar
  • A title and message, unless you define a custom notification layout
  • A PendingIntent, to be fired when the notification is selected

Optional settings for the status bar notification include:

  • A ticker-text message for the status bar
  • An alert sound
  • A vibrate setting
  • A flashing LED setting

 

Updating the notification

You can update the information in your status bar notification as events continue to occur in your application. For example, when a new SMS text message arrives before previous messages have been read, the Messaging application updates the existing notification to display the total number of new messages received. This practice of updating an existing notification is much better than adding new notifications, because it avoids clutter in the notifications window.

Because each notification is uniquely identified by the NotificationManager with an integer ID, you can revise the notification by calling setLatestEventInfo() with new values, change some field values of the notification, and then call notify() again.

You can revise each property with the object member fields (except for the Context and the notification title and text). You should always revise the text message when you update the notification by calling setLatestEventInfo() with new values for contentTitle and contentText. Then call notify() to update the notification. (Of course, if you’ve created a custom notification layout, then updating these title and text values has no effect.)

 

Adding a sound

You can alert the user with the default notification sound (which is defined by the user) or with a sound specified by your application.

To use the user’s default sound, add “DEFAULT_SOUND” to the defaults field:

notification.defaults |= Notification.DEFAULT_SOUND;

 

Adding vibration

You can alert the user with the the default vibration pattern or with a vibration pattern defined by your application.

To use the default pattern, add DEFAULT_VIBRATE to the defaults field:

notification.defaults |= Notification.DEFAULT_VIBRATE;

 

Adding flashing lights

To alert the user by flashing LED lights, you can implement the default light pattern (if available), or define your own color and pattern for the lights.

To use the default light setting, add DEFAULT_LIGHTS to the defaults field:

notification.defaults |= Notification.DEFAULT_LIGHTS;

 

Dialog Boxes :

A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).

The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the following subclasses:

AlertDialog

A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type. See Creating an AlertDialog below.

ProgressDialog

A dialog that displays a progress wheel or progress bar. Because it’s an extension of the AlertDialog, it also supports buttons. See Creating a ProgressDialog below.

DatePickerDialog

A dialog that allows the user to select a date. See the Hello DatePicker tutorial.

TimePickerDialog

A dialog that allows the user to select a time. See the Hello TimePicker tutorial. If you would like to customize your own dialog, you can extend the base Dialog object or any of the subclasses listed above and define a new layout. See the section on Creating a Custom Dialog below.

 

Showing a Dialog

A dialog is always created and displayed as a part of an Activity. You should normally create dialogs from within your Activity’s onCreateDialog(int) callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the “owner” of each dialog. As such, each dialog inherits certain properties from the Activity. For example, when a dialog is open, the Menu key reveals the options menu defined for the Activity and the volume keys modify the audio stream used by the Activity.

Note: If you decide to create a dialog outside of the onCreateDialog() method, it will not be attached to an Activity. You can, however, attach it to an Activity with setOwnerActivity(Activity). When you want to show a dialog, call showDialog(int) and pass it an integer that uniquely identifies the dialog that you want to display.

When a dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity, which is where you should instantiate the Dialog. This callback method is passed the same ID that you passed to showDialog(int). After you create the Dialog, return the object at the end of the method. The best way to define the onCreateDialog(int) and onPrepareDialog(int, Dialog) callback methods is with a switch statement that checks the id parameter that’s passed into the method. Each case should check for a unique dialog ID and then create and define the respective Dialog. For example, imagine a game that uses two different dialogs: one to indicate that the game has paused and another to indicate that the game is over. First, define an integer ID for each dialog:

static final int DIALOG_PAUSED_ID = 0;

static final int DIALOG_GAMEOVER_ID = 1;

Then, define the onCreateDialog(int) callback with a switch case for each ID:

protected Dialog onCreateDialog(int id) {

Dialog dialog;

switch(id) {

case DIALOG_PAUSED_ID:

// do the work to define the pause Dialog

break;

case DIALOG_GAMEOVER_ID:

// do the work to define the game over Dialog

break;

default:

dialog = null;

}

return dialog;

}

Note: In this example, there’s no code inside the case statements because the procedure for defining your Dialog is outside the scope of this section. See the section below about Creating an AlertDialog, offers code suitable for this example.

When it’s time to show one of the dialogs, call showDialog(int) with the ID of a dialog:

showDialog(DIALOG_PAUSED_ID);

 

Dismissing a Dialog

When you’re ready to close your dialog, you can dismiss it by calling dismiss() on the Dialog object. If necessary, you can also call dismissDialog(int) from the Activity, which effectively calls dismiss() on the Dialog for you.

If you are using onCreateDialog(int) to manage the state of your dialogs (as discussed in the previous section), then every time your dialog is dismissed, the state of the Dialog object is retained by the Activity. If you decide that you will no longer need this object or it’s important that the state is cleared, then you should call removeDialog(int). This will remove any internal references to the object and if the dialog is showing, it will dismiss it.

 

Creating an AlertDialog

An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:

  • A title
  • A text message
  • One, two, or three buttons
  • A list of selectable items (with optional checkboxes or radio buttons)

To create an AlertDialog, use the AlertDialog.Builder subclass. Get a Builder with AlertDialog.Builder(Context) and then use the class’s public methods to define all of the AlertDialog properties. After you’re done with the Builder, retrieve the AlertDialog object with create().

The following topics show how to define various properties of the AlertDialog using the AlertDialog.Builder class. If you use any of the following sample code inside your onCreateDialog() callback method, you can return the resulting Dialog object to display the dialog.

 

Adding buttons

21

To create an AlertDialog with side-by-side buttons like the one shown in the screenshot to the right, use

the set…Button() methods:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage(“Are you sure you want to exit?”)

.setCancelable(false)

.setPositiveButton(“Yes”, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

MyActivity.this.finish();

}

})

.setNegativeButton(“No”, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

dialog.cancel();

}

});

AlertDialog alert = builder.create();

First, add a message for the dialog with setMessage(CharSequence). Then, begin method-chaining and set the dialog to be not cancelable (so the user cannot close the dialog with the back button) with setCancelable(boolean). For each button, use one of the set…Button() methods, such as setPositiveButton(), that accepts the name for the button and a DialogInterface.OnClickListener that defines the action to take when the user selects the button.

Note: You can only add one of each button type to the AlertDialog. That is, you cannot have more than one “positive” button. This limits the number of possible buttons to three: positive, neutral, and negative. These names are technically irrelevant to the actual functionality of your buttons, but should help you keep track of which one does what.

 

Adding a list

To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems()

method:

final CharSequence[] items = {“Red”, “Green”, “Blue”};

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle(“Pick a color”);

builder.setItems(items, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();

}

});

AlertDialog alert = builder.create();

First, add a title to the dialog with setTitle(CharSequence). Then, add a list of selectable items with setItems(), which accepts the array of items to display and a DialogInterface.OnClickListener that defines the action to take when the user selects an item.

 

Adding checkboxes and radio buttons

To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoiceItems() methods, respectively. If you create one of these selectable lists in the onCreateDialog() callback method, Android manages the state of the list for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is lost. 

Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout the activity lifecycle. To permanently save the selections, even when the Activity process is completely shutdown, you need to save the settings with one of the Data Storage techniques.

To create an AlertDialog with a list of single-choice items like the one shown to the right, use the same code from the previous example, but replace the setItems() method with setSingleChoiceItems():

final CharSequence[] items = {“Red”, “Green”, “Blue”};

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle(“Pick a color”);

builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();

}

});

AlertDialog alert = builder.create();

The second parameter in the setSingleChoiceItems() method is an integer value for the checkedItem, which indicates the zero-based list position of the default selected item. Use “-1” to indicate that no item should be selected by default.

 

ProgressDialog :

22

A ProgressDialog is an extension of the AlertDialog class that can display a progress animation in the form of a spinning wheel, for a task with progress that’s undefined, or a progress bar, for a task that has a defined progression. The dialog can also provide buttons, such as one to cancel a download.

Opening a progress dialog can be as simple as calling ProgressDialog.show(). For example, the progress dialog shown to the right can be easily achieved without managing the dialog through the onCreateDialog(int) callback, as shown here:

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, “”,

“Loading. Please wait…”, true);

The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progress is indeterminate (this is only relevant when creating a progress bar, which is discussed in the next section).

The default style of a progress dialog is the spinning wheel. If you want to create a progress bar that shows the loading progress with granularity, some more code is required, as discussed in the next section.

 

Showing a progress bar :

To show the progression with an animated progress bar:

  1. Initialize the ProgressDialog with the class constructor, ProgressDialog(Context).
  2. Set the progress style to “STYLE_HORIZONTAL” with setProgressStyle(int) and set any other properties, such as the message.
  3. When you’re ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback.
  4. You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far. For example, your setup might look like this:

ProgressDialog progressDialog;

progressDialog = new ProgressDialog(mContext);

progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

progressDialog.setMessage(“Loading…”);

progressDialog.setCancelable(false);

The setup is simple. Most of the code needed to create a progress dialog is actually involved in the process that updates it. You might find that it’s necessary to create a second thread in your application for this work and then report the progress back to the Activity’s UI thread with a Handler object. If you’re not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread to increment a progress dialog managed by the Activity.

 

DatePickerDialog:

To provide a widget for selecting a date, use the DatePicker widget, which allows the user to select the

month, day, and year, in a familiar interface.

 

Main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:orientation=”vertical”>

<TextView android:id=”@+id/dateDisplay”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=””/>

<Button android:id=”@+id/pickDate”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”Change the date”/>

</LinearLayout>

 

HelloDatePicker.java

Public class HelloDatePicker extends Activity

{

private TextView mDateDisplay;

private Button mPickDate;

private int mYear;

private int mMonth;

private int mDay;

static final int DATE_DIALOG_ID = 0;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// capture our View elements

mDateDisplay = (TextView) findViewById(R.id.dateDisplay);

mPickDate = (Button) findViewById(R.id.pickDate);

// add a click listener to the button

mPickDate.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

showDialog(DATE_DIALOG_ID);

}

});

// get the current date

final Calendar c = Calendar.getInstance();

mYear = c.get(Calendar.YEAR);

mMonth = c.get(Calendar.MONTH);

mDay = c.get(Calendar.DAY_OF_MONTH);

// display the current date (this method is below)

updateDisplay();

}

// updates the date in the TextView

private void updateDisplay() {

mDateDisplay.setText(

new StringBuilder()

// Month is 0 based so add 1

.append(mMonth + 1).append(“-“)

.append(mDay).append(“-“)

.append(mYear).append(” “));

}

// the callback received when the user “sets” the date in the dialog

private DatePickerDialog.OnDateSetListener mDateSetListener =

new DatePickerDialog.OnDateSetListener() {

public void onDateSet(DatePicker view, int year,

int monthOfYear, int dayOfMonth) {

mYear = year;

mMonth = monthOfYear;

mDay = dayOfMonth;

updateDisplay();

}

};

@Override

protected Dialog onCreateDialog(int id) {

switch (id) {

case DATE_DIALOG_ID:

return new DatePickerDialog(this,

mDateSetListener,

mYear, mMonth, mDay);

}

return null;

}

Time Picker Dialog:

To provide a widget for selecting a time, use the TimePicker widget, which allows the user to select the

hour and minute in a familiar interface.

 

main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:orientation=”vertical”>

<TextView android:id=”@+id/timeDisplay”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=””/>

<Button android:id=”@+id/pickTime”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”Change the time”/>

</LinearLayout>

 

HelloTimePicker.java:

Public class HelloTimePicker extends Activity

{

private TextView mTimeDisplay;

private Button mPickTime;

private int mHour;

private int mMinute;

static final int TIME_DIALOG_ID = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// capture our View elements

mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);

mPickTime = (Button) findViewById(R.id.pickTime);

// add a click listener to the button

mPickTime.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

showDialog(TIME_DIALOG_ID);

}

});

// get the current time

final Calendar c = Calendar.getInstance();

mHour = c.get(Calendar.HOUR_OF_DAY);

mMinute = c.get(Calendar.MINUTE);

// display the current date

updateDisplay();

}

// updates the time we display in the TextView

private void updateDisplay() {

mTimeDisplay.setText(

new StringBuilder()

.append(pad(mHour)).append(“:”)

.append(pad(mMinute)));

}

private static String pad(int c) {

if (c >= 10)

return String.valueOf(c);

else

return “0” + String.valueOf(c);

}

// the callback received when the user “sets” the time in the dialog

private TimePickerDialog.OnTimeSetListener mTimeSetListener =

new TimePickerDialog.OnTimeSetListener() {

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

mHour = hourOfDay;

mMinute = minute;

updateDisplay();

}

};

@Override

protected Dialog onCreateDialog(int id) {

switch (id) {

case TIME_DIALOG_ID:

return new TimePickerDialog(this,

mTimeSetListener, mHour, mMinute, false);

}

return null;

}

AutoCompleteTextView:

An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with. The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key.The list of suggestions is obtained from a data adapter and appears only after a given number of characters defined by the threshold.

Example:

 

Main.java:

public class main extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

AutoCompleteTextView textView = (AutoCompleteTextView)

findViewById(R.id.autocomplete_country);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

R.layout.list_item, DISTRICTS);

textView.setAdapter(adapter);

}

static final String[] DISTRICTS = new String[] {

“SRIKAKULAM”,”VIJAYAGANAGARAM”,”VISHAKAPATNAM”,”EASTGODAVARI”,”WESTG

ODAVARI”,”KRISHNA”

};

}

 

Main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”horizontal”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:padding=”5dp”>

<TextView

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”Country” />

<AutoCompleteTextView android:id=”@+id/autocomplete_country”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:layout_marginLeft=”5dp”/>

</LinearLayout>

 

ListItem.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<TextView xmlns:android=”http://schemas.android.com/apk/res/android”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:padding=”10dp”

android:textSize=”16sp”

android:textColor=”#000″

>

</TextView>

 

SPINNER:

Any good web designed knows how important the <select> element can be. In a touch screen environment, like Android, where users often don’t have a full keyboard, like many Android phones, the ability to simply select an item from a pre-determined list is absolutely vital. It’s easier for the user to select what they want – rather than have to type it, it protects your databases from junk data and typos by limiting choices to pre-defined, pre-screened responses. The Android OS has a very robust, user friendly and – relatively – programmer friendly way to handle this: the Android Spinner.

Spinners are simple to use, easy to program and just downright good-looking. However, there are several different ways to populate the list of items in an Android Spinner, and – as of the writing of this article – the Android Developer’s Website (developer.android.com) only focuses on one of those methods. This article will break down both of the most popular ways to do populate an Android Spinner: with an array contained in your strings.xml file, and from a database query. Then it will also demonstrate how to manually insert items into a spinner array using code. For ease of navigation, I’m placing each of those on a separate page and including links to them so you can go to the page that best fits your needs as a developer.

  • Populate Android Spinner from string array resource
  • Populate Android Spinner from database query (using a cursor)
  • Populate Android Spinner manually with Java code

 

main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”vertical”

android:padding=”10dip”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”>

<TextView

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:layout_marginTop=”10dip”

android:text=”@string/planet_prompt”

/>

<Spinner

android:id=”@+id/spinner”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:prompt=”@string/planet_prompt”

</LinearLayout>

 

strings.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<resources>

<string name=”planet_prompt”>Choose a planet</string>

<string-array name=”planets_array”>

<item>Mercury</item>

<item>Venus</item>

<item>Earth</item>

<item>Mars</item>

<item>Jupiter</item>

<item>Saturn</item>

<item>Uranus</item>

<item>Neptune</item>

</string-array>

</resources>

  

SpinnerDemo.java:

Public class SpinnerDemo extends Activity

{

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Spinner spinner = (Spinner) findViewById(R.id.spinner);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(

this, R.array.planets_array,android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

}

public class MyOnItemSelectedListener implements OnItemSelectedListener {

public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {

Toast.makeText(parent.getContext(), “The planet is ” +

parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

}

public void onNothingSelected(AdapterView parent) {

// Do nothing.

}

}

spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

}

  

ListView:

responsible for providing the data model for the list and for converting the data into the fields of the list. Android has two standard adapters, ArrayAdapter and CursorAdapter . “ArrayAdapter” can handle data based on Arrays or Lists while “SimpleCursorAdapter” handle database related data. You can develop your own Adapter by extending these classes or the BaseAdapter class.

The following description will focus on ArrayAdapter and how to develop your own adapter. It will also give a small example for “CursorAdapter”.

 ListActivity

You can directly use the “ListView” in your layout as any other UI component. In case your Activity is primary showing a list you can extend the activity “ListActivity” which simplifies the handling of a “ListView”. “ListActivity” extends “Activity” and provides simplified handling of lists. For example you have a predefine method if someone clicks on a list element. “ListActivity” contains a “ListAdapter” which is responsible for managing the data. This adapter must be set in the onCreate() method of your Activity via the method setListAdapter(). If the user select in the list a list entry the method onListItemClick() will be called. This method allows to access the selected element.

Android provides already some default layouts which you can use in your Adapter, e.g. “android.R.layout.simple_list_item1”. In case you don’t want to use one of the pre-defined layouts your own layout must have an element with the id “@android:id/list” which is the ListView. You can also use a view with the id “@android:id/empty”. This view is displayed if the list is empty. For example you could display here an error message.

 

ListViews and performance

Displaying a large dataset must be efficiently implemented on a mobile device. Therefore the ListView only creates views (widget) if needed and attach them to the view hierarchy. The default Adapter implementation for a ListView will recycle views, e.g. if a row is not displayed anymore it will be recycled and only its content will change. If you implement your own adapter for a view you also should do this to avoid performance problems. This technique will be demonstrated in this tutorial.

 

ListActivity with ArrayAdapter and Android standard layout

Create a new Android project “de.vogella.android.listactivity” with the activity “MyList”. You do not need to change the default layout “main.xml”. Create the following activity.

package sk.saitech.android.receiver;

import android.app.ListActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.Toast;

public class MyList extends ListActivity {

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

// Create an array of Strings, that will be put to our ListActivity static final

String[] DISTRICTS = new String[] {

“SRIKAKULAM”,”VIJAYAGANAGARAM”,”VISHAKAPATNAM”,”EASTGODAVARI”,”WESTG

ODAVARI”,”KRISHNA”

};

// Create an ArrayAdapter, that will actually make the Strings above

// appear in the ListView

this.setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, DISTRICTS));

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

super.onListItemClick(l, v, position, id);

// Get the item that was clicked

Object o = this.getListAdapter().getItem(position);

String keyword = o.toString();

Toast.makeText(this, “You selected: ” + keyword, Toast.LENGTH_LONG)

.show();

}

}

 

ListActivity with own layout

You can also define your own layout for the rows and assign this layout to your row adapter. We will add a graphic to each list entry. Create the following layout file “rowlayout.xml” in the res/layout folder of your project

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:layout_width=”wrap_content” android:layout_height=”wrap_content”>

<ImageView android:id=”@+id/icon”

android:layout_height=”wrap_content”

android:src=”@drawable/icon” android:layout_width=”22px”

android:layout_marginTop=”4px” android:layout_marginRight=”4px”

android:layout_marginLeft=”4px”>

</ImageView>

<TextView android:text=”@+id/TextView01″ android:layout_width=”wrap_content”

android:layout_height=”wrap_content” android:id=”@+id/label”

android:textSize=”30px”></TextView>

</LinearLayout>

Change your activity “MyList” to the following. This is almost the same coding as in the previous example, the only difference is that we are using our own layout in the ArrayAdapter and telling the adapter which UI element should contains the text.

package sk.saitech.android.receiver;

import android.app.ListActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.Toast;

public class MyList extends ListActivity {

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

// Create an array of Strings, that will be put to our ListActivity

static final String[] DISTRICTS = new String[] {

“SRIKAKULAM”,”VIJAYAGANAGARAM”,”VISHAKAPATNAM”,”EASTGODAVARI”,”WESTG

ODAVARI”,”KRISHNA”

};

// contains the label

this.setListAdapter(new ArrayAdapter<String>(this, R.layout.rowlayout,

R.id.label, DISTRICTS));

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

super.onListItemClick(l, v, position, id);

// Get the item that was clicked

Object o = this.getListAdapter().getItem(position);

String keyword = o.toString();

Toast.makeText(this, “You selected: ” + keyword, Toast.LENGTH_LONG)

.show();

}

}

 

GridView:

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.

Main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<GridView xmlns:android=”http://schemas.android.com/apk/res/android”

android:id=”@+id/gridview”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:columnWidth=”90dp”

android:numColumns=”auto_fit”

android:verticalSpacing=”10dp”

android:horizontalSpacing=”10dp”

android:stretchMode=”columnWidth”

android:gravity=”center”

/>

 

Hellogrid.java:

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

GridView gridview = (GridView) findViewById(R.id.gridview);

gridview.setAdapter(new ImageAdapter(this));

gridview.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

Toast.makeText(HelloGridView.this, “” + position, Toast.LENGTH_SHORT).show();

}

});

}

public class ImageAdapter extends BaseAdapter {

private Context mContext;

public ImageAdapter(Context c) {

mContext = c;

}

public int getCount() {

return mThumbIds.length;

}

public Object getItem(int position) {

return null;

}

public long getItemId(int position) {

return 0;

}

// create a new ImageView for each item referenced by the Adapter

public View getView(int position, View convertView, ViewGroup parent) {

ImageView imageView;

if (convertView == null) { // if it’s not recycled, initialize some attributes

imageView = new ImageView(mContext);

imageView.setLayoutParams(new GridView.LayoutParams(85, 85));

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

imageView.setPadding(8, 8, 8, 8);

} else {

imageView = (ImageView) convertView;

}

imageView.setImageResource(mThumbIds[position]);

return imageView;

}

// references to our images

private Integer[] mThumbIds = {

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7,

R.drawable.sample_0, R.drawable.sample_1,

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7,

R.drawable.sample_0, R.drawable.sample_1,

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7

};

}

 

Gallery:

Gallery is a layout widget used to display items in a horizontally scrolling list and positions the current selection at the center of the view.

Example:

Main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout android:id=”@+id/LinearLayout01″

android:layout_width=”fill_parent” android:layout_height=”fill_parent”

xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”vertical”>

<Gallery xmlns:android=”http://schemas.android.com/apk/res/android”

android:id=”@+id/examplegallery” android:layout_width=”fill_parent”

android:layout_height=”wrap_content” />

<ImageView android:id=”@+id/ImageView01″

android:layout_width=”wrap_content” android:layout_height=”wrap_content”/>

</LinearLayout>

 

GalleryExample.java

public class GalleryExample extends Activity {

private Gallery gallery;

private ImageView imgView;

private Integer[] Imgid = {

R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5,

R.drawable.a_6, R.drawable.a_7

}; @Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

imgView = (ImageView)findViewById(R.id.ImageView01);

imgView.setImageResource(Imgid[0]);

gallery = (Gallery) findViewById(R.id.examplegallery);

gallery.setAdapter(new AddImgAdp(this));

gallery.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView parent, View v, int position, long id) {

imgView.setImageResource(Imgid[position]);

} }); }

public class AddImgAdp extends BaseAdapter {

int GalItemBg;

private Context cont;

public AddImgAdp(Context c) {

cont = c;

TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);

GalItemBg =

typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);

typArray.recycle(); }

public int getCount() {

return Imgid.length; }

public Object getItem(int position) {

return position; }

public long getItemId(int position) {

return position;

} public View getView(int position, View convertView, ViewGroup parent) {

ImageView imgView = new ImageView(cont);

imgView.setImageResource(Imgid[position]);

imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));

imgView.setScaleType(ImageView.ScaleType.FIT_XY);

imgView.setBackgroundResource(GalItemBg);

return imgView;

} }}

 

Other Important Views In ANDROID :

Edit Text

In this section, you will create a text field for user input, using the EditText widget. Once text has been entered into the field, the “Enter” key will display the text in a toast message.

  1. Open the res/layout/main.xml file and add the EditText element (inside the LinearLayout):

<EditText

android:id=”@+id/edittext”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”/>

  1. To do something with the text that the user types, add the following code to the end of the

onCreate() method:

final EditText edittext = (EditText) findViewById(R.id.edittext);

edittext.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {

// If the event is a key-down event on the “enter” button

if ((event.getAction() == KeyEvent.ACTION_DOWN) &&

(keyCode == KeyEvent.KEYCODE_ENTER)) {

// Perform action on key press

Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();

return true;

}

return false;

}

});

The action to be made when a key is pressed while the widget has focus. In this case, the methodis defined to listen for the Enter key (when pressed down), then pop up a Toast message with the text that has been entered. The onKey(View, int, KeyEvent) method should always return true if the event has been handled, so that the event doesn’t bubble-up (which would result in a carriage return in the text field).

  1. Run the application.

 Checkbox

In this section, you will create a checkbox for selecting items, using the CheckBox widget. When the checkbox is pressed, a toast message will indicate the current state of the checkbox.

  1. Open the res/layout/main.xml file and add the CheckBox element (inside the LinearLayout):

<CheckBox android:id=”@+id/checkbox”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”check it out” />

  1. To do something when the state is changed, add the following code to the end of the onCreate()

method:

final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);

checkbox.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// Perform action on clicks, depending on whether it’s now checked

if (((CheckBox) v).isChecked()) {

Toast.makeText(HelloFormStuff.this, “Selected”, Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(HelloFormStuff.this, “Not selected”, Toast.LENGTH_SHORT).show();

}

}

});

This captures the CheckBox element from the layout, then adds an View.OnClickListener. The View.OnClickListener must implement the onClick(View) callback method, which defines the action to be made when the checkbox is clicked. When clicked, isChecked() is called to check the new state of the check box. If it has been checked, then a Toast displays the message “Selected”, otherwise it displays “Not selected”. Note that the View object that is passed in the onClick(View) callback must be cast to a CheckBox because the isChecked() method is not defined by the parent View class. The CheckBox handles its own state changes, so you only need to query the current state.

  1. Run it. 

Tip: If you need to change the state yourself (such as when loading a saved CheckBoxPreference), use the setChecked(boolean) or toggle() method.

 

Radio Buttons

In this section, you will create two mutually-exclusive radio buttons (enabling one disables the other), using the RadioGroup and RadioButton widgets. When either radio button is pressed, a toast message will be displayed.

  1. Open the res/layout/main.xml file and add two RadioButtons, nested in a RadioGroup (inside the LinearLayout):

<RadioGroup

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:orientation=”vertical”>

<RadioButton android:id=”@+id/radio_red”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”Red” />

<RadioButton android:id=”@+id/radio_blue”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”Blue” />

</RadioGroup>

It’s important that the RadioButtons are grouped together by the RadioGroup element so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When one RadioButton within a group is selected, all others are automatically deselected.

  1. To do something when each RadioButton is selected, you need an View.OnClickListener. In this case, you want the listener to be re-usable, so add the following code to create a new member in

the HelloFormStuff Activity:

private OnClickListener radio_listener = new OnClickListener() {

public void onClick(View v) {

// Perform action on clicks

RadioButton rb = (RadioButton) v;

Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();

}

};

First, the View that is passed to the onClick(View) method is cast into a RadioButton. Then a Toast message displays the selected radio button’s text.

  1. Now, at the bottom of the onCreate() method, add the following:

final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red);

final RadioButton radio_blue = (RadioButton) findViewById(R.id.radio_blue);

radio_red.setOnClickListener(radio_listener);

radio_blue.setOnClickListener(radio_listener);

This captures each of the RadioButtons from the layout and adds the newly-created View.OnClickListener to each.

  1. Run the application.

 Tip: If you need to change the state yourself (such as when loading a saved CheckBoxPreference), use the setChecked(boolean) or toggle() method.

 

Toggle Button

In this section, you’ll create a button used specifically for toggling between two states, using the ToggleButton widget. This widget is an excellent alternative to radio buttons if you have two simple states that are mutually exclusive (“on” and “off”, for example).

  1. Open the res/layout/main.xml file and add the ToggleButton element (inside the LinearLayout):

<ToggleButton android:id=”@+id/togglebutton”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textOn=”Vibrate on”

android:textOff=”Vibrate off”/>

The attributes android:textOn and android:textOff specify the text for the button when the button has been toggled on or off. The default values are “ON” and “OFF”.

  1. To do something when the state is changed, add the following code to the end of the onCreate() method:

final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);

togglebutton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// Perform action on clicks

if (togglebutton.isChecked()) {

Toast.makeText(HelloFormStuff.this, “Checked”, Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(HelloFormStuff.this, “Not checked”, Toast.LENGTH_SHORT).show();

}

}

});

This captures the ToggleButton element from the layout, then adds an View.OnClickListener. The View.OnClickListener must implement the onClick(View) callback method, which defines the action to perform when the button is clicked. In this example, the callback method checks the new state of the button, then shows a Toast message that indicates the current state.

Notice that the ToggleButton handles its own state change between checked and unchecked, so you just ask which it is.

  1. Run the application.

 Tip: If you need to change the state yourself (such as when loading a saved CheckBoxPreference), use

  1. the setChecked(boolean) or toggle() method.

 

Rating Bar

In this section, you’ll create a widget that allows the user to provide a rating, with the RatingBar widget.

  1. Open the res/layout/main.xml file and add the RatingBar element (inside the LinearLayout):

<RatingBar android:id=”@+id/ratingbar”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:numStars=”5″

android:stepSize=”1.0″/>

The android:numStars attribute defines how many stars to display for the rating bar. The android:stepSize attribute defines the granularity for each star (for example, a value of 0.5 would allow half-star ratings).

  1. To do something when a new rating has been set, add the following code to the end of the onCreate() method:

final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);

ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {

Toast.makeText(HelloFormStuff.this, “New Rating: ” + rating,

Toast.LENGTH_SHORT).show();

}

});

This captures the RatingBar widget from the layout with findViewById(int) and then sets an RatingBar.OnRatingBarChangeListener. The onRatingChanged() callback method then defines the action to perform when the user sets a rating. In this case, a simple Toast message displays the new rating.

  1. Run the application.

 

Services :

 

What is Service?

A service is a component which runs in the background, without interacting with the user. The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In your activity you access services via the method getSystemService(). Own Services must be declared via the “AndroidManifest.xml”. They run the main thread of their hosting process. Therefore you should run performance intensive tasks in the background .

 

Own Services:

You can declare your own service to perform long running operations without user interaction or to supply functionality to other applications. A activity can start a service via the startService() method and stop the service via the stopService() method. If the activity want to interact with the service it can use the bindService() method of the service. This requires an “ServiceConnection” object which allows to connect to the service and which return a IBinder object. This IBinder object can be used by the activity to communicate with the service.

Once a service is started its onCreate() method is called. Afterwards the onStartCommand() is called with the Intent data provided by the activity. startService also allows to provide a flag with determines the lifecycle behavior of the services. START_STICKY is used for services which are explicit started or stopped. Services started with START_NOT_STICKY will end automatically after the onStartCommand() method is done. A service is started within the main thread of the application therefore all long running tasks should be performed in the background .

A Services needs to be declared in the “AndroidManifest.xml” via a <service android:name=”yourclasss”> </service> and the implementing class must extend the class “Service” or one of its subclasses.

One common case is that the service and the activity are very closely related. In this case class just case the IBinder to the class the service provides. See Local Service Example for an example. Another example would be the usage of Remote Messenger Service. In this case activities can send messages to the service and receive messages as well if they register for them.

Broadcast Receiver:

A broadcast receiver is a class which extends “BroadcastReceiver” and which is registered as a receiver in an Android Application via the AndroidManifest.xml (or via code). This class will be able to receive intents via the sendBroadcast() method. “BroadCastReceiver” defines the method “onReceive()”. Only during this method your broadcast receiver object will be valid, afterwards the Android system will consider your object as no longer active. Therefore you cannot perform any asynchronous operation.

 

Pending Intent:

This tutorial will also use a PendingIntent. A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.

To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().

 Broadcast Receiver Example:

We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message. Create a new project “de.vogella.android.receiver.phone”. We do not need an activity. Create the following “AndroidManifest.xml”.

<?xml version=”1.0″ encoding=”utf-8″?>

<manifest xmlns:android=”http://schemas.android.com/apk/res/android”

package=”sk.saitech.android.receiver” android:versionCode=”1″

android:versionName=”1.0″>

<application android:icon=”@drawable/icon” android:label=”@string/app_name”>

<receiver android:name=”MyPhoneReceiver”>

<intent-filter>

<action android:name=”android.intent.action.PHONE_STATE”></action>

</intent-filter>

</receiver>

</application>

<uses-sdk android:minSdkVersion=”9″ />

<uses-permission android:name=”android.permission.READ_PHONE_STATE”></usespermission>

</manifest>

 

Create the following class “MyPhoneReceiver”.

package sk.saitech.android.receiver;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.TelephonyManager;

import android.util.Log;

public class MyPhoneReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

Bundle extras = intent.getExtras();

if (extras != null) {

String state = extras.getString(TelephonyManager.EXTRA_STATE);

Log.w(“DEBUG”, state);

if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {

String phoneNumber = extras

.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

Log.w(“DEBUG”, phoneNumber);

}

}

}

}

If you install your application and receive a call, e.g simulated by the DDMS perspective in Eclipse, then your receiver will be called and lot a message to the console.

 

Menus

Menus are an important part of an activity’s user interface, which provide users a familiar way to perform actions. Android offers a simple framework for you to add standard menus to your application. There are three types of application menus:

 Options Menu

The primary collection of menu items for an activity, which appears when the user touches the MENU button. When your application is running on Android 3.0 or later, you can provide quick access to select menu items by placing them directly in the Action Bar, as “action items.”

 Context Menu

A floating list of menu items that appears when the user touches and holds a view that’s registered to provide a context menu.

 Submenu

A floating list of menu items that appears when the user touches a menu item that contains a nested menu. This document shows you how to create each type of menu, using XML to define the content of the menu and callback methods in your activity to respond when the user selects an item.

 Creating a Menu Resource

Instead of instantiating a Menu in your application code, you should define a menu and all its items in an XML menu resource, then inflate the menu resource (load it as a programmable object) in your application code. Using a menu resource to define your menu is a good practice because it separates the content for the menu from your application code. It’s also easier to visualize the structure and content of a menu in XML.

To create a menu resource, create an XML file inside your project’s res/menu/ directory and build the menu with the following elements:

<menu>

Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements.

<item>

Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> lement in order to create a submenu.

<group>

An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility. See the section about Menu groups.

Here’s an example menu named game_menu.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<menu xmlns:android=”http://schemas.android.com/apk/res/android”>

<item android:id=”@+id/new_game”

android:icon=”@drawable/ic_new_game”

android:title=”@string/new_game” />

<item android:id=”@+id/help”

android:icon=”@drawable/ic_help”

android:title=”@string/help” />

</menu>

This example defines a menu with two items. Each item includes the attributes:

android:id

A resource ID that’s unique to the item, which allows the application can recognize the item when the user selects it.

android:icon

A reference to a drawable to use as the item’s icon.

android:title

A reference to a string to use as the item’s title.

There are many more attributes you can include in an <item>, including some that specify how the item may appear in the Action Bar. For more information about the XML syntax and attributes for a menu resource, see the  Menu

Resource reference.

 

Inflating a Menu Resource

From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). For example, the following code inflates the game_menu.xml file defined above, during the onCreateOptionsMenu() callback method, to use the menu as the activity’s Options Menu:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.game_menu, menu);

return true;

}

The getMenuInflater() method returns a MenuInflater for the activity. With this object, you can call inflate(), which inflates a menu resource into a Menu object. In this example, the menu resource defined by game_menu.xml is inflated into the Menu that was passed into onCreateOptionsMenu(). (This callback method for the Options Menu is discussed more in the next section.)

 Creating an Options Menu

The Options Menu is where you should include basic activity actions and necessary navigation items (for example, a utton to open the application settings). Items in the Options Menu are accessible in two distinct ways: the MENU button or in the Action Bar (on devices running Android 3.0 or higher). When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is the icon menu. It holds the first six menu items. If you add more than six items to the Options Menu, Android places the sixth item and those after it into the overflow menu, which the user can open by touching the “More” menu item.

On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears at the top of the activity in place of the traditional title bar. By default all items from the Options Menu are placed in the overflow menu, which the user can open by touching the menu icon on the right side of the Action Bar. However, you can place select menu items directly in the Action Bar as “action items,” for instant access, as shown in figure 2.

When the Android system creates the Options Menu for the first time, it calls your activity’s onCreateOptionsMenu() method. Override this method in your activity and populate the Menu that is passed into the method, Menu by inflating a menu resource as described above in Inflating a Menu Resource. For example:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.game_menu, menu);

return true;

}

You can also populate the menu in code, using add() to add items to the Menu.

Note: On Android 2.3 and lower, the system calls onCreateOptionsMenu() to create the Options Menu when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as soon as the activity is created, in order to populate the Action Bar.

 Responding to user action

When the user selects a menu item from the Options Menu (including action items in the Action Bar), the system calls your activity’s onOptionsItemSelected() method. This method passes the MenuItem that the user selected. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You can match this ID against known menu items and perform the appropriate action. For example:

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle item selection

switch (item.getItemId()) {

case R.id.new_game:

newGame();

return true;

case R.id.help:

showHelp();

return true;

default:

return super.onOptionsItemSelected(item);

}

}

In this example, getItemId() queries the ID for the selected menu item and the switch statement compares the ID against the resource IDs that were assigned to menu items in the XML resource. When a switch case successfully handles the menu item, it returns true to indicate that the item selection was handled. Otherwise, the default statement passes the menu item to the super class, in case it can handle the item selected. (If you’ve directly extended the Activity class, then the super class returns false, but it’s a good practice to pass unhandled menu items to the super class instead of directly returning false.)

Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu item in the menu resource XML, using the android:onClick attribute. So you don’t need to implement onOptionsItemSelected(). Using the android:onClick attribute, you can specify a method to call when the user selects the menu item. Your activity must then implement the method specified in the android:onClick attribute so that it accepts a single MenuItem parameter—when the system calls this method, it passes the menu item selected.

 

Tip: If your application contains multiple activities and some of them provide the same Options Menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu actions and each descendant class inherits the menu behaviors. If you want to add menu items to one of your descendant activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) so the original menu items are created, then add new menu items with menu.add(). You can also override the super class’s behavior for individual menu items.

 Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it’s first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you’d like to remove, add, disable, or enable menu items depending on the current state of your application. On Android 2.3 and lower, the system calls onPrepareOptionsMenu() each time the user opens the Options Menu. On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items. 

Note: You should never change items in the Options Menu based on the View currently in focus. When in touch mode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying items in the Options Menu. If you want to provide menu items that are context-sensitive to a View, use a Context Menu.

If you want to add menu items to one of your descendant activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) so the original menu items are created, then add new menu items with menu.add(). You can also override the super class’s behavior for individual menu items.

 Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it’s first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you’d like to remove, add, disable, or enable menu items depending on the current state of your application.

On Android 2.3 and lower, the system calls onPrepareOptionsMenu() each time the user opens the Options Menu. On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.

 Note: You should never change items in the Options Menu based on the View currently in focus. When in touch  ode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying items in the Options Menu. If you want to provide menu items that are context-sensitive to a View, use a Context Menu.

If your activity uses a ListView and you want all list items to provide a context menu, register all items for a context menu by passing the ListView to registerForContextMenu(). For example, if you’re using a ListActivity, register all list items like this:

registerForContextMenu(getListView());

In order for a View to provide a context menu, you must “register” the view for a context menu. Call registerForContextMenu() and pass it the View you want to give a context menu. When this View then receives a long-press, it displays a context menu.

To define the context menu’s appearance and behavior, override your activity’s context menu callback methods, onCreateContextMenu() and onContextItemSelected().

For example, here’s an onCreateContextMenu() that uses the context_menu.xml menu resource:

@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.context_menu, menu);

}

MenuInflater is used to inflate the context menu from a menu resource. (You can also use add() to add menu items). The callback method parameters include the View that the user selected and a ContextMenu. ContextMenuInfo object that provides additional information about the item selected. You might use these parameters to determine which context menu should be created, but in this example, all context menus for the activity are the same. Then when the user selects an item from the context menu, the system calls onContextItemSelected(). Here is an example of how you can handle selected items:

@Override

public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

switch (item.getItemId()) {

case R.id.edit:

editNote(info.id);

return true;

case R.id.delete:

deleteNote(info.id);

return true;

default:

return super.onContextItemSelected(item);

}

}

The structure of this code is similar to the example for Creating an Options Menu, in which getItemId() queries the ID for the selected menu item and a switch statement matches the item to the IDs that are defined in the menu resource. And like the options menu example, the default statement calls the super class in case it can handle menu items not handled here, if necessary.

In this example, the selected item is an item from a ListView. To perform an action on the selected item, the application needs to know the list ID for the selected item (it’s position in the ListView). To get the ID, the application calls getMenuInfo(), which returns a AdapterView.AdapterContextMenuInfo object that includes the list ID for the selected item in the id field. The local methods editNote() and deleteNote() methods accept this list ID to perform an action on the data specified by the list ID.

 Note: Items in a context menu do not support icons or shortcut keys.

 

Creating Submenus

A submenu is a menu that the user can open by selecting an item in another menu. You can add a submenu to any menu (except a submenu). Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application’s menu bar (File, Edit, View, etc.).

When creating your menu resource, you can create a submenu by adding a <menu> element as the child of an

<item>. For example:

<?xml version=”1.0″ encoding=”utf-8″?>

<menu xmlns:android=”http://schemas.android.com/apk/res/android”>

<item android:id=”@+id/file”

android:icon=”@drawable/file”

android:title=”@string/file” >

<!– “file” submenu –>

<menu>

<item android:id=”@+id/create_new”

android:title=”@string/create_new” />

<item android:id=”@+id/open”

android:title=”@string/open” />

</menu>

</item>

</menu>

When the user selects an item from a submenu, the parent menu’s respective on-item-selected callback method receives the event. For instance, if the above menu is applied as an Options Menu, then the onOptionsItemSelected() method is called when a submenu item is selected. You can also use addSubMenu() to dynamically add a SubMenu to an existing Menu. This returns the new SubMenu object, to which you can add submenu items, using add().

Summary
Review Date
Reviewed Item
What Is Android?
Author Rating
5

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on What Is Android?"

Leave a Message

Your email address will not be published. Required fields are marked *

Site Disclaimer, Copyright © 2016 - All Rights Reserved.