Android Application Development E-Book
Android Application Development E-Book
Android Application
Development
Hands-on guide to Android programming
Information in this document, including URL and other Internet Web site references,
is subject to change without notice. Complying with all applicable copyright laws is the
responsibility of the user. Without limiting the rights under copyright, no part of this
document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying,
recording, or otherwise), or for any purpose, without the express written permission of
Android ATC company.
Android ATC company is not responsible for webcasting or any other form of
transmission received from any linked site.
Android ATC company is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Android ATC of the site or the
products contained therein.
Android ATC company may have patents, patent applications, trademarks, copyrights, or
other intellectual property rights covering subject matter in this document. Except as
expressly provided in any written license agreement from Android ATC company, the
furnishing of this document does not give you any license to these patents,
trademarks, copyrights, or other intellectual property.
This book is available from www.androidatc.com
Copyright Android ATC 2012
Table of Contents
Lesson 1 Hello Android Framework-------------------------------------------------------------- 1
Introduction -----------------------------------------------------------------------------------------------1
Creating an Android Project -----------------------------------------------------------------------------1
Within Eclipse ------------------------------------------------------------------------------------------ 1
From Command line --------------------------------------------------------------------------------- 2
Running Your Application ------------------------------------------------------------------------------ 2
Running you project on the emulator -------------------------------------------------------------- 2
Components of an Android application --------------------------------------------------------------- 6
Application Life-cycle ----------------------------------------------------------------------------------- 7
Modifying created project ------------------------------------------------------------------------------ 8
Change activitys name ------------------------------------------------------------------------------ 8
Lesson 2 Android SDK Tools and Activity Class -------------------------------------------- 10
Android Software Layers ------------------------------------------------------------------------------- 10
Linux kernel ------------------------------------------------------------------------------------------ 10
C/C++ Libraries ------------------------------------------------------------------------------------- 10
Android Runtime ------------------------------------------------------------------------------------ 11
Application Framework ---------------------------------------------------------------------------- 11
Application layer ------------------------------------------------------------------------------------ 11
Android Libraries --------------------------------------------------------------------------------------- 11
The Android Manifest File ----------------------------------------------------------------------------- 12
Structure of the Manifest File ------------------------------------------------------------------------- 13
Android SDK Tools ------------------------------------------------------------------------------------- 13
Activity life-cycle through Java -------------------------------------------------------------------- 15
Create an Activity --------------------------------------------------------------------------------------- 17
Methods to remember ---------------------------------------------------------------------------------- 20
Lesson 3: ListActivity and ListView ------------------------------------------------------------ 21
Introduction --------------------------------------------------------------------------------------------- 21
Views ----------------------------------------------------------------------------------------------------- 21
Using Views ------------------------------------------------------------------------------------------ 22
II
III
IV
SQLiteOpenHelper ----------------------------------------------------------------------------------- 69
SQLiteDatabase -------------------------------------------------------------------------------------- 69
Cursors ------------------------------------------------------------------------------------------------ 70
Databases in Android ---------------------------------------------------------------------------------- 70
Native Android Content Providers -------------------------------------------------------------------- 72
Methods to remember ---------------------------------------------------------------------------------- 72
Lesson 10: Android Notifications --------------------------------------------------------------- 73
Introduction --------------------------------------------------------------------------------------------- 73
Creating a notification---------------------------------------------------------------------------------- 73
Notification actions ------------------------------------------------------------------------------------- 73
Example: NotificationManager ------------------------------------------------------------------- 74
Summary------------------------------------------------------------------------------------------------- 77
When you install the Android SDK, you will have a set development tools and utilities installed
on your hard disk that will help during your Android development. Most of these tools are
accessible from the Eclipse ADT plug-in through a set of views and buttons (more on this in
lesson 2). Thats why all the Android operations you perform from inside Eclipse, can be
performed from command line. The Eclipse ADT provides a simple and intuitive GUI to access
these commands.
Within Eclipse
To create a project from within Eclipse (preferred method)
1
New
2
3
Enter the application name and project name (Can be the same)
Enter the package name. This is a unique name for your application and used by Android
system to differentiate between your applications and others. Make sure the name
follows a proper folder structuring e.g. com.android.atc.lesson1
4 From the Build SDK drop-down list, choose the preferred target for you application.
The list will contain all APIs that you have installed in your machine using the Android
SDK Manager. It means that your code will be conforming to that API. Note that if you
choose a high SDK version, then your application might not work on older devices. Click
Next
5 Choose to build a blank Activity. Click Next.
6 Keep default value as is and click Finish.
Your Android project is now set up with required files and you can start building your
application.
Under a Windows machine, open a command prompt but clicking on start run, type
cmd, then click OK
Execute: android list targets, to get a list of all android platforms installed. Take a note of
the target id.
Execute:
android create project --target <target-id> --name MyFirstApp
--path <path-to-workspace>/MyFirstApp --activity MyFirstActivity --package
com.example.myapp
Replace <target-id> with your SDK version of preference, and <path-to-workspace>
with the location you want to save your project in.
Your Android project is now set up with several default configurations and youre ready to start
Android development.
2
3
4
5
Click New and fill in the details for the AVD. Give it a name, a platform target, an SD
card size, and a skin.
Click Create AVD.
Select the new AVD from the Android Virtual Device Manager and click Start.
The emulator needs few minutes to boot up for the first time, then you can unlock the
screen.
Your Android application is installed on an emulator and you can now starting development.
You will notice that the emulator home screen will be the lock screen. Unlock it to see your
projects screen:
The following are other examples of some of Android Java objects you will see frequently in this
book:
1. Views
Views are objects that know how to draw itself to the screen. Each activity is made up of
a set of views grouped together within a layout. View is the parent class of all Activity
widgets.
2. Intents
These are objects used to send message across the whole Android system. They are used
to broadcast messages, start an Activity, or start a Service, including an intention to have
an action performed. Its the systems duty to interpret the message and determine the
target(s) that will perform any actions as appropriate.
3. Notifications
They can be used in an application to alert users to certain events without having a
visible activity. Notifications do not steal focus or interrupt users current interaction
with an activity. They are preferably used to get a users attention from within a service.
For example, when a service finishes downloading a file from the Internet, it can alert the
user by a notification that can make sound, show dialog messages, vibrate....etc.
Application Life-cycle
Contrary to traditional applications you build, Android applications life cycle is controlled by
the Android framework itself. Its Android that runs and shuts down correctly the applications
when it is needed. Android applications are always listening to changes in its state and respond
accordingly till it reaches proper termination. Each Android application runs its own process
and process management is handled exclusively at run time. You will learn later about the
handling of life cycle event through Java call-back methods.
Android actively manages its resources, doing whatever it takes to ensure that the device
remains active. To achieve this, Android will kill applications without a warning if necessary to
free resources for applications of higher priority.
To determine which processes should be killed when low on memory, Android classifies each application
into an importance hierarchy based type of components the application is made of and the state of those
components.
Visible process
Visible, but inactive processes are those hosting visible Activities. As the name
suggests, visible Activities are visible, but they arent in the foreground or responding to
user events. This happens when an Activity is only partially obscured (by a non-fullscreen or transparent Activity). There are generally very few visible processes, and theyll
only be killed in extreme circumstances to allow active processes to continue.
Services
Processes hosting Services that have been started. Services support ongoing processing
that should continue without a visible interface. Because Services dont interact directly
with the user, they receive a slightly lower priority than visible Activities. They are still
considered to be foreground processes and wont be killed unless resources are needed
for active or visible processes.
Background process
Processes hosting Activities that arent visible and that dont have any Services that have
been started are considered background processes. There will generally be a large
number of background processes that Android will kill using a last-seen-first-killed
pattern to obtain resources for foreground processes.
Empty process
To improve overall system performance, Android often retains applications in memory
after they have reached the end of their lifetimes. Android maintains this cache to
improve the start-up time of applications when theyre re-launched. These processes are
routinely killed as required.
Changing the main activitys name that shows up in the top bar
Changing the Hello World! message.
Under Package explorer in the left pane, expand the res folder under project Lesson1.
Expand values folder
Double click on strings.xml file
Make sure the Resources tab is opened, then clicked on element title_main_activity.
On the right side of the screen, under field Value*, replace MainActivity with Lesson
1
Click element hello_world, then under field Value*, replace Hello World! with Hello
World from Android A.T.C.!
Save changes - either by pressing CTRL+S or by clicking on the save button in Eclipse.
Run the project and youll see the changes on the main screen of your application:
Lesson 2
Android SDK Tools and Activity Class
Android Software Layers
The Android system is made up of several layers as shown in the figure below.
Linux kernel
Android relies on a Linux kernel for core system services such as security, memory management,
process management, network stack, and hardware drivers. The kernel also acts as an
abstraction layer between the hardware and the rest of the software stack. Linux is a proven
driver model and efficient in resource management.
C/C++ Libraries
On top of the Linux kernel comes a set of native libraries written in C/C++, which are
responsible for stable performance of various components. They manage the access for different
processes to compose 2D and 3D graphic layers. They are also responsible for media framework
Android ATC 2012
10
processing; i.e. playback and recording support for all the major media and static image files - in
addition to supporting fonts, data storage, and web browsers.
Android Runtime
Next to the C/C++ libraries lies the Android Runtime, where the main component Dalvik
Virtual Machine (DVM) is located. It was designed based on Java Virtual Machine specifically
for Android running in limited environment, where the limited battery, CPU, memory and data
storage are the main issues. Instead of .jar file that are read by JVM, the DVM read .dx files.
These byte-code optimized files that are more efficient to run on small processes.
Android runtime contains core libraries that are written in Java language and contains of the
collection classes, the utilities, IO and other tools.
Application Framework
The Application Framework is written in Java language. It is a collection of Java libraries that all
Android applications use, whether native Android applications like dialer or any other
application any Android developer. It has several components, for example the Activity Manager
manages the life cycle of the applications, the Package Manager keeps track of the applications,
which are installed in the device, the Telephony Manager contains of a set of API necessary for
calling applications notification manager is used to customize display alerts and other functions.
Application layer
This is the upper most layer of the Android Architecture which contains all the applications used
by the end user. All application that you build lies in this layer and they are all written using the
Java programming language.
Android Libraries
Android offers a set of Java APIs for developing your applications. The following is a noncomplete list of the main libraries provided by Android SDK. All Android devices must provide
support for these libraries:
android.view
This library provides the main classes for Android graphical user interfaces and for handling
users interaction with the UI. The View class -part of this package- is the most important UI
class which other screen components inherent from.
android.widget
The widget package contains GUI elements to use on your Applications screen. This package
derives from the view package and contains built-in views ready to be used on a screen.
android.util
This is the main utility package which includes special classes like string utilities formatters and
XML parsers.
Android ATC 2012
11
android.database
It provides the API to access low-level interactions with Android databases and handling
cursors.
android.content
Provides classes to manage data access. These classes are mainly used with resources, content
providers, and packages. Context class is part of this library.
android.app
Provides access for high-level components of the application model. For example, Activity and
Service classes - basic classes for all Android applications - are part of this package.
android.provider
This library provides easier access to the basic Content Providers, like the contacts and calendar
databases.
android.telephony
Telephony package gives the ability to monitor basic phone information, like the phone state,
network connectivity, and SMS messages.
android.webkit
Provides classes to allow your application to browse the web. The main class in this library used
by developers is WebView.
In addition to set of advanced Android libraries like android.location, android.media,
android.opengl, android.hardware, android.bluetooth, ...etc.
The Java package names of the application, which is a unique identifier for the
application.
It declares which permissions the application must have in order to access protected
parts of the API.
12
It declares the minimum level of the Android API that the application requires. This value
determines whether your application is supported on a certain devices Android OS
version or not.
DDMS: Stands for Dalvik Debug Monitor Server, its a debugging tool which provides
screen capture on the device, thread and heap information on the device, logcat, process,
and radio state information, incoming call and SMS spoofing, location data spoofing, and
more.
13
To run DDMS from Eclipse: Click Window > Open Perspective > Other... > DDMS.
HierarchyViewer: allows you to debug and optimize your user interface. It provides a
visual representation of the layout's View hierarchy (the Layout View) and a magnified
inspector of the display
14
ADB: Android Debug Bridge (adb) is a command line tool that lets you communicate
with an emulator or connected Android-powered phone. It is a client-server program
that includes: a client, which runs on your development machine, a server, which runs as
a background process on your development machine, and a daemon, which runs as a
background process on each emulator or device instance.
Logcat: A mechanism for collecting and viewing system debug output. Logs from
various applications and portions of the system are collected, which then can be viewed
and filtered by the logcat command. You can use logcat from an ADB shell to view
the log messages using command adb logcat, or more preferrably, use DDMS from
within Eclipse to see your application logs in the logcat view
To log a message in your application and make it viewable through logcat, use the
following syntanx:
Log.i("Application Tag", "This is the logged message);
Traceview: This is a graphical viewer for execution data saved by your application. It
help you debug your application and profile its performance. Traceview is located under
tools/ SDK directory.
15
are functions that are called by the Android system whenever an event occurs. For example,
when you launch an Android application, the moment the Android system starts loading the
main activity of that application, it sends the callback onCreate(). In your Java code you can
override that method and add your own Java code to be executed by the system. In fact, Android
SDK provides a callback method for each event in an activity life-cycle. The following is skeleton
of a Java class which extends Activity and overrides its life-cycle events.
import android.app.Activity;
import android.os.Bundle;
public class MyActivity extends Activity {
// Called at the start of the full lifetime.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Initialize activity.
}
// Called after onCreate has finished, use to restore UI state
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
}
// Called before subsequent visible lifetimes
// for an activity process.
@Override
public void onRestart(){
super.onRestart();
// Load changes knowing that the activity has already
// been visible within this process.
}
// Called at the start of the visible lifetime.
@Override
public void onStart(){
super.onStart();
// Apply any required UI change now that the Activity is visible.
}
// Called at the start of the active lifetime.
@Override
public void onResume(){
super.onResume();
// Resume any paused UI updates, threads, or processes required
// by the activity but suspended when it was inactive.
}
// Called to save UI state changes at the
// end of the active lifecycle.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
super.onSaveInstanceState(savedInstanceState);
}
// Called at the end of the active lifetime.
@Override
16
Create an Activity
To add an activity to the project that we created in Lesson 1, you should follow these steps:
1
17
shows the default folder structure created by ADT when you create a project:
Resource files are files that contain raw data that can be accessed and used by your Java
code. Each Activity must have a layout. You can specify the components of that layout in
an XML resource file saved under res/layout. To create a layout:
18
Right click on res/layout folder, then choose News Android XML File
Choose Layout for the Resource Type, then type in my_layout as the name of
the file.
Click on Finish.
Add the Activity to your AndroidManifest.xml file. The file is located in the root
folder of your application. Every activity in an application that a user would interact with
must be included in the manifest file. By doing this, the Android system would be
notified of the activitys presence. If you omit this step, then your Java and layout files
would simply not exist according to the system even if included in your application
package. To add the activity follow these steps:
a
19
In the right pane, fill in the Name* field, which is the Java class name you
created in step 1. Click on Browse..., then choose the Java class.
After you add required files, you have to tell the Java Activity class created in step 1 to
use the layout file created in step 3. Do so by calling setContentView() method inside
onCreate() method. setContentView(R.layout.my_layout) Where my_layout is
the name of the XML layout file under res/layout/.
Methods to remember
onCreate()
setContentView()
findViewById()
20
This lesson will introduce views in general and focus on list components and other concepts
revolving around lists.
Views
The View is a Java class that represents the basic building block for user interface components.
It is the parent class of all other interactive UI components (widgets) of your application like
buttons, text fields, labels...etc.. It occupies a rectangular area on the screen and is responsible
for drawing and event handling. The ViewGroup subclass is the base class for layouts, which
are invisible containers that hold other Views (or other ViewGroups) and define their layout
properties.
Android ATC 2012
21
Using Views
All of the views in a window are arranged in a single tree. You can add views either from code or
by specifying a seet of views in XML layout files. There are many specialized subclasses of views
that act as controls or are capable of displaying text, images, or other content.
Once you have created your views, you typically might need to perform some of the following:
Set properties: for example setting the text of a TextView. The available properties
and the methods that set them will vary among the different subclasses of views. Note
that properties that are known at build time can be set in the XML layout files.
Set focus: The framework will handled moving focus in response to user input. To force
focus to a specific view, call requestFocus().
Set up listeners: Views allows you to set listeners that will be notified when something
event happens to the view. For example, some views like the Button will let you set a
listener to be notified when it is clicked. You can register such a listener using
setOnClickListener(OnClickListener).
Set visibility: You can hide or show views using setVisibility(int).
Create a new project, then open the default layout under res/layout called
main_activity.xml
22
To add a button to the layout, drag the Button component from under Form Widgets
in the left pane, to inside the activity in the right.
23
Using ListActivity - a sub type of Activity that is made up of a single List view only.
If you are planning to create an activity that contains a list view only, then the first method is
recommended for simplicity. However, if List view is only one of many components in your
activity then you have to use the second method.
Using a ListActivity
ListActivity is a sub-class of Activity that features a ListView as a the primary UI. The following
steps describe how to view a list of strings using ListActivity.
1
After you create a project, add a Java class that extends ListActivity, the same way you
added an Activity in previously. The code should be similar to this:
24
Create a String array of element you want to display. Lets assume we want to display a
list of Android version names:
static final String[] ANDROID_OS = new String[] {Cupcake, Donut, "Eclaire, Froyo,
GingerBread", HoneyComb, "Ice Cream Sandwich", "JellyBean" };
Link your array of raw data to the list view using an Adapter:
Putting the code in the previous steps together will provide the following following simple class
which produces the list view in the image above:
import
import
import
import
android.app.ListActivity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
ANDROID_OS));
25
Adapters are Java classes used in Android SDK to bind your presentation layer
to data sources. There are different sub-classes of Adatper depending on the
type of data to be bound, like ArrayAdapter, CursorAdapter...etc.
Adding ListView
In the previous section, you have seen how to populate a ListView indirectly through the usage
of ListActivity. In this section, we will add a ListView to a layout of a Java class that extends
Activity (rather than ListActivity).
1
Layout file
Add a layout file for the list item only under res/layout. This resource file only
represents the layout of each item in the ListView. Call it list_os.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="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Open the res/layout/main_activity.xml, then add List View component from under
Composite category of the palette pane.
26
Set the id property of the ListView to the preferred name. To change a property in a
widget in the layout visual editor, click on it, then a properties view will show up in
Eclipse. Look for the id property field, then change to @+id/listViewOS. ( by default the
value will be @+id/listView1)
Create a Java class that extends Activity, then get a reference to the ListView widget you
have just added in step 3:
public class ListFruitActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a reference to the list view widget
ListView listVieww = (ListView) getElemenById(R.id.listViewOS);
}
27
Link your array of raw data to the list view variable you created in step 4 using an
Adapter:
listView.setAdapter(new ArrayAdapter<String>(this,R.layout.list_os, ANDROID_OS));
Now you can run your application and view similar list as the previous section. However in this
method you can add as much widgets as you want, and can get more control over the list
properties. The final Java class will look like this:
package com.android.atc.lesson3;
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;
28
Summary
The following is a summary of the steps you should follow to populate a ListView:
1
Now that you can view the items in a list, you can make every item in the list clickable
using:
setOnItemClickListener(new OnItemClickListener(){});
Methods to remember
getListView()
setListAdapter( ArrayAdapter aa )
29
Intents
Intents are used for interaction between different android components. They glues separate
components into an interconnected system. When a button click starts an activity i.e. brings a
new activity to the foreground and the current activity goes to the background, it basically sends
the Android system a message telling it of its intention start an activity. From the Android
system perspective, there is two types of intents: explicit and implicit.
Explicit Intents
Explicit Intents specify which component it wants to start. They basically tell the system where
from the message is issued and to which component i.e. which activity or service. It does so by
specifying explicitly the name of the class to load as a parameter to the Intent constructor.
The following code sample is taken from inside an activity. It create an Instance of the Intent
class, and starts another activity:
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
In these lines, the Intent constructor specifies explicitly which activity is intends to start, by providing its
name ActivityTwo.class. You can think of the two parameter of the constructor, as the source and
destination of the message, where this refers to the current activity.
30
Briefly, explicit Intents are mainly used to start activities i.e. open a different application screen in your
application, or a service.
Implicit Intents
Rather than specifying the destination class name, implicit intent only specifies an Action, and
the underlying Android system will translate that action and starts the components that can deal
with it. The following two examples show two implicit intents
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.Androidatc.com"));
startActivity(intent);
This intent sends a message with two pieces of information. The action it should perform
(ACTION_VIEW) and the data it wants the receiver to process i.e. the url. The Android system
receives the message and looks for activities that can process this action and data.
ACTION_VIEW,
This implicit intent sends the ACTION_DIAL with a data URI made of a telephone number. The
Android system will launch its phone dialer and add the phone number supplied to the dialer to
be ready for dialing.
31
ACTION_VIEW is most common generic action. It asks that the data supplied in the
Intents URI be viewed in the most reasonable manner. Different components will
handle this action depending on the URI schema of the data supplied.
ACTION_WEB_SEARCH Opens an activity that performs a Web search based on the
text supplied in the data URI.
Data Transfer
It is very likely that you will need to transfer some data to the activity you want to start through
an Intent. Android SDK provides this ability by using extras. You can attach data to your intent
by using Intents method putExtra() in the calling activity and method getExtra() in the
called activity. Suppose you want to send a string from ActivityOne to ActivityTwo when it
starts. First you put the string as extra in the intent from ActivityOne.
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra(Intent.EXTRA_TEXT, "News for you!");
Notice that putExtra() takes two parameters: the first is a String constant that acts as a key, and
the second is the string data you want to send. Extras in intents work as key-value pairs, where
the keys serve as a unique identifier of the string sent.
Then, on the receiving side, you read the extra using getExtra().
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// Do something with the data
}
Now variable value1 should be equal to string News for you! sent by ActivityOne.
Direct calls
The examples on intents you have seen so far brings an activity to the foreground, using
startActivity() method.
When this method is used, the activity started is independent and the calling activity is not
expecting and data returned from it. startActivity(Intent) is available in every Activity object.
Android ATC 2012
32
Notice that the second parameter of startActivityForResult() is an integer constant. This acts as
a unique id for the calling intent.
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case SHOW_SUBACTIVITY:
if (resultCode == Activity.RESULT_OK)
{
Bundle resultData = data.getExtras();
Log.i("Text",resultData.getString("TextReturned"));
}
break;
}
}
33
In ActivityTwo, you return results by overriding method finish() and inside it use method
setResult(). Android system will then return a call-back to method onActivityResult() in
ActivityOne.
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("TextReturned", This string is sent from
ActivityTwo);
// Activity finished ok, return the data
setResult(RESULT_OK, data);
super.finish();
}
Register an IntentFilter
When an implicit intent is sent, the Android system tries to match that intents action and data
with all activities that can process them. This process is simply a filtration of all activities
registered in Android to receive implicit intents. For example, when you execute the following
statement:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.AndroidATC.com"));
You are implicitly telling Android to look up for all activities that process the Uri which starts
with http:// and expects ACTION_VIEW. By default, every Android system has a default
browser with can process this intent. That is why, executing that line of code will bring up the
web browser.
You can tell Android system to register one of your application activities for certain action and
data, so that it will be launched whenever an implicit intent that matches them is called.
To make one of your activities respond to an implicit intent, follow these steps:
1
<activity android:name="MyListActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.BROWSABLE"></category>
<category android:name="android.intent.category.DEFAULT"></category>
<data android:scheme="http"></data>
</intent-filter>
Android ATC 2012
34
</activity>
In your activity (MyListActivity) make a call to getIntent(). This will return an instance
of the intent, and allows you to get the intents data for processing.
Now, Android will look up for all activities that match this implicit intent. Since, it already has
the browser application as a match, as well as your registered activity, Android will show up
these two applications in a list, and you have to choose which one to open the intent with.
Methods to remember:
startActivity();
startActivityForResult()
intent.putExtra(String Key, String Value)
bundle.getExtra()
finish()
intent.getExtra()
intent.getAction()
intent.getData()
35
Modify existing views: You can create a different theme and/or behavior of an existing
view provided by Android framework. For example, you can change the default
appearance of the TextView, by drawing a different text and background colors; or you
can change the default behavior of the TextView by adding a left-to-right swipe
functionality for a TextView.
Compound Views: Combine a group of views into a single view. For example, you
might need to create a single view that contains two text views - one as a title of an article
with large font and one below it as a subtitle with smaller font. Then you can use this view
in a ListView of stories.
New views: Create a totally new view that resembles real world object; like a compass
view or a volume knob.
When you extend Android View class, you are basically creating a totally customized view.
However, by extending a built-in view (a view that itself extends from the View class) you can
use the already built-in behavior and appearance if it matches what you need and modify the
part that doesnt.
Step by Step
Android ATC 2012
36
The following section shows you how to modify Android TextView to suite your needs. We will
call the view MyTextView.
Here are the steps to create MyTextView:
1
Create a new Java class that extends TextView. It extends TextView, which is the View
we have chosen to customize in this case. When we are finished, the new class will be able
to substitute for a normal TextView view.
public static class MyTextView extends TextView {
Create Constructors
As always, the super is called first. Furthermore, this is not a default constructor, but a
parameterized one. The TextView is created with these parameters when it is inflated
from an XML layout file, thus, our constructor needs to both take them and pass them to
the superclass constructor as well.
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
...
}
Override Methods
To implement a custom view, you should usually override some of the standard methods
that the framework calls on all views. But you can just override
onDraw(android.graphics.Canvas). In this example, we want to change the appearance of
TextView, so we only need to override onDraw() to make our own drawing and
appearance changes. Later in this lesson, we will see how and what to draw in this
method.
@Override
protected void onDraw(Canvas canvas) {
super.draw(canvas);
}
37
The super.onDraw() method is called before the method ends. The superclass method
should be invoked, but in this case, we do it at the end after we have made the
appearance changes we want to include.
4
The attributes and parameters in the definition of the layout are the ones passed into the
custom component constructor, and then passed through to the TextView constructor, so
they are the same parameters that you would use for a TextView view.
Once you save your customized view Java class you created in step 1, it will
become a widget and appear in the layout editor in Eclipse. You can check it
when you edit you layout. It should appear under section Custom & Library
Views. Click on refresh if it doesnt show up.
38
You are done. All you need to do is to use the customize text view in an Activity. Either
you can use setContentView(R.layout.my_text_view) of an activity, or use the
MyTextView in a ListView where every item in the list contains a MyTextView.
A more sophisticated component can override more handler methods (the ones starting with
on...), substantially customizing its properties and behavior. You can use your imagination to
customize your component the way you want.
What is in onDraw()
The most important step in changing the appearance of a custom view is to override the
onDraw() method which take a Canvas object as a parameter and used to draw itself. The
Canvas class contains several methods to help you draw text, lines, bitmaps...etc. You can use
these methods in onDraw() to customize your view. However, you need to create an instance of
object Paint before you can draw.
Classes Canvas and Paint are two parts of the android.graphics library:
Canvas: defines what shapes that you can draw on the screen
Paint: defines the how you draw on screen using color, style, font, ...etc. of each shape.
For example, to draw a line in our MyTextView class, we must created a Paint object and use as
a parameter to a canvas method call in our onDraw() method.
public void onDraw(Canvas canvas){
canvas.save();
// Use the TextView to render the text.
super.onDraw(canvas);
...
}
android.content.Context;
android.graphics.Canvas;
android.graphics.Color;
android.graphics.Paint;
android.util.AttributeSet;
android.widget.TextView;
39
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
public void init(){
// Create the paint brushes we will use in the onDraw method.
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(Color.BLUE);
}
@Override
public void onDraw(Canvas canvas){
canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);
canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(),
getMeasuredHeight(),linePaint);
canvas.save();
super.onDraw(canvas);
canvas.restore();
my_text_view.xml
This is saved under res/layout
<?xml version="1.0" encoding="utf-8"?>
<com.androidatc.lesson5.view.MyTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MyTextView" />
40
my_text_view_list.xml
MyTextViewActivity.java
package com.androidatc.lesson5.activity;
import java.util.ArrayList;
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;
import com.androidatc.lesson5.notepad.R;
public class MyTextViewActivity extends Activity {
ListView myTextViewListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_text_view_list);
final ArrayList<String> items = new ArrayList<String>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
R.layout.my_text_view, items);
myTextViewListView = (ListView) findViewById(R.id.my_text_view_list);
myTextViewListView.setAdapter(aa);
}
}
41
Use Androids built-in Dialog sub-classes: These are Dialog boxes provided by Android
SDK. They all extend the Dialog class
Create an Activity and make it behave as a Dialog by changing its theme.
Toast: This is a special kind of message boxes that show up for a short period of time
then disappear. Toasts are not necessarily attached to an activitys lifecycle. Thats why
they preferred to be used with background services.
Dialog sub-classes
Android provides a set of Dialog sub-classes that youre recommended to use. These are:
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 Alert Dialog section later in this lesson.
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 Progress
Dialog later in this lesson.
DatePickerDialog A dialog that allows the user to select a date.
TimePickerDialog A dialog that allows the user to select a time.
Create layout resource, in the res/layout folder. Lets call the file dialog_view.xml
Create a variable of type Dialog and instantiate it.
Call setContentView(R.layout.dialog_view) for the dialog
Call show()
42
To edit the appearance of the whole dialogs window, you should get a reference to the dialogs
Window object. To do so, call:
You can modify the appearance of the Dialogs window simply by changing few flags. The
following makes the activity behind the dialog appear blurred, and changes the dialogs height
and width.
// Have the new window tint and blur the window it obscures.
Window window = dialog.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.Lay
outParams.FLAG_BLUR_BEHIND);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
Always use dialog.show() and dialog.cancel() to show and hide a dialog respectively.
43
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertD.setButton(AlertDialog.BUTTON_POSITIVE, "YES", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
alertD.show();
44
45
When you run the code, youll get the following dialog
46
To change the wheel to a progress bar, replace the following line in the code above:
progressD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
with this line
progressD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Then you will get the following dialog:
You can add two more button to the progress dialog using Dialog.BUTTON_POSITIVE and
Dialog.BUTTON_NEUTRAL as the first parameter for method setButton() as used above
47
The simplest way to do so is by applying the dialog theme to your Activity in the manifest file.
The following XML snippet goes into your manifest and then your activity will appear like a
dialog:
<activity android:name=AndroidATCActivity android:theme=@android:style/Theme.Dialog>
</activity>
Toasts
Toasts are an easy way to deliver status messages to users without disrupting the current
working activity, because unlike Alert Dialogs they do not take focus away from the Activity.
Theyre suitable for displaying informative messages that dont need too much attention. For
example, it can be used to tell the user that a download has completed, or an email is sent.
Toasts fade away automatically after a certain period of time. Due to this nature, it may
not be guaranteed that a user will read the message. Thats why toasts are not used for critical
messages.
To create a toast only a single line of code is needed:
Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();
The first parameter of makeText() defines the context in which its displayed. The second is
the message body and the last argument is and int that specifies how long the Toast should stay
on screen. Only Toast.LENGTH_LONG or Toast.LENGTH_SHORT are accepted values. Any
non-1 value is considered as a Toast.LENGTH_SHORT, and 1 is Toast.LENGTH_LONG.
A Toast message
Android ATC 2012
48
Customizing Toasts
Although showing a text message inside Toast is sufficient in most situations, but you might
need to customize your own Toast. To do that, you can set the layout of your own design and/or
change the Toasts screen position - by default a Toast is shown in the bottom of the screen.
Create and instantiate a Toast object using the makeText() static method
Toast toast = Toast.makeText(this, "Hello World from Toast!",Toast.LENGTH_LONG);
Toast class does not have method setContenView(), but rather the method
setView(). So you cant inflate a layout from an xml resource.
The following code snippet creates and displays a customized Toast. The toast contains a
message and a button, and its displayed at the top of the screen.
Toast toast = Toast.makeText(this, " ",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
49
OK
");
btn.setPadding(10, 10,10,10);
ll.addView(tv,LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
ll.addView(btn, LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
ll.setGravity(Gravity.CENTER);
toast.setView(ll);
toast.show();
50
Methods to remember
Toast.makeToast()
The following methods in class Dialog
setTitle()
show()
cancel()
The following methods for a built-in Dialog subclass (ProgressDialog, AlertDialog,...etc.)
setMessage()
setButton()
51
Menus
You can build a menu directly from Java code or from a resource file under res/menu.
3
4
The following code snippet creates a menu in an Activity and adds two items to it, Settings and
Exit.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create the menu item and keep a reference to it.
MenuItem menuItem1 = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE,
"Settings");
MenuItem menuItem2 = menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "Exit");
52
return true;
}
Notice that the method menu.add() returns a reference to the newly added
menu item and takes four arguments:
1
2
3
4
Since options menu supports icons, you can set an icon using method setIcon() with a resource
id of an image that you have to add to folder res/drawable
menuItem1.setIcon(R.drawable.ic_menu_settings);
53
Create a new XML file under folder res/menu. If folder menu is not found, create the
folder.
Open the file in Eclipse to open the menu resource editor.
Add the required menu items by clicking Add..., and selecting Item from the pop up
window.
Then fill in the required attributes for the new item. Most importantly, fill in the item id
and the title fields.
54
The Id field in the attributes form above is equivalent to the thirst parameter of
method add() explained before. This is a crucial attribute to handle event on a
menu item. Read section Handle Select Events later in this lesson for more
information.
5
6
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
55
If you check the content of the menu resource file res/menu/activity_main.xml, it will look like
this:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings" android:title="@string/menu_settings"
android:icon="@drawable/ic_menu_settings">
</item>
<item android:id="@+id/exit_option" android:title="Exit">
</item>
</menu>
Note that returning false for any case means that the item selected is not handled, the code is
ignored, and Android will call the intent associated with the menu item if any exists.
56
Sub-menus
You can create a submenu for an options menu item by following these steps:
1
2
3
4
Context Menus
Context Menus are associated to views and are triggered by pressing the View for around 3
seconds. So each Activity might have many context menus buy only one options menu.
You define and populate Context Menus similar to the options menu. You can also build a
context menu from Java code or from a resource file.
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(Context Menu);
menu.add(0, menu.FIRST, Menu.NONE, Item 1).setIcon(R.drawable.menu_item);
menu.add(0, menu.FIRST+1, Menu.NONE, Item 2).setCheckable(true);
menu.add(0, menu.FIRST+2, Menu.NONE, Item 3).setShortcut(3, 3);
57
A context menu
MenuItem icons only show up in menus. Even if you call method setIcon() on
a MenuItem of context menus or submenus, the icon will not show up, just as
in the code above.
58
A radio button group is a group of items displaying circular buttons, where only one item can be
selected at any given time. To create a radio button group, call Menu.setGroupCheckable(),
passing in that group identifier.
Shortcut Keys
Add a keypad shortcut to a menu item using method setShortcut()
// Add a shortcut to this menu item, 1 if using the numeric keypad
// or a if using the full keyboard.
menuItem.setShortcut('1', 'a');
59
Icons
Icons are resource files saved under res/drawable folder. You can add icons to options menu
only using:
menuItem.setIcon(R.drawable.menu_item_icon);
Condensed Titles
When using icons with menu item in and option menu, you can use a shortened title for the
menu item using
menuItem.setTitleCondensed(Short Title);
Intents
You can assign an Intent to a Menu Item and trigger it when clicking it. This isnt handled by the
Activitys onOptionsItemSelected() or setOnMenuItemClickListener() handler. When triggered,
Android will execute startActivity, passing in the specified Intent. This is done using setIntent()
method.
menuItem.setIntent(new Intent(this, MyOtherActivity.class));
WebView
You can embed a web browser inside your application using web views. A WebView is a crucial
component for many applications that needs to display a URL without worrying about using
Androids native views. For example, an application that displays a list of article titles and loads
the full article upon clicking can display the article in a web view, instead of retrieving the
articles text and do the rendering and parsing inside the application.
Android ATC 2012
60
3
4
5
6
In your Activitys Java class, Create an instance of WebView in your Java Activity class
and initialize it:
webView = (WebView) findViewById(R.id.webView1);
Enable javascript in the WebView
webview.getSettings().setJavaScriptEnabled(true);
Set a WebView client that will receive various requests:
webview.setWebViewClient();
Send the URL request to display the page:
webView.loadUrl(url);
Give your application INTERNET permission to allow it to access the internet. To do
this, add the following tag to your Manifest XML file:
61
Methods to remember
onCreateOptionsMenu()
onOptionsItemSelected()
onCreateContextMenu()
onContextItemSelected()
getMenuInflator().inflate(int menuRes);
The main activity takes username and password and a button that checks if credentials
are correct.
The second is a list activity that opens when the credentials are correct and shows a list
of universities.
Whenever each item is clicked, the browser opens to a Google URL searching for that
university name.
Each item in the list activity is a custom view with the background colored white and
foreground black.
62
Shared Preferences
Store application-specific primitive data in key-value pairs.
Internal Storage
Store private data on the device memory using file I/O
SQLite Databases
Store structured data in a private database.
Android also provides Content Providers - an abstraction to SQLite databases to allow
sharing applications data. They encapsulate the data, and provide mechanisms for defining
data security.
Network Connection
Store data on the web with your own network server.
63
Connect to an URL that retrieves data you can process (XML, JSON, ..etc)
Retrieve the data from the URL.
Process and manipulate retrieved data.
The following method connects to a URL and returns a string of the content retrieved:
private String connectToWeb() {
String url = "http://www.AndroidATC.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error for URL
" + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
byte[] buffer = new byte[128];
getResponseEntity.getContent().read(buffer);
return new String(buffer);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
File I/O
Reading and writing from/into local files in Android is purely java-based. To write to a file you
should create a FileOutputStream instance and to read from a file create a FileInputStream.
String FILE_NAME = tempfile.tmp;
// Create a new output file stream thats private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fis = openFileInput(FILE_NAME);
Android ATC 2012
64
Yet, you can include a file as an Android resource, and read it from the resource folder.
Shared Preferences
Shared Preferences is a very useful and simple mechanism to permanently store data of your
Android application. This is the recommended way of storing data if primitive data types are all
you need to store.
Shared Preferences are a key-value pairs used for accessing and modifying preference data, and
support all primitive types. You can get an instance of a Shared Preferences object by calling
getSharedPreferences(String, int) in any activity. For any particular set of
preferences, there is a single instance of this class that all clients share.
After you get the instance you should use SharedPreferences.Editor object to modify
preferences and ensure the preference values remain in a consistent state and control when they
are committed to storage.
The following code uses SharedPreference to save data of a primitive types. Notice that the
preferences name is the value mySharedPreferences of string constant MY_PREFS.
public static final String MY_PREFS = mySharedPreferences;
protected void savePreferences(){
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS,
mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(isTrue, true);
editor.putFloat(lastFloat, 1f);
editor.putInt(wholeNumber, 2);
Android ATC 2012
65
editor.putLong(aNumber, 3l);
editor.putString(textEntryValue, Not Empty);
// Commit the changes.
editor.commit();
}
You must call method commit on the SharedPreferences.Editor object, to save your
preference permanently. Its not enough to put the values in the object.
66
2. Create another method to load the saved activity state. Lets call it
loadActivityPreferences()
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences
mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
long aNumber = mySharedPreferences.getLong("aNumber", 0);
String stringPreference;
String stringEditValue;
stringPreference = mySharedPreferences.getString("textEntryValue", "");
stringEditValue = mySharedPreferences.getString("currentTextValue","test")
;
addTodoEditText.setText(stringEditValue);
Log.v("loadedpref",stringEditValue);
}
67
68
SQLite library
To use SQLite database in your application you need to import package android.database.*
To use databases in Android code, you have to learn about the following classes:
SQLiteOpenHelper
SQLiteDatabase
Cursor
SQLiteOpenHelper
This is a helper class to manage database creation and version management. It is
recommended that you create a subclass of SQLiteOpenHelper implementing
onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally
onOpen(SQLiteDatabase). This class takes care of opening the database if it exists,
creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the
database is always in a sensible state.
SQLiteDatabase
SQLiteDatabase exposes methods to manage a SQLite database. It has methods to create, delete,
execute SQL commands, and perform other common database management tasks.
69
Cursors
The Cursor interface provides random read-write access to the result set returned by a database
query. So, it is a just pointer to the data returned by a database query, it doesn't contain all the
data from your query. But rather used facilitate access to each row of your returned data.
Databases in Android
Here is a set of steps to create and manipulate SQLite databases in Android:
1. Create an adapter class
2. Create an inner private class extend SQLiteOpenHelper
3. Create class constructor
public MyDBAdapter(Context _context) {
context = _context;
dbHelper = new myDbHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
5. Override onCreate()
6. Override onUpgrade()
public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
int _newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
c}
70
b. Inserting
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);
d. Deleting
myDatabase.delete(DATABASE_TABLE, KEY_ID + = + rowId, null);
71
Methods to remember
Class SQLiteDatabase SQL-commands methods:
o query()
o delete()
o insert()
o update()
getContentResolver().query()
startManagingCursor()
Cursor class methods like:
o getColumnIndexOrThrow()
o getString()
o getPosition()
o moveToNext()
Android ATC 2012
72
Creating a notification
To create notifications you should use the NotificationManager class which can be created
in an Activity using the getSystemService() method.
NotificationManager MyNotificationManager
= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification actions
Although they're optional, you should add at least one action to your notification. An action
allows users to go directly from the notification to an Activity in your application.
73
You should always define the action that's triggered when the user touches the notification;
usually this action opens an Activity in your application. You can add more actions by adding
more UI elements to the notification (like a button) and assign them other on click actions.
Inside a Notification, the action itself is defined by a PendingIntent containing an Intent
that starts an Activity in your application. Here how to create a notification and an explicit
Intent to be used by a PendingIntent.
// Create Notifcation
Notification notification = new Notification(R.drawable.icon, "Hello notifications!",
System.currentTimeMillis());
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.number += 1;
// Specify the called Activity
Intent intent = new Intent(this, NotificationReceiver.class);
You use then a PendingIntent to assign the Intent to the notification and finally assign
it to the NotificationManager.
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title", "This is the text", activity);
notificationManager.notify(0, notification);
Example: NotificationManager
Create a new project "com.androidatc.notificationmanager" with the Activity
"CreateNotification".
result.xml
Create the following layout "result.xml".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andro
id"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the result activity opened from the
notification" >
Android ATC 2012
74
</TextView>
</LinearLayout>
main.xml
This layout is automatically created when you created the project. Modify it as the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk
/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="createNotification"
android:text="Create Notification" >
</Button>
</LinearLayout>
NotificationReceiver.java
Create a new activity "NotificationReceiver" and register the acitivity in the manifest file.
package com.androidatc.notificationmanager;
import android.app.Activity;
import android.os.Bundle;
public class NotificationReceiver extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
}
}
75
CreateNotification .java
Change the activity "CreateNotification" to the following.
package com.androidatc.notificationmanager;
import
import
import
import
import
import
import
android.app.Activity;
android.app.Notification;
android.app.NotificationManager;
android.app.PendingIntent;
android.content.Intent;
android.os.Bundle;
android.view.View;
When you run your application, press the button and you should receive a new notification. If
you select it, your second activity will be displayed.
76
Summary
Briefly, creating and configuring a notification requires the following simple steps:
1. Create a NotificationManager object:
String svcName = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager;
notificationManager = (NotificationManager)getSystemService(svcName);
3. Configure appearance
Context context = getApplicationContext();
// Text to display in the extended status window
String expandedText = Extended status text;
// Title for the expanded status
String expandedTitle = Notification Title;
// Intent to launch an activity when the extended text is clicked
Intent intent = new Intent(this, MyActivity.class);
PendingIntent launchIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.setLatestEventInfo(context,expandedTitle, expandedText,
launchIntent);
77