Android Notes Part1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Topic

1. About Mobile Phone History


2. Mobile Phone OS
3. Android History
4. Android Version
5. Android Architecture
6. Android Application
7. Android Application Components
8. Android Application Project Folder and files
9. Android Activity
10. Android Fragment
11. Android Intent
12. Using Resources:
13. Service:
14. BroadcastReciver:
15. Content Provider
16. Data Storage Options
17. Android UI Layouts
18. Android UI Controls
19. Android Event Handling
20. Android UI Design
1. About Mobile Phone History:

1993 The first Smart phone, the IBM Simon, had a touchscreen, email, and PDA features.
2002 Microsoft's first Windows CE (Pocket PC) Smart phones are introduced.
2002 BlackBerry releases its first Smart phone.
2007 Apple iPhone with iOS introduced as an iPhone, "mobile phone" and "internet communicator.
2007 Open Handset Alliance (OHA) formed by Google, HTC, Sony, Dell, Intel, Motorola, Samsung,
LG, etc
2008 OHA releases Android 1.0 with the HTC Dream (T-Mobile G1) as the first Android phone.

2. Mobile Phone OS :

Google's Android
Apple's iOS
Nokia's Symbian
RIM's BlackBerry OS (RIM- Research In Motion)
Samsung's Bada OS
Microsoft's Windows Phone
Hewlett-Packard's webOS

3. Android History:
Android was originally created by Andy Rubin as an operating system for mobile phones, around
the dawn of this twenty-first century. In 2005, Google acquired Android Inc., and made Andy
Rubin the Director of Mobile Platforms for Google. Many think the acquisition was largely in
response to the emergence of the Apple iPhone around that time; however, there were enough other
large players, such as RIM Blackberry, Nokia Symbian, and Microsoft Windows Mobile, that it seemed
a salient business decision for Google to purchase the talent and intellectual property necessary to
assert the company into this emerging space, which has become known as Internet 2.0.

4. Android Version:
-------------------------------------------------------------------------------------------------------
Version | Version Name | API Level | Release Date
---------------------------------------------------------------------------------- ---------------------
Android 4.4 Kitkat API Level 19 Oct 31, 2013
Android 4.3 Jelly Bean API Level 18 July 24, 2013
Android 4.2 Jelly Bean API Level 17 Nov 13, 2012
Android 4.1.2 Jelly Bean API Level 16 July 9, 2012
Android 4.0.3 Ice Cream Sandwich API Level 15 Oct 19, 2011
Android 4.0.4 Ice Cream Sandwich API Level 14 Oct 19, 2011
Android 3.2 Honey Comb API Level 13 Feb 22, 2011
Android 3.1 Honey Comb API Level 12 Feb 22, 2011
Android 3.0 Honey Comb API Level 11 Feb 22, 2011
Android 2.3.7 Ginger Bread API Level 10 Dec 6, 2010
Android 2.3.3 Ginger Bread API Level 10 Dec 6, 2010
Android 2.3.2 Ginger Bread API Level 9 Dec 6, 2010
Android 2.3 Ginger Bread API Level 9 Dec 6, 2010
Android 2.2 Froyo API Level 8 May 20, 2010
Android 2.1 Éclair API Level 7 Oct 26, 2009
Android 1.6 Donut API Level 4 Sept 15, 2009
Android 1.5 Cupcake API Level 3 April 30, 2009

5. Android Architecture :

Android is a software stack for mobile devices that includes an operating system, middleware and key
applications.

Home, Contact, Phone, Browser, Map, Email client, SMS program, Calendar are core Applications
comes with Android.
Activity Manager, Window Manager, Content Provider, View System, Package Manager, Telephony
Manager, Resource Manager, Location Manager and Notification Manager are Application
Frameworks available to used by android application developers.

- Activity Manager: This component provides an app’s life cycle and maintains a shared activity stack
for navigating within and among apps.
- Content Providers: These components encapsulate data (such as the Browser app’s bookmarks) that
can be shared among apps.
- Location Manager: This component makes it possible for an Android device to be aware of its
physical location.
- Notification Manager: This component lets an app notify the user of a significant event (such as a
message’s arrival) without interrupting what the user is currently doing.
- Package Manager: This component lets an app learn about other app packages that are currently
installed on the device.
- Resource Manager: This component lets an app access its resources.
- Telephony Manager: This component lets an app learn about a device’s telephony services. It also
handles making and receiving phone calls.
- View System: This component manages user interface elements and user interface-oriented event
generation.
- Window Manager: This component organizes the screen’s real estate into windows, allocates drawing
surfaces, and performs other window-related jobs.

Android includes a set of C/C++ libraries used by various components of the Android system. These
capabilities are exposed to developers through the Android application framework. Some of the core
libraries are listed below:

• System C library - a BSD-derived implementation of the standard C system library (libc),


tuned for embedded Linux-based devices

• Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and
recording of many popular audio and video formats, as well as static image files, including
MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG

• Surface Manager - manages access to the display subsystem and seamlessly composites 2D
and 3D graphic layers from multiple applications

• LibWebCore - a modern web browser engine which powers both the Android browser and an
embeddable web view

• SGL - the underlying 2D graphics engine

• 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either
hardware 3D acceleration (where available) or the included, highly optimized 3D software
rasterizer

• FreeType - bitmap and vector font rendering

• SQLite - a powerful and lightweight relational database engine available to all applications
Android Runtime

Android includes a set of core libraries that provides most of the functionality available in the core
libraries of the Java programming language.

Every Android application runs in its own process, with its own instance of the Dalvik virtual machine.
Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes
files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM
is register-based, and runs classes compiled by a Java language compiler that have been transformed
into the .dex format by the included "dx" tool.

The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management.

6. Android Application:

An Android application is a single installable unit which can be started and used independently of other
Android applications. It consists out of Android components and resource files.
An Android Application stores on device as a .apk file. So when we install application on device .apk
file for application store and install on device.

Describe the .apk format?

The APK file is compressed the AndroidManifeast.xml file, application code(.dex files), resource files,
and other files. A project is compiled into a single .apk file.

Each Android application lives in its own security sandbox:

• The Android operating system is a multi-user Linux system in which each application is a
different user.

• By default, the system assigns each application a unique Linux user ID (the ID is used only by
the system and is unknown to the application). The system sets permissions for all the files in an
application so that only the user ID assigned to that application can access them.

1
• Each process has its own virtual machine (VM), so an application's code runs in isolation from
other applications.

• By default, every application runs in its own Linux process. Android starts the process when
any of the application's components need to be executed, then shuts down the process when it's
no longer needed or when the system must recover memory for other applications.

7. Android Application Components:

Application components are the essential building blocks of an Android application. These components
are loosely coupled by the application manifest file AndroidManifest.xml that describes each
component of the application and how they interact.

There are following four main components that can be used within an Android application:
Components Description
Activities They they dictate the UI and handle the user interaction to the smartphone screen
Services They handle background processing associated with an application.
Broadcast Receivers They handle communication between Android OS and applications.
Content Providers They handle data and database management issues.

Application components are the essential building blocks of an Android application. Each component is
a different point through which the system can enter your application. Not all components are actual
entry points for the user and some depend on each other, but each one exists as its own entity and plays
a specific role—each one is a unique building block that helps define your application's overall
behavior.

There are four different types of application components. Each type serves a distinct purpose and has a
distinct lifecycle that defines how the component is created and destroyed.

Android application components can connect to components of other Android applications. This way
they can create cross-application tasks.

Here are the four types of application components:


Activities
An activity represents a single screen with a user interface. For example, an email application
might have one activity that shows a list of new emails, another activity to compose an email, and
another activity for reading emails. Although the activities work together to form a cohesive user
experience in the email application, each one is independent of the others. As such, a different
application can start any one of these activities (if the email application allows it). For example, a
camera application can start the activity in the email application that composes new mail, in order
for the user to share a picture.

An activity is implemented as a subclass of Activity and you can learn more about it in the
Activities developer guide.

public class MainActivity extends Activity {

Services
A service is a component that runs in the background to perform long-running operations or to
perform work for remote processes. A service does not provide a user interface. For example, a
service might play music in the background while the user is in a different application, or it might
fetch data over the network without blocking user interaction with an activity. Another
component, such as an activity, can start the service and let it run or bind to it in order to interact
with it.

A service is implemented as a subclass of Service and you can learn more about it in the
Services developer guide.

public class MyService extends Service {

Content providers
A content provider manages a shared set of application data. You can store the data in the file
system, an SQLite database, on the web, or any other persistent storage location your application
can access. Through the content provider, other applications can query or even modify the data (if
the content provider allows it). For example, the Android system provides a content provider that
manages the user's contact information. As such, any application with the proper permissions can
query part of the content provider (such as ContactsContract.Data) to read and write
information about a particular person.

Content providers are also useful for reading and writing data that is private to your application
and not shared. For example, the Note Pad sample application uses a content provider to save
notes.

A content provider is implemented as a subclass of ContentProvider and must implement a


standard set of APIs that enable other applications to perform transactions. For more information,
see the Content Providers developer guide.

A content provider is implemented as a subclass of ContentProvider class and must implement a


standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {

}
Broadcast receivers
A broadcast receiver is a component that responds to system-wide broadcast announcements.
Many broadcasts originate from the system—for example, a broadcast announcing that the screen
has turned off, the battery is low, or a picture was captured. Applications can also initiate
broadcasts—for example, to let other applications know that some data has been downloaded to
the device and is available for them to use. Although broadcast receivers don't display a user
interface, they may create a status bar notification to alert the user when a broadcast event occurs.
More commonly, though, a broadcast receiver is just a "gateway" to other components and is
intended to do a very minimal amount of work. For instance, it might initiate a service to perform
some work based on the event.

A broadcast receiver is implemented as a subclass of BroadcastReceiver and each


broadcast is delivered as an Intent object. For more information, see the
BroadcastReceiver class.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is


broadcasted as an Intent object.
public class MyReceiver extends BroadcastReceiver {

A unique aspect of the Android system design is that any application can start another application’s
component. For example, if you want the user to capture a photo with the device camera, there's
probably another application that does that and your application can use it, instead of developing an
activity to capture a photo yourself. You don't need to incorporate or even link to the code from the
camera application. Instead, you can simply start the activity in the camera application that captures a
photo. When complete, the photo is even returned to your application so you can use it. To the user, it
seems as if the camera is actually a part of your application.

When the system starts a component, it starts the process for that application (if it's not already
running) and instantiates the classes needed for the component. For example, if your application starts
the activity in the camera application that captures a photo, that activity runs in the process that belongs
to the camera application, not in your application's process. Therefore, unlike applications on most
other systems, Android applications don't have a single entry point (there's no main() function, for

example).

Because the system runs each application in a separate process with file permissions that restrict access
to other applications, your application cannot directly activate a component from another application.
The Android system, however, can. So, to activate a component in another application, you must
deliver a message to the system that specifies your intent to start a particular component. The system
then activates the component for you.
8. Android Application Project Folder and files:
<----- 1. HelloWorldApp ( Application Name)

<----- 2. MainActivity.java file ( Activity name)

<----- 3. Automatic generated files by eclipse BuildConfi.java and


R.java

<----- 4. assets folder


<----- 5. bin folder

<----- 6. HelloWorldApp.apk file ( .apk file for Application )

<----- 7. res folder ( having all resources belonging to application

<----- 8. main.xml file ( layout file for MainActivity )

<----- 9. AndroidManifest.xml (Manifest file for application )

Files under project folder of android.

1. Package Name

2. Activity Class
MainActivity.java
------------------------

package in.cdac.HelloWorldApp;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setContentView() -Set the activity content from a layout resource. The
resource will be inflated,adding all top-level views to the activity.
}
}
-------------------------

3. Automatically generated files


Every resource file gets an ID assigned by the Android build system. The gen directory in an Android

project contains the R.java references file which contains these generated values. These references

are static integer values.

R.java
-------------------------
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/

package in.cdac.HelloWorldApp;

public final class R {


public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

---------------------------

4. Asset Folder
While the res directory contains structured values which are known to the Android platform, the

assets directory can be used to store any kind of data.

While you could also store used data in the /res/raw folder. If you need access to original file names

and file hierarchy, you can save these resources in the assets directory.

Accessing assets:
You access this data via the AssetsManager which you can access the getAssets() method.

The AssetsManager class allows to read a file in the assets folder as InputStream with the

open() method. The following code shows an example for this.

6. bin folder

.apk file of an application.

7. resource folder

8. xml files
Android activities define their user interface with views (widgets) and fragments. This user interface
can be defined via XML layouts resource files in the /res/layout folder or via Java code. You can

also mix both approaches.


A layout resource file is referred to as layout. A layout specifies the ViewGroups, Views, their

relationship and their attributes via an XML representation.

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

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>

----------------------------

9. AndroidManifest file

AndroidManifest.xml
--------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.cdac.HelloWorldApp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

-------------------

the <intent-filter> element—in order to declare how other application components


may activate it.

The Manifest File


Before the Android system can start an application component, the system must know that the
component exists by reading the application's AndroidManifest.xml file (the "manifest" file).

Your application must declare all its components in this file, which must be at the root of the
application project directory.

The manifest does a number of things in addition to declaring the application's components, such as:

• Identify any user permissions the application requires, such as Internet access or read-access to
the user's contacts.

• Declare the minimum API Level required by the application, based on which APIs the
application uses.

• Declare hardware and software features used or required by the application, such as a camera,
bluetooth services, or a multitouch screen.

• API libraries the application needs to be linked against (other than the Android framework
APIs), such as the Google Maps library.

• And more

9. Android Activity:
9.1 Activity and Its Life Cycle
An activity represents the visual screen of an android application with which users can
interact.
An activity in Android creates a window over which UI components can be placed.

The Activity class defines the following callbacks i.e. events. You don't need to implement all the
callbacks methods. However, it's important that you understand each one and implement those that
ensure your app behaves the way users expect.
Callback Description
onCreate() This is the first callback and called when the activity is first created.
onStart() This callback is called when the activity becomes visible to the user.
onResume() This is called when the user starts interacting with the application.
The paused activity does not receive user input and cannot execute any code and
onPause() called when the current activity is being paused and the previous activity is being
resumed.
onStop() This callback is called when the activity is no longer visible.
onDestroy() This callback is called before the activity is destroyed by the system.
onRestart() This callback is called when the activity restarts after stopping it.

onCreate():Called when the activity is first created. This is where


you should do all of your normal static set up — create views, bind
data to lists, and so on. This method is passed a Bundle object
containing the activity's previous state, if that state was captured

onRestart():Called after the activity has been stopped, just prior to


it being started again.
Always followed by onStart()

onStart():Called just before the activity becomes visible to the


user. Followed by onResume() if the activity comes to the foreground, or onStop() if it
becomes hidden.

onResume(): Called just before the activity starts interacting with


the user. At this point the activity is at the top of the activity
stack, with user input going to it. Always followed by onPause().

OnPause(): Called when the system is about to start resuming another


activity. This method is typically used to commit unsaved changes to
persistent data,stop animations and other things that may be
consuming CPU, and so on. It should do whatever it does very quickly,
because the next activity will not be resumed until it returns.
Followed either by onResume() if the activity returns back to the front, or by onStop() if it
becomes invisible to the user.

OnStop(): Called when the activity is no longer visible to the user.


This may happen because it is being destroyed, or because another
activity (either an existing one or a new one) has been resumed and
is covering it.

Followed either by onRestart() if the activity is coming back to interact with the user, or by
onDestroy() if this activity is going away.
OnDestroy():

Called before the activity is destroyed. This is the final call that
the activity will receive. It could be called either because the
activity is finishing (someone called finish() on it)

--------------

package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {


String msg = "Android : ";

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


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}

/** Called when the activity is about to become visible. */


@Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
}

/** Called when the activity has become visible. */


@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}

/** Called when another activity is taking focus. */


@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}

/** Called when the activity is no longer visible. */


@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
}

-------------

9.2 Saving activity state

when an activity is paused or stopped, the state of the activity is retained.Thus, any changes the user
made within the activity are retained so that when the activity returns to the foreground (when it
"resumes"), those changes are still there.

However, when the system destroys an activity in order to recover memory, the Activity object is

destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate
the Activity object if the user navigates back to it.

you can ensure that important information about the activity state is preserved by implementing an
additional callback method that allows you to save information about the state of your activity:
onSaveInstanceState().

The system calls onSaveInstanceState() before making the activity vulnerable to destruction.

The system passes this method a Bundle in which you can save state information about the activity as

name-value pairs, using methods such as putString() and putInt(). Then, if the system kills

your application process and the user navigates back to your activity, the system recreates the activity
and passes the Bundle to both onCreate() and onRestoreInstanceState().

Using either of these methods, you can extract your saved state from the Bundle and restore the

activity state. If there is no state information to restore, then the Bundle passed to you is null (which

is the case when the activity is created for the first time).

MultiRes.java

---------------------
@Override

protected void onSaveInstanceState(Bundle outState) {


outState.putInt("photo_index", mCurrentPhotoIndex);
super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mCurrentPhotoIndex = savedInstanceState.getInt("photo_index");
showPhoto(mCurrentPhotoIndex);
super.onRestoreInstanceState(savedInstanceState);
}
----------------

9.3 Shutting Down Activity:

You can shut down an activity by calling its finish() method. You can also shut down a separate

activity that you previously started by calling finishActivity().

Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in
the following section about the activity lifecycle, the Android system manages the life of an activity for
you, so you do not need to finish your own activities. Calling these methods could adversely affect the
expected user experience and should only be used when you absolutely do not want the user to return to
this instance of the activity.
9.4 Tasks and Back Stack
A task is a collection of activities that users interact with when performing a certain job. The activities
are arranged in a stack (the "back stack"), in the order in which each activity is opened.

The device Home screen is the starting place for most tasks
When the current activity starts another, the new activity is pushed on the top of the stack and takes
focus. The previous activity remains in the stack, but is stopped.
When the user presses the Back button, the current activity is popped from the top of the stack (the
activity is destroyed) and the previous activity resumes (the previous state of its UI is restored).
Activities in the stack are never rearranged, only pushed and popped from the stack—pushed onto the
stack when started by the current activity and popped off when the user leaves it using the Back button.
As such, the back stack operates as a "last in, first out" object structure.

10. Android Fragment:

Android 3.0 introduced the concept of fragments, which are objects that
represent parts of an activity’s user interface. A fragment serves as a modular
section of an activity with its own life cycle and the ability to receive its own
input events, and which you can add or remove while the activity is running. You
can combine multiple fragments into a single activity to build a multipane user
interface (typically in a tablet context) and reuse the fragment in multiple
activities.
NOTE: You must always embed a fragment in an activity.
Google introduced fragments in Honeycomb mainly to support more dynamic
and flexible user interfaces on tablets and other large screens. Because a
tablet’s screen is much larger than that of a handset, there’s more room to
combine and interchange widgets. Fragments allow such designs without
forcing you to manage complex changes to the view hierarchy. By organizing an
activity’s layout into fragments, you can modify its appearance at runtime and
preserve changes in the activity-managed back stack.

11. Android Intent:


Three of the four component types—activities, services, and broadcast receivers—are activated by an
asynchronous message called an intent. Intents bind individual components to each other at runtime,
whether the component belongs to your application or another.

An intent is created with an Intent object, which defines a message to activate either a specific

component or a specific type of component—an intent can be either explicit or implicit, respectively.

For activities and services, an intent defines the action to perform (for example, to "view" or "send"
something) and may specify the URI of the data to act on (among other things that the component
being started might need to know). For example, an intent might convey a request for an activity to
show an image or to open a web page. In some cases, you can start an activity to receive a result, in
which case, the activity also returns the result in an Intent .

For broadcast receivers, the intent simply defines the announcement being broadcast (for example, a
broadcast to indicate the device battery is low includes only a known action string that indicates
"battery is low").
The other component type, content provider, is not activated by intents.

There are separate methods for activating each type of component:

• You can start an activity (or give it something new to do) by passing an Intent to

startActivity() or startActivityForResult() (when you want the activity to

return a result).

• You can start a service (or give new instructions to an ongoing service) by passing an Intent

to startService(). Or you can bind to the service by passing an Intent to

bindService().

• You can initiate a broadcast by passing an Intent to methods like sendBroadcast(),

sendOrderedBroadcast(), or sendStickyBroadcast().

• You can perform a query to a content provider by calling query() on a

ContentResolver.

What is intent in Android?


A class (Intent) will describes what a caller desires to do. The caller will send this intent to Android's
intent resolver, which finds the most suitable activity (or other component type eg service, broadcast
receiver) for the intent.
eg. opening web page in an intent, and web browser application which install on mobile device will be
perfect activity for that intent.

What are intent filters?


Intent filters are used to register activity, service , broadcast receiver as being capable of performing an
action on a particular kind of action.

For example, let's assume that you have an Activity that needs to launch an email client and sends an
email using your Android device. For this purpose, your Activity would send an ACTION_SEND along
with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper
interface for the user to pick how to send your email data.

For example, assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the
Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a
list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser
Activity. The Intent Resolver then passes your web page to the web browser and starts the Web
Browser Activity.

There are separate mechanisms for delivering intents to each type of component - activities, services,
and broadcast receivers.
S.N. Method & Description
Context.startActivity()
1 The Intent object is passed to this method to launch a new activity or get an existing activity to
do something new.
Context.startService()
2 The Intent object is passed to this method to initiate a service or deliver new instructions to an
ongoing service.
Context.sendBroadcast()
3 The Intent object is passed to this method to deliver the message to all interested broadcast
receivers.

Intent Objects
An Intent object is a bundle of information which is used by the component that receives the intent plus
information used by the Android system.

An Intent object can contain the following components based on what it is communicating or going to
perform: action, data, category, Extras

Action
This is mandatory part of the Intent object and is a string naming the action to be performed — or, in
the case of broadcast intents, the action that took place and is being reported. The action largely
determines how the rest of the intent object is structured . The Intent class defines a number of action
constants corresponding to different intents.

Intent i=new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(“http://www.cdac.in”));

startActivity(i);

-----

Intenti=new Intent(“android.intent.action.VIEW”);

i.setData(Uri.parse(“http://www.cdac.in”));
startActivity(i);

------

Intent i = new Intent(android.content.Intent.ACTION_DIAL,Uri.parse(“tel:+651234567”));

startActivity(i);

Intenti=new

Intent(android.content.Intent.ACTION_VIEW,

Uri.parse(“geo:37.827500,-122.481670”));

startActivity(i);

here http and geo are the defined scheme.

Following table lists down various important Android Intent Standard Actions. You can check Android
Official Documentation for a complete list of Actions:
S.N. Activity Action Intent & Description
ACTION_ALL_APPS
1
List all the applications available on the device.
ACTION_ANSWER
2
Handle an incoming phone call.
ACTION_BATTERY_LOW
3
This broadcast corresponds to the "Low battery warning" system dialog.
ACTION_BATTERY_OKAY
4 This will be sent after ACTION_BATTERY_LOW once the battery has gone back up to an okay
state.
ACTION_BOOT_COMPLETED
5
This is broadcast once, after the system has finished booting.
ACTION_CALL
6
Perform a call to someone specified by the data.
ACTION_CALL_BUTTON
7
The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.
ACTION_CAMERA_BUTTON
8
The "Camera Button" was pressed.
ACTION_DEFAULT
9
A synonym for ACTION_VIEW, the "standard" action that is performed on a piece of data.
ACTION_DEVICE_STORAGE_LOW
10
A sticky broadcast that indicates low memory condition on the device.
ACTION_DIAL
11
Dial a number as specified by the data.
ACTION_EDIT
12
Provide explicit editable access to the given data.
ACTION_FACTORY_TEST
13
Main entry point for factory tests.
ACTION_HEADSET_PLUG
14
Wired Headset plugged in or unplugged.
ACTION_MAIN
15
Start as a main entry point, does not expect to receive data.
ACTION_MEDIA_EJECT
16
User has expressed the desire to remove the external storage media.
ACTION_POWER_CONNECTED
17
External power has been connected to the device.
ACTION_REBOOT
18
Have the device reboot. This is only for use by system code.
ACTION_SCREEN_OFF
19
Sent after the screen turns off.
ACTION_SCREEN_ON
20
Sent after the screen turns on.
ACTION_SEARCH
21
Perform a search.
ACTION_SEND
22
Deliver some data to someone else.
ACTION_SET_WALLPAPER
23
Show settings for choosing wallpaper.
ACTION_SHUTDOWN
24
Device is shutting down.
ACTION_SYNC
25
Perform a data synchronization.
ACTION_VIEW
26
Display the data to the user.

The action in an Intent object can be set by the setAction() method and read by getAction().

Data
The URI of the data to be acted on and the MIME type of that data. For example, if the action field is
ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing.

The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and
setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the
type by getType().

Some examples of action/data pairs are:


S.N. Action/Data Pair & Description
ACTION_VIEW content://contacts/people/1
1
Display information about the person whose identifier is "1".
ACTION_DIAL content://contacts/people/1
2
Display the phone dialer with the person filled in.
ACTION_VIEW tel:123
3
Display the phone dialer with the given number filled in.
ACTION_DIAL tel:123
4
Display the phone dialer with the given number filled in.
ACTION_EDIT content://contacts/people/1
5
Edit information about the person whose identifier is "1".
ACTION_VIEW content://contacts/people/
6
Display a list of people, which the user can browse through.

Category

The category is an optional part of Intent object and it's a string containing additional information about
the kind of component that should handle the intent. The addCategory() method places a category in an
Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of
all categories currently in the object.

Following table lists down various important Android Intent Standard Categories. You can check
Android Official Documentation for a complete list of Categories:
S.N. Categories & Description
CATEGORY_APP_BROWSER
1
Used with ACTION_MAIN to launch the browser application.
CATEGORY_APP_CONTACTS
2
Used with ACTION_MAIN to launch the contacts application.
CATEGORY_APP_EMAIL
3
Used with ACTION_MAIN to launch the email application.
CATEGORY_APP_MAPS
4
Used with ACTION_MAIN to launch the maps application.
CATEGORY_APP_MESSAGING
5
Used with ACTION_MAIN to launch the messaging application.
CATEGORY_BROWSABLE
6
Activities that can be safely invoked from a browser must support this category.
CATEGORY_DEFAULT
7 Set if the activity should be an option for the default action (center press) to perform on a piece
of data.
CATEGORY_HOME
8
This is the home activity, that is the first activity that is displayed when the device boots.
CATEGORY_LAUNCHER
9
Should be displayed in the top-level launcher.

You can check detail on Intent Filters in below section to understand how do we use categories to
choose appropriate acivity coressponding to an Intent.

Extras
This will be in key-value pairs for additional information that should be delivered to the component
handling the intent. The extras can be set and read using the putExtras() and getExtras() methods
respectively.

Types of Intents

There are following two types of intents supported by Android till version 4.1

Explicit Intents
These intents designate the target component by its name and they are typically used for application-
internal messages - such as an activity starting a subordinate service or launching a sister activity. For
example:
// Explicit Intent by specifying its class name
Intent i = new Intent(this, TargetActivity.class);
i.putExtra("Key1", "ABC");
i.putExtra("Key2", "123");

// Starts TargetActivity
startActivity(i);

Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit intents
are often used to activate components in other applications. For example:
// Implicit Intent by specifying a URI
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));

// Starts Implicit Activity


startActivity(i);

The target component which receives the intent can use the getExtras() method to get the extra data
sent by the source component. For example:
// Get bundle object at appropriate place in your code
Bundle extras = getIntent().getExtras();

// Extract data using passed keys


String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");

What is a Sticky Intent?


SendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, the intent you are sending
stays around after the broadcast is complete, so that others can quickly retrieve that data through the
return value of registerReceiver ( BroadcastReceiver, IntentFilter). In all other ways, this behaves the
same as sendBroadcast(Intent).

12. Using Resources:

Organize Resources
You should place each type of resource in a specific subdirectory of your project's res/ directory. For
example, here's the file hierarchy for a simple project:
MyProject/
src/
MyActivity.java
res/
drawable/
icon.png
layout/
activity_main.xml
info.xml
values/
strings.xml

The res/ directory contains all the resources in various subdirectories. Here we have an image resource,
two layout resources, and a string resource file. Following table gives a detail about the resource
directories supported inside project res/ directory.
Directory Resource Type
XML files that define property animations. They are saved in res/anim/ folder and accessed
anim/
from the R.anim class.
XML files that define a state list of colors. They are saved in res/color/ and accessed from
color/
the R.color class.
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state lists,
drawable/ shapes, animation drawables. They are saved in res/drawable/ and accessed from the
R.drawable class.
XML files that define a user interface layout. They are saved in res/layout/ and accessed
layout/
from the R.layout class.
XML files that define application menus, such as an Options Menu, Context Menu, or Sub
menu/
Menu. They are saved in res/menu/ and accessed from the R.menu class.
Arbitrary files to save in their raw form. You need to call Resources.openRawResource()
raw/
with the resource ID, which is R.raw.filename to open such raw files.
values/ XML files that contain simple values, such as strings, integers, and colors. For example,
here are some filename conventions for resources you can create in this directory:

• arrays.xml for resource arrays, and accessed from the R.array class.

• integers.xml for resource integers, and accessed from the R.integer class.

• bools.xml for resource boolean, and accessed from the R.bool class.

• colors.xml for color values, and accessed from the R.color class.

• dimens.xml for dimension values, and accessed from the R.dimen class.

• strings.xml for string values, and accessed from the R.string class.

• styles.xml for styles, and accessed from the R.style class.

Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You can
xml/
save various configuration files here which will be used at run time.

Alternative Resources
Your application should provide alternative resources to support specific device configurations. For
example, you should include alternative drawable resources ( ie.images ) for different screen resolution
and alternative string resources for different languages. At runtime, Android detects the current device
configuration and loads the appropriate resources for your application.

To specify configuration-specific alternatives for a set of resources, follow the following steps:

• Create a new directory in res/ named in the form <resources_name>-<config_qualifier>. Here


resources_name will be any of the resources mentioned in the above table, like layout,
drawable etc. The qualifier will specify an individual configuration for which these resources
are to be used. You can check official documentation for a complete list of qualifiers for
different type of resources.

• Save the respective alternative resources in this new directory. The resource files must be named
exactly the same as the default resource files as shown in the below example, but these files will
have content specific to the alternative. For example though image file name will be same but
for high resolution screen, its resolution will be high.

Below is an example which specifies images for a default screen and alternative images for high
resolution screen.
MyProject/
src/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml

Below is another example which specifies layout for a default language and alternative layout for
arabic language.
MyProject/
src/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
layout-ar/
main.xml
values/
strings.xml

Accessing Resources
During your application development you will need to access defined resources either in your code, or
in your layout XML files. Following section explains how to access your resources in both the
scenarios:

Accessing Resources in Code


When your Android application is compiled, a R class gets generated, which contains resource IDs for
all the resources available in your res/ directory. You can use R class to access that resource using sub-
directory and resource name or directly resource ID.

Example:
To access res/drawable/myimage.png and set an ImageView you will use following code:
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);

Here first line of the code make use of R.id.myimageview to get ImageView defined with id
myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get an image
with name myimage available in drawable sub-directory under /res.
Example:
Consider next example where res/values/strings.xml has following definition:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>

Now you can set the text on a TextView object with ID msg using a resource ID as follows:
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);

Example:
Consider a layout res/layout/activity_main.xml with the following definition:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>

This application code will load this layout for an Activity, in the onCreate() method as follows:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}

Accessing Resources in XML

Consider the following resource XML res/values/strings.xml file that includes a color resource and a
string resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>

Now you can use these resources in the following layout file to set the text color and text string as
follows:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />

Now if you will go through previous chapter once again where I have explained Hello World!
example, and I'm sure you will have better understanding on all the concepts explained in this chapter.
So I highly recommend to check previous chapter for working example and check how I have used
various resources at very basic level.

13. Service:

A Service is an application component that can perform long-running operations in the background
and does not provide a user interface. Another application component can start a service and it will
continue to run in the background even if the user switches to another application. Additionally, a
component can bind to a service to interact with it and even perform interprocess communication
(IPC). For example, a service might handle network transactions, play music, perform file I/O, or
interact with a content provider, all from the background.

To create a service, you must create a subclass of Service (or one of its existing subclasses). In your
implementation, you need to override some callback methods that handle key aspects of the service
lifecycle and provide a mechanism for components to bind to the service, if appropriate. The most
important callback methods you should override are:

understand each one and implement those that ensure your app behaves the way users expect.
Callback Description
The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement
onStartCommand()
this method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide
onBind() an interface that clients use to communicate with the service, by returning an
IBinder object. You must always implement this method, but if you don't want to
allow binding, then you should return null.
The system calls this method when all clients have disconnected from a
onUnbind()
particular interface published by the service.
The system calls this method when new clients have connected to the service,
onRebind() after it had previously been notified that all had disconnected in its
onUnbind(Intent).
onCreate() The system calls this method when the service is first created using
onStartCommand() or onBind(). This call is required to perform one-time setup.
The system calls this method when the service is no longer used and is being
onDestroy() destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.

Declaring a service in the manifest


Like activities (and other components), you must declare all services in your application's manifest file.

To declare your service, add a <service> element as a child of the <application> element. For

example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>

Starting a Service

You can start a service from an activity or other application component by passing an Intent

(specifying the service to start) to startService(). The Android system calls the service's

onStartCommand() method and passes it the Intent. (You should never call

onStartCommand() directly.)

For example, an activity can start the example service in the previous section (HelloSevice) using

an explicit intent with startService():


Intent intent = new Intent(this, HelloService.class);
startService(intent);

The startService() method returns immediately and the Android system calls the service's

onStartCommand() method. If the service is not already running, the system first calls

onCreate(), then calls onStartCommand().


Stopping a service
A started service must manage its own lifecycle. That is, the system does not stop or destroy the service
unless it must recover system memory and the service continues to run after onStartCommand()

returns. So, the service must stop itself by calling stopSelf() or another component can stop it by

calling stopService().

Creating a Bound Service

A bound service is one that allows application components to bind to it by calling bindService()

in order to create a long-standing connection (and generally does not allow components to start it by
calling startService()).

You should create a bound service when you want to interact with the service from activities and other
components in your application or to expose some of your application's functionality to other
applications, through interprocess communication (IPC).

Managing the Lifecycle of a Service

The lifecycle of a service is much simpler than that of an activity. However, it's even more important
that you pay close attention to how your service is created and destroyed, because a service can run in
the background without the user being aware.

The service lifecycle—from when it's created to when it's destroyed—can


follow two different paths:
• A started service

The service is created when another component calls startService(). The service then

runs indefinitely and must stop itself by calling stopSelf(). Another component can also

stop the service by calling stopService(). When the service is stopped, the system destroys

it..
• A bound service

The service is created when another component (a client) calls bindService(). The client

then communicates with the service through an IBinder interface. The client can close the

connection by calling unbindService(). Multiple clients can bind to the same service and

when all of them unbind, the system destroys the service. (The service does not need to stop
itself.)

Implementing the lifecycle callbacks


Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in
the service's state and perform work at the appropriate times. The following skeleton service
demonstrates each of the lifecycle methods:
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used

@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}

14. BroadcastReciver:
Broadcast Receivers simply respond to broadcast messages from other applications or from the system
itself. These messages are sometime called events or intents. For example, applications can also initiate
broadcasts to let other applications know that some data has been downloaded to the device and is
available for them to use, so this is broadcast receiver who will intercept this communication and will
initiate appropriate action.

There are following two important steps to make BroadcastReceiver works for the systen broadcasted
intents:

• Creating the Broadcast Receiver.

• Registering Broadcast Receiver

There is one additional steps in case you are going to implement your custom intents then you will have
to create and broadcast those intents.

Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the


onReceive() method where each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}

Registering Broadcast Receiver


An application listens for specific broadcast intents by registering a broadcast receiver in
AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event
ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed
the boot process.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>

</application>

Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver
MyReceiver and implemented logic inside onReceive() will be executed.

There are several system generated events defined as final static fields in the Intent class. The
following table lists a few important system events.
Event Constant Description
android.intent.action.BATTERY_CHAN Sticky broadcast containing the charging state, level, and
GED other information about the battery.
android.intent.action.BATTERY_LOW Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLET
This is broadcast once, after the system has finished booting.
ED
android.intent.action.BUG_REPORT Show activity for reporting a bug.
android.intent.action.CALL Perform a call to someone specified by the data.
The user pressed the "call" button to go to the dialer or other
android.intent.action.CALL_BUTTON
appropriate UI for placing a call.
android.intent.action.DATE_CHANGED The date has changed.
android.intent.action.REBOOT Have the device reboot.

Broadcasting Custom Intents


If you want your application itself should generate and send custom intents then you will have to create
and send those intents by using the sendBroadcast() method inside your activity class. If you use the
sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays
around after the broadcast is complete.
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("in.cdac.CUSTOM_INTENT");
sendBroadcast(intent);
}

This intent in.cdac.CUSTOM_INTENT can also be regsitered in similar way as we have regsitered
system generated intent.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="in.cdac.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>

</application>

-----------------

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}

----------------

15. Content Provider


Content providers manage access to a structured set of data. They encapsulate the data, and provide
mechanisms for defining data security. Content providers are the standard interface that connects data
in one process with code running in another process.

Each Android applications runs in its own process with its own permissions which keeps an application
data hidden from another application. But sometimes it is required to share data across applications.
This is where content providers become very useful.

Content providers let you centralize content in one place and have many different applications access it
as needed. A content provider behaves very much like a database where you can query it, edit its
content, as well as add or delete content usingg insert(), update(), delete(), and query() methods. In
most cases this data is stored in an SQlite database.

A content provider is implemented as a subclass of ContentProvider class and must implement a


standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {

A content provider component supplies data from one application to others on request. Such requests
are handled by the methods of the ContentResolver class. A content provider can use different ways to
store its data and the data can be stored in a database, in files, or even over a network.

When you want to access data in a content provider, you use the ContentResolver object in your
application's Context to communicate with the provider as a client. The ContentResolver object
communicates with the provider object, an instance of a class that implements ContentProvider.
The provider object receives data requests from clients, performs the requested action, and returns the
results.

Content URIs
To query a content provider, you specify the query string in the form of a URI which has following
format:
<prefix>://<authority>/<data_type>/<id>

Here is the detaial of various parts of the URI:


Part Description
prefix This is always set to content://
This specifies the name of the content provider, for example contacts, browser etc. For
authority
third-party content providers, this could be the fully qualified name
This indicates the type of data that this particular provider provides. For example, if you are
data_type getting all the contacts from the Contacts content provider, then the data path would be
people and URI would look like this content://contacts/people
This specifies the specific record requested. For example, if you are looking for contact
id number 5 in the Contacts content provider then URI would look like this
content://contacts/people/5.

Create Content Provider


This involves number of simple steps to create your own content provider.

• First of all you need to create a Content Provider class that extends the ContentProviderbase
class.

• Second, you need to define your content provider URI address which will be used to access the
content.

• Next you will need to create your own database to keep the content. Usually, Android uses
SQLite database and framework needs to override onCreate() method which will use SQLite
Open Helper method to create or open the provider's databse. When your application is
launched, the onCreate() handler of each of its Content Providers is called on the main
application thread.

• Next you will have to implement Content Provider queries to perform different database
specific operations.

• Finally register your Content Provider in your acitivity file using <provider> tag.

Here is the list of methods which you need to override in Content Provider class to have your Content
Provider working:

• onCreate() This method is called when the provider is started.

• query() This method receives a request from a client. The result is returned as a Cursor object.

• insert()This method inserts a new record into the content provider.

• delete() This method deletes an existing record from the content provider.

• update() This method updates an existing record from the content provider.

• getType() This method returns the MIME type of the data at the given URI.

16. Data Storage Options


Android provides several options for you to save persistent application data. The solution you choose
depends on your specific needs, such as whether the data should be private to your application or
accessible to other applications (and the user) and how much space your data requires.

Your data storage options are the following:


Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.

Android provides a way for you to expose even your private data to other applications — with a
content provider. A content provider is an optional component that exposes read/write access to your
application data, subject to whatever restrictions you want to impose. For more information about using
content providers, see the Content Providers documentation.

16.1 Using Shared Preferences

The SharedPreferences class provides a general framework that allows you to save and retrieve

persistent key-value pairs of primitive data types. You can use SharedPreferences to save any

primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even
if your application is killed).

User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has
chosen. If you're interested in creating user preferences for your application, see
PreferenceActivity, which provides an Activity framework for you to create user preferences,

which will be automatically persisted (using shared preferences).

To get a SharedPreferences object for your application, use one of two methods:

• getSharedPreferences() - Use this if you need multiple preferences files identified by

name, which you specify with the first parameter.

• getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

1. Call edit() to get a SharedPreferences.Editor.

2. Add values with methods such as putBoolean() and putString().

3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

16.2 Using the Internal Storage

You can save files directly on the device's internal storage. By default, files saved to the internal storage
are private to your application and other applications cannot access them (nor can the user). When the
user uninstalls your application, these files are removed.

To create and write a private file to the internal storage:

1. Call openFileOutput() with the name of the file and the operating mode. This returns a

FileOutputStream.

2. Write to the file with write().

3. Close the stream with close().

For example:
String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);


fos.write(string.getBytes());
fos.close();

MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your

application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and

MODE_WORLD_WRITEABLE.

To read a file from internal storage:

1. Call openFileInput() and pass it the name of the file to read. This returns a

FileInputStream.
2. Read bytes from the file with read().

3. Then close the stream with close().

Other useful methods


getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.

16.3 Using the External Storage


Every Android-compatible device supports a shared "external storage" that you can use to save files.
This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.
Files saved to the external storage are world-readable and can be modified by the user when they
enable USB mass storage to transfer files on a computer.

It's possible that a device using a partition of the internal storage for the external storage may also offer
an SD card slot. In this case, the SD card is not part of the external storage and your app cannot access
it (the extra storage is intended only for user-provided media that the system scans).

Caution: External storage can become unavailable if the user mounts the external storage on a
computer or removes the media, and there's no security enforced upon files you save to the external
storage. All applications can read and write files placed on the external storage and the user can remove
them.

Checking media availability


Before you do any work with the external storage, you should always call
getExternalStorageState() to check whether the media is available. The media might be

mounted to a computer, missing, read-only, or in some other state. For example, here's how you can
check the availability:

16.4 Using Databases

Android provides full support for SQLite databases. Any databases you create will be accessible by
name to any class in the application, but not outside the application.
The recommended method to create a new SQLite database is to create a subclass of
SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite

command to create tables in the database. For example:


public class DictionaryOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;


private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";

DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}

You can then get an instance of your SQLiteOpenHelper implementation using the constructor

you've defined. To write to and read from the database, call getWritableDatabase() and

getReadableDatabase(), respectively. These both return a SQLiteDatabase object that

represents the database and provides methods for SQLite operations.

Android does not impose any limitations beyond the standard SQLite concepts. We do recommend
including an autoincrement value key field that can be used as a unique ID to quickly find a record.
This is not required for private data, but if you implement a content provider, you must include a
unique ID using the BaseColumns._ID constant.

You can execute SQLite queries using the SQLiteDatabase query() methods, which accept

various query parameters, such as the table to query, the projection, selection, columns, grouping, and
others. For complex queries, such as those that require column aliases, you should use
SQLiteQueryBuilder, which provides several convienent methods for building queries.

Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor

is always the mechanism with which you can navigate results from a database query and read rows and
columns.

For sample apps that demonstrate how to use SQLite databases in Android, see the Note Pad and
Searchable Dictionary applications.
17. Android UI Layouts
The basic building block for user interface is a View object which is created from the View class and
occupies a rectangular area on the screen and is responsible for drawing and event handling. View is
the base class for widgets, which are used to create interactive UI components like buttons, text fields,
etc.

The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.

At third level we have different layouts which are subclasses of ViewGroup class and a typical layout
defines the visual structure for an Android user interface and can be created either at run time using
View/ViewGroup objects or you can declare your layout using simple XML file main_layout.xml
which is located in the res/layout folder of your project.

This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may
contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple
example of XML file having LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

<!-- More GUI components go here -->

</LinearLayout>

Once your layout is defined, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
S.N. Layout & Description
Linear Layout
1 LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
Relative Layout
2
RelativeLayout is a view group that displays child views in relative positions.
Table Layout
3
TableLayout is a view that groups views into rows and columns.
Absolute Layout
4
AbsoluteLayout enables you to specify the exact location of its children.
Frame Layout
5
The FrameLayout is a placeholder on screen that you can use to display a single view.
List View
6
ListView is a view group that displays a list of scrollable items.
Grid View
7
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that layout.
Following are common attributes and will be applied to all the layouts:
Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBott
This is the extra space on the bottom side of the layout.
om
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRigh
This is the extra space on the right side of the layout.
t
android:layout_gravity This specifies how child Views are positioned.
This specifies how much of the extra space in the layout should be
android:layout_weight
allocated to the View.
android:layout_x This specifies the x-coordinate of the layout.
android:layout_y This specifies the y-coordinate of the layout.
android:layout_width This is the width of the layout.
android:layout_width This is the width of the layout.
android:paddingLeft This is the left padding filled for the layout.
android:paddingRight This is the right padding filled for the layout.
android:paddingTop This is the top padding filled for the layout.
android:paddingBottom This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch),
px( Pixels), mm ( Millimeters) and finally in (inches).

You can specify width and height with exact measurements but more often, you will use one of these
constants to set the width or height:

• android:layout_width=wrap_content tells your view to size itself to the dimensions required


by its content.

• android:layout_width=fill_parent tells your view to become as big as its parent view.

Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.
Constant Value Description
top 0x30 Push object to the top of its container, not changing its size.
bottom 0x50 Push object to the bottom of its container, not changing its size.
left 0x03 Push object to the left of its container, not changing its size.
right 0x05 Push object to the right of its container, not changing its size.
center_verti
0x10 Place object in the vertical center of its container, not changing its size.
cal
Grow the vertical size of the object if needed so it completely fills its
fill_vertical 0x70
container.
center_horiz
0x01 Place object in the horizontal center of its container, not changing its size.
ontal
fill_horizont Grow the horizontal size of the object if needed so it completely fills its
0x07
al container.
Place the object in the center of its container in both the vertical and
center 0x11
horizontal axis, not changing its size.
Grow the horizontal and vertical size of the object if needed so it
fill 0x77
completely fills its container.
Additional option that can be set to have the top and/or bottom edges of the
child clipped to its container's bounds. The clip will be based on the vertical
clip_vertical 0x80
gravity: a top gravity will clip the bottom edge, a bottom gravity will clip
the top edge, and neither will clip both edges.
Additional option that can be set to have the left and/or right edges of the
clip_horizo child clipped to its container's bounds. The clip will be based on the
0x08
ntal horizontal gravity: a left gravity will clip the right edge, a right gravity will
clip the left edge, and neither will clip both edges.
start 0x00800003 Push object to the beginning of its container, not changing its size.
end 0x00800005 Push object to the end of its container, not changing its size.

View Identification

A view object may have a unique ID assigned to it which will identify the View uniquely within the
tree. The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"

Following is a brief description of @ and + signs:

• The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and
expand the rest of the ID string and identify it as an ID resource.

• The plus-symbol (+) means that this is a new resource name that must be created and added to
our resources. To create an instance of the view object and capture it from the layout, use the
following:
Button myButton = (Button) findViewById(R.id.my_button);

18. Android UI Controls


An Android application user interface is everything that the user can see and interact with. You have
learned about the various layouts that you can use to position your views in an activity. This chapter
will give you detail on various views.

A View is an object that draws something on the screen that the user can interact with and a
ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of
the user interface.

You define your layout in an XML file which offers a human-readable structure for the layout, similar
to HTML. For example, a simple vertical layout with a text view and a button looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.
S.N. UI Control & Description
TextView
1
This control is used to display text to the user.
EditText
2
EditText is a predefined subclass of TextView that includes rich editing capabilities.
AutoCompleteTextView
3 The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of
completion suggestions automatically while the user is typing.
Button
4
A push-button that can be pressed, or clicked, by the user to perform an action.
ImageButton
5
AbsoluteLayout enables you to specify the exact location of its children.
CheckBox
6 An on/off switch that can be toggled by the user. You should use checkboxes when presenting
users with a group of selectable options that are not mutually exclusive.
ToggleButton
7
An on/off button with a light indicator.
RadioButton
8
The RadioButton has two states: either checked or unchecked.
RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.
ProgressBar
10 The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are
performing a task in the background.
Spinner
11
A drop-down list that allows users to select one value from a set.
TimePicker
12 The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM
mode.
DatePicker
13
The DatePicker view enables users to select a date of the day.

Create UI Controls
As explained in previous chapter, a view object may have a unique ID assigned to it which will identify
the View uniquely within the tree. The syntax for an ID, inside an XML tag is:
android:id="@+id/text_id"

To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign
it a unique ID as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use the following:
TextView myText = (TextView) findViewById(R.id.text_id);

19. Android Event Handling


Events are a useful way to collect data about a user's interaction with interactive components of your
app, like button presses or screen touch etc. The Android framework maintains an event queue into
which events are placed as they occur and then each event is removed from the queue on a first-in,
first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per
requirements.

There are following three concepts related to Android Event Management:

• Event Listeners: The View class is mainly involved in building up a Android GUI, same View
class provides a number of Event Listeners. The Event Listener is the object that receives
notification when an event happes.

• Event Listeners Registration: Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener fires
the event.

• Event Handlers: When an event happens and we have registered and event listener fo the
event, the event listener calls the Event Handlers, which is the method that actually handles the
event.

Event Listeners & Event Handlers


Event Handler Event Listener & Description
OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget
onClick()
like button, text, image etc. You will use onClick() event handler to handle such
event.
OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget
onLongClick()
like button, text, image etc. for one or more seconds. You will use onLongClick()
event handler to handle such event.
OnFocusChangeListener()
onFocusChange()
This is called when the widget looses its focus ie. user goes away from the view
item. You will use onFocusChange() event handler to handle such event.
OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
onKey()
hardware key on the device. You will use onKey() event handler to handle such
event.
OnTouchListener()
onTouch() This is called when the user presses the key, releases the key, or any movement
gesture on the screen. You will use onTouch() event handler to handle such event.
OnMenuItemClickListener()
onMenuItemClick(
This is called when the user selects a menu item. You will use onMenuItemClick()
)
event handler to handle such event.
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official
documentation for Android application development in case you are going to develop a sophisticated
apps.

Event Listeners Registration:

Event Registration is the process by which an Event Handler gets registered with an Event Listener so
that the handler is called when the Event Listener fires the event. Though there are several tricky ways
to register your event listener for any event, but I'm going to list down only top 3 ways, out of which
you can use any of them based on the situation.

• Using an Anonymous Inner Class

• Activity class implements the Listener interface.

• Using Layout file activity_main.xml to specify event handler directly.

Below section will provide you detailed examples on all the three scenarios:

Event Listeners Registration Using an Anonymous Inner Class


Here you will create an anonymous implementation of the listener and will be useful if each class is
applied to a single control only and you have advantage to pass arguments to event handler. In this
approach event handler methods can access private data of Activity. No reference is needed to call to
Activity.

But if you applied the handler to more than one control, you would have to cut and paste the code for
the handler and if the code for the handler is long, it makes the code harder to maintain.

Following are the simple steps to show how we will make use of separate Listener class to register and
capture click event. Similar way you can implement your listener for any other required event type.
20. Android UI Design

Units of Measurement
When you are specifying the size of an element on an Android UI, you should remember the following
units of measurement.
Sr.No Unit & description
dp
1
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.
sp
2
Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes
pt
3
Point. A point is defined to be 1/72 of an inch, based on the physical screen size.
px
4
Pixel. Corresponds to actual pixels on the screen

Screen Densities
Sr.No Density & DPI
Low density (ldpi)
1
120 dpi
Medium density (mdpi)
2
160 dpi
High density (hdpi)
3
240 dpi
Extra High density (xhdpi)
4
320 dpi

You might also like