Free Essay

Android Tutorial

In:

Submitted By Lenohj21
Words 22354
Pages 90
Android Tutorial

ANDROID TUTORIAL

Simply Easy Learning by tutorialspoint.com

tutorialspoint.com i ABOUT THE TUTORIAL

Android Tutorial
Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. This tutorial will teach you basic Android programming and will also take you through some advance concepts related to Android application development.

Audience
This tutorial has been prepared for the beginners to help them understand basic Android programming. After completing this tutorial you will find yourself at a moderate level of expertise in Android programming from where you can take yourself to next levels.

Prerequisites
Android programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn Android application development.

Copyright & Disclaimer Notice
All
the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com

TUTORIALS POINT Simply Easy Learning

Table of Content
Android Tutorial........................................................................ 2 Audience .................................................................................. 2 Prerequisites ............................................................................ 2 Copyright & Disclaimer Notice.................................................. 2 Overview .................................................................................. 7
Features of Android .................................................................................... 7 Android Applications .................................................................................. 8

Environment Setup .................................................................. 9
Step 1 - Setup Java Development Kit (JDK) .............................................. 9 Step 2 - Setup Android SDK..................................................................... 10 Step 3 - Setup Eclipse IDE ....................................................................... 11 Step 4 - Setup Android Development Tools (ADT) Plugin ........................ 12 Step 5 - Create Android Virtual Device..................................................... 14

Architecture............................................................................ 16
Linux kernel .............................................................................................. 16 Libraries ................................................................................................... 17 Android Runtime ...................................................................................... 17 Application Framework ............................................................................. 17 Applications .............................................................................................. 17

Application Components ........................................................ 18
Activities ................................................................................................... 18 Services ................................................................................................... 18 Broadcast Receivers ................................................................................ 19 Content Providers .................................................................................... 19 Additional Components ............................................................................ 19

Hello World Example ............................................................. 20
Create Android Application....................................................................... 20 Anatomy of Android Application ............................................................... 22 The Main Activity File ............................................................................... 24 The Manifest File ...................................................................................... 24 The Strings File ........................................................................................ 25 The R File................................................................................................. 26 The Layout File ........................................................................................ 26 Running the Application ........................................................................... 27

Resources Organizing & ........................................................ 29 Accessing .............................................................................. 29
Alternative Resources .............................................................................. 30 TUTORIALS POINT Simply Easy Learning

Accessing Resources ............................................................................... 31 ACCESSING RESOURCES IN CODE..................................................... 31 EXAMPLE: ............................................................................................... 31 EXAMPLE: ............................................................................................... 31 EXAMPLE: ............................................................................................... 32 ACCESSING RESOURCES IN XML........................................................ 32

Activities................................................................................. 33
Example ................................................................................................... 34

Services ................................................................................. 37
Example ................................................................................................... 40

Broadcast Recievers .............................................................. 45
Creating the Broadcast Receiver ............................................................. 45 Registering Broadcast Receiver ............................................................... 45 Broadcasting Custom Intents ................................................................... 46 Example ................................................................................................... 47

Content Providers .................................................................. 52
Content URIs............................................................................................ 52 Create Content Provider........................................................................... 53 Example ................................................................................................... 53

Fragments.............................................................................. 63
Fragment Life Cycle ................................................................................. 64 How to use Fragments? ........................................................................... 65 Example ................................................................................................... 66

Intents and Filters .................................................................. 72
Intent Objects ........................................................................................... 72 ACTION.................................................................................................... 73 Android Intent Standard Actions: .............................................................. 73 DATA........................................................................................................ 76 CATEGORY ............................................................................................. 76 EXTRAS ................................................................................................... 78 FLAGS ..................................................................................................... 80 COMPONENT NAME............................................................................... 80 Types of Intents........................................................................................ 80 EXPLICIT INTENTS ................................................................................. 80 IMPLICIT INTENTS .................................................................................. 81 Example ................................................................................................... 81 Intent Filters ............................................................................................. 84 Example ................................................................................................... 85

UI Layouts.............................................................................. 92
TUTORIALS POINT Simply Easy Learning

Android Layout Types .............................................................................. 93 Example ................................................................................................... 93 RelativeLayout Attributes ......................................................................... 96 Example ................................................................................................... 98 GridView Attributes ................................................................................ 111 Example ................................................................................................. 112 Sub-Activity Example ............................................................................. 116 Layout Attributes .................................................................................... 122 View Identification .................................................................................. 124

UI Controls ........................................................................... 125
Android UI Controls ................................................................................ 125 TextView ................................................................................................ 126 TextView Attributes ................................................................................ 126 Example ................................................................................................. 128 Exercise: ................................................................................................ 131 EditText .................................................................................................. 131 EditText Attributes .................................................................................. 131 Example ................................................................................................. 132 Exercise: ................................................................................................ 136 AutoCompleteTextView .......................................................................... 136 AutoCompleteTextView Attributes .......................................................... 136 Example ................................................................................................. 137 Exercise: ................................................................................................ 140 Button ..................................................................................................... 140 Button Attributes ..................................................................................... 140 Example ................................................................................................. 141 Exercise: ................................................................................................ 145 ImageButton ........................................................................................... 145 ImageButton Attributes ........................................................................... 145 Example ................................................................................................. 146 Exercise: ................................................................................................ 149 CheckBox ............................................................................................... 149 CheckBox Attributes ............................................................................... 149 Example ................................................................................................. 150 Exercise: ................................................................................................ 155 ToggleButton .......................................................................................... 155 ToggleButton Attributes .......................................................................... 155 Example ................................................................................................. 156 Exercise: ................................................................................................ 160 TUTORIALS POINT Simply Easy Learning

RadioButton ........................................................................................... 160 RadioButton Attributes ........................................................................... 160 Example ................................................................................................. 161 Exercise: ................................................................................................ 165 RadioGroup ............................................................................................ 165 RadioGroup Attributes ............................................................................ 165 Example ................................................................................................. 165 Exercise: ................................................................................................ 170 Create UI Controls ................................................................................. 170

Event Handling..................................................................... 172
Event Listeners & Event Handlers .......................................................... 172 Event Listeners Registration: ................................................................. 173 Event Handling Examples ...................................................................... 173 EVENT LISTENERS REGISTRATION USING AN ANONYMOUS INNER CLASS 173 REGISTRATION USING THE ACTIVITY IMPLEMENTS LISTENER INTERFACE 176 REGISTRATION USING LAYOUT FILE ACTIVITY_MAIN.XML ............ 178 Exercise: ................................................................................................ 180

Styles and Themes .............................................................. 181
Defining Styles ....................................................................................... 182 Using Styles ........................................................................................... 182 Style Inheritance .................................................................................... 186 Android Themes ..................................................................................... 187 Default Styles & Themes ........................................................................ 191

Custom Components ........................................................... 192
Creating a Simple Custom Component .................................................. 192
INSTANTIATE USING CODE INSIDE ACTIVITY CLASS .................... 193 INSTANTIATE USING LAYOUT XML FILE .......................................... 196

Custom Component with Custom Attributes........................................... 201
STEP 1 .................................................................................................. 202 STEP 2 .................................................................................................. 202 STEP 3 .................................................................................................. 203

Example ................................................................................................. 208 Big View Notification .............................................................................. 214

TUTORIALS POINT Simply Easy Learning

CHAPTER

1

Overview
What is Android?

A

ndroid is an open source and Linux-based Operating System for mobile devices such as smartphones

and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2.

Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below: Feature Beautiful UI Connectivity Storage Media support Messaging Description Android OS basic screen provides a beautiful and intuitive user interface. GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX. SQLite, a lightweight relational database, is used for data storage purposes. H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP SMS and MMS

TUTORIALS POINT Simply Easy Learning

Web browser

Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3. Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero. User can jump from one task to another and same time various application can run simultaneously. Widgets are resizable, so users can expand them to show more content or shrink them to save space Supports single direction and bi-directional text. Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution. A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection. A popular NFC-based technology that lets users instantly share, just by touching two NFCenabled phones together.

Multi-touch

Multi-tasking

Resizable widgets Multi-Language GCM

Wi-Fi Direct

Android Beam

Android Applications
Android applications are usually developed in the Java language using the Android Software Development Kit. Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide. This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications.

TUTORIALS POINT Simply Easy Learning

CHAPTER

2

Environment Setup

Y
      

ou will be glad to know that you can start your Android application development on either of the following

operating systems: Microsoft Windows XP or later version. Mac OS X 10.5.8 or later version with Intel chip. Linux including GNU C Library 2.7 or later.

Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming. Java JDK5 or JDK6 Android SDK Eclipse IDE for Java Developers (optional) Android Development Tools (ADT) Eclipse Plugin (optional)

Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment.

Step 1 - Setup Java Development Kit (JDK)
You can download the latest version of Java JDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME=C:\jdk1.6.0_15

TUTORIALS POINT Simply Easy Learning

Alternatively, you could also right-click on My Computer, select Properties, then Advanced, thenEnvironment Variables. Then, you would update the PATH value and press the OK button. On Linux, if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following code into your .cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) Eclipse, then it will know automatically where you have installed your Java.

Step 2 - Setup Android SDK
You can download the latest version of Android SDK from Android official website : Android SDK Downloads. If you are installing SDK on Windows machine, then you will find a installer_rXX-windows.exe, so just download and run this exe which will launch Android SDK Tool Setup wizard to guide you throughout of the installation, so just follow the instructions carefully. Finally you will haveAndroid SDK Tools installed on your machine. If you are installing SDK either on Mac OS or Linux, check the instructions provided along with the downloaded android-sdk_rXX-macosx.zip file for Mac OS and android-sdk_rXX-linux.tgz file for Linux. This tutorial will consider that you are going to setup your environment on Windows machine having Windows 7 operating system. So let's launch Android SDK Manager using the option All Programs > Android SDK Tools > SDK Manager, this will give you following window:

Once you launched SDK manager, its time to install other required packages. By default it will list down total 7 packages to be installed, but I will suggest to de-select Documentation for Android SDK andSamples for

TUTORIALS POINT Simply Easy Learning

SDK packages to reduce installation time. Next click Install 7 Packages button to proceed, which will display following dialogue box:

If you agree to install all the packages, select Accept All radio button and proceed by clicking Installbutton. Now let SDK manager do its work and you go, pick up a cup of coffee and wait until all the packages are installed. It may take some time depending on your internet connection. Once all the packages are installed, you can close SDK manager using top-right cross button.

Step 3 - Setup Eclipse IDE
All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from http://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Linux machine: $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display following result:

TUTORIALS POINT Simply Easy Learning

Step 4 - Setup Android Development Tools (ADT) Plugin
This step will help you in setting Android Development Tool plugin for Eclipse. Let's start with launching Eclipse and then, choose Help > Software Updates > Install New Software. This will display the following dialogue box.

TUTORIALS POINT Simply Easy Learning

Now use Add button to add ADT Plugin as name and https://dl-ssl.google.com/android/eclipse/ as the location. Then click OK to add this location, as soon as you will click OK button to add this location, Eclipse starts searching for the plug-in available the given location and finally lists down the found plugins.

TUTORIALS POINT Simply Easy Learning

Now select all the listed plug-ins using Select All button and click Next button which will guide you ahead to install Android Development Tools and other required plugins.

Step 5 - Create Android Virtual Device
To test your Android applications you will need a virtual Android device. So before we start writing our code, let us create an Android virtual device. Launch Android AVD Manager using Eclipse menu optionsWindow > AVD Manager> which will launch Android AVD Manager. Use New button to create a new Android Virtual Device and enter the following information, before clicking Create AVD button.

TUTORIALS POINT Simply Easy Learning

If your AVD is created successfully it means your environment is ready for Android application development. If you like, you can close this window using top-right cross button. Better you re-start your machine and once you are done with this last step, you are ready to proceed for your first Android example but before that we will see few more important concepts related to Android Application Development.

TUTORIALS POINT Simply Easy Learning

CHAPTER

3

Architecture

A

ndroid operating system is a stack of software components which is roughly divided into five sections and

four main layers as shown below in the architecture diagram.

Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.

TUTORIALS POINT Simply Easy Learning

Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.

Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language.

Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications.

Applications
You will find all the Android application at the top layer. You will write your application to be installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.

TUTORIALS POINT Simply Easy Learning

CHAPTER

4

Application Components

A
Activities Services

pplication 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 They they dictate the UI and handle the user interaction to the smartphone screen They handle background processing associated with an application. They handle communication between Android OS and applications. They handle data and database management issues.

Broadcast Receivers Content Providers

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. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. An activity is implemented as a subclass of Activity class as follows: public class MainActivity extends Activity { }

Services
A service is a component that runs in the background to perform long-running operations. 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. A service is implemented as a subclass of Service class as follows: public class MyService extends Service {

TUTORIALS POINT Simply Easy Learning

}

Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system. 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. 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 {

Content Providers
A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely. 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 } We will go through these tags in detail while covering application components in individual chapters. ContentProvider {

Additional Components
There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are: Components Fragments Views Layouts Intents Resources Manifest Description Represents a behavior or a portion of user interface in an Activity. UI elements that are drawn onscreen including buttons, lists forms etc. View hierarchies that control screen format and appearance of the views. Messages wiring components together. External elements, such as strings, constants and drawables pictures. Configuration file for the application.

TUTORIALS POINT Simply Easy Learning

CHAPTER

5

Hello World Example

L

et us start actual programming with Android Framework. Before you start writing your first example using

Android SDK, you have to make sure that you have setup your Android development environment properly as explained in Android - Environment Setup tutorial. I also assume that you have a little bit working knowledge with Eclipse IDE. So let us proceed to write a simple Android Application which will print "Hello World!".

Create Android Application
The first step is to create a simple Android Application using Eclipse IDE. Follow the option File -> New -> Project and finally select Android New Application wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows:

TUTORIALS POINT Simply Easy Learning

Next, follow the instructions provided and keep all other entries as default till the final step. Once your project is created successfully, you will have following project screen:

TUTORIALS POINT Simply Easy Learning

Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in the Android project:

TUTORIALS POINT Simply Easy Learning

S.N. Folder, File & Description 1 src This contains the .java source files for your project. By default, it includes an MainActivity.javasource file having an activity class that runs when your app is launched using the app icon. gen This contains the .R file, a compiler-generated file that references all the resources found in your project. You should not modify this file. bin This folder contains the Android package files .apk built by the ADT during the build process and everything

2

3

TUTORIALS POINT Simply Easy Learning

else needed to run an Android application. 4 5 res/drawable-hdpi This is a directory for drawable objects that are designed for high-density screens. res/layout This is a directory for files that define your app's user interface. res/values This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions. AndroidManifest.xml This is the manifest file which describes the fundamental characteristics of the app and defines each of its components.

6

7

Following section will give a brief overview few of the important application files.

The Main Activity File
The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application: package com.example.helloworld; import import import import import android.os.Bundle; android.app.Activity; android.view.Menu; android.view.MenuItem; android.support.v4.app.NavUtils;

public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } Here, R.layout.activity_main refers to the activity_main.xml file located in TheonCreate() method is one of many methods that are fi red when an activity is loaded. the res/layout folder.

The Manifest File
Whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which ressides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file: Here ... tags enclosed the components related to the application. Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders The tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using tags. The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is namedandroid.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon. The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to theapp_name string defined in the strings.xml fi le, which is "HelloWorld". Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components:

   

elements for activities elements for services elements for broadcast receivers elements for content providers

The Strings File
The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file: HelloWorld Hello world! Settings MainActivity

TUTORIALS POINT Simply Easy Learning

The R File
The gen/com.example.helloworld/R.java file is the glue between the activity Java files likeMainActivity.java and the resources like strings.xml. It is an automatically generated file and you should not modify the content of the R.java file. Following is a sample of R.java file: /* 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 com.example.helloworld; public final class R { public static final class attr { } public static final class dimen { public static final int padding_large=0x7f040002; public static final int padding_medium=0x7f040001; public static final int padding_small=0x7f040000; } public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; } public static final class id { public static final int menu_settings=0x7f080000; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int activity_main=0x7f070000; } public static final class string { public static final int app_name=0x7f050000; public static final int hello_world=0x7f050001; public static final int menu_settings=0x7f050002; public static final int title_activity_main=0x7f050003; } public static final class style { public static final int AppTheme=0x7f060000; } }

The Layout File
The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout: This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attribuites like android:layout_width,android:layout_height etc which are being used to set its width and height etc. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml fi le, which is "Hello World!".

Running the Application
Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

TUTORIALS POINT Simply Easy Learning

Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best.

TUTORIALS POINT Simply Easy Learning

CHAPTER

6

Resources Organizing & Accessing

T

here are many more items which you use to build a good Android application. Apart from coding for the

application, you take care of various other resources like static content that your code uses, such as bitmaps, colors, layout definitions, user interface strings, animation instructions, and more. These resources are always maintained separately in various sub-directories under res/ directory of the project. This tutorial will explain you how you can organize your application resources, specify alternative resources and access them in your applications.

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 anim/ color/ Resource Type XML files that define property animations. They are saved in res/anim/ folder and accessed from the R.anim class. XML files that define a state list of colors. They are saved in res/color/ and accessed

TUTORIALS POINT Simply Easy Learning

from the R.color class. drawable/ Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state lists, 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 from the R.layout class. XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. They are saved in res/menu/ and accessed from theR.menu class. Arbitrary files to save in their raw form. You need to callResources.openRawResource() with the resource ID, which is R.raw.filename to open such raw files. 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.integerclass. 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 save various configuration files here which will be used at run time.

layout/ menu/

raw/

values/

      

xml/

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 -. Hereresources_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

TUTORIALS POINT Simply Easy Learning

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 idmyimageview 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: Hello, World!

TUTORIALS POINT Simply Easy Learning

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: 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: #f00 Hello! Now you can use these resources in the following layout file to set the text color and text string as follows: 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.

TUTORIALS POINT Simply Easy Learning

CHAPTER

7

Activities

A

n 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. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in anActivity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity lifecycle diagram: (image courtesy : android.com )

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 onCreate() onStart() onResume() Description This is the first callback and called when the activity is first created. This callback is called when the activity becomes visible to the user. This is called when the user starts interacting with the application.

TUTORIALS POINT Simply Easy Learning

onPause() onStop() onDestroy() onRestart()

The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. This callback is called when the activity is no longer visible. This callback is called before the activity is destroyed by the system. This callback is called when the activity restarts after stopping it.

Example
This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 2 3 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged. Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.helloworld/MainActivity.java. This file includes each of the fundamental lifecycle methods. The Log.d() method has been used to generate log messages: 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

TUTORIALS POINT Simply Easy Learning

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"); } } An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file: setContentView(R.layout.activity_main); An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an that includes the MAIN action and LAUNCHER category as follows: If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps. Let's try to run our modified Hello World! application we just modified. I assume you had created yourAVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Eclipse IDE: 07-19 15:00:43.405: D/Android :(866): The onCreate() event

TUTORIALS POINT Simply Easy Learning

07-19 15:00:43.405: D/Android :(866): The onStart() event 07-19 15:00:43.415: D/Android :(866): The onResume() event

Let us try to click Red button in LogCat window in Eclipse IDE:

on the Android emulator and it will generate following events messages

07-19 15:01:10.995: D/Android :(866): The onPause() event 07-19 15:01:12.705: D/Android :(866): The onStop() event Let us again try to click Menu button in LogCat window in Eclipse IDE: on the Android emulator and it will generate following events messages

07-19 15:01:13.995: D/Android :(866): The onStart() event 07-19 15:01:14.705: D/Android :(866): The onResume() event

Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Eclipse IDE and this completes the Acitivity Life Cycle for an Android Application. 07-19 15:33:15.687: D/Android :(992): The onPause() event 07-19 15:33:15.525: D/Android :(992): The onStop() event 07-19 15:33:15.525: D/Android :(992): The onDestroy() event

TUTORIALS POINT Simply Easy Learning

CHAPTER

8

Services

A
State Started Bound

service is a component that runs in the background to perform long-running operations without needing

to interact with the user. 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. A service can essentially take two states: Description A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by callingbindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).

A service has lifecycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService(): (image courtesy : android.com )

TUTORIALS POINT Simply Easy Learning

To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines various callback methods and the most important are given below. 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 The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement 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 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 particular interface published by the service. The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in itsonUnbind(Intent).

onStartCommand()

onBind()

onUnbind() onRebind()

TUTORIALS POINT Simply Easy Learning

onCreate()

The system calls this method when the service is first created usingonStartCommand() 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 destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.

onDestroy()

The following skeleton service demonstrates each of the lifecycle methods: package com.tutorialspoint; import import import import android.app.Service; android.os.IBinder; android.content.Intent; android.os.Bundle;

public class HelloService extends Service { /** indicates how to behave if the service is killed */ int mStartMode; /** interface for clients that bind */ IBinder mBinder; /** indicates whether onRebind should be used */ boolean mAllowRebind; /** Called when the service is being created. */ @Override public void onCreate() { } /** The service is starting, due to a call to startService() */ @Override public int onStartCommand(Intent intent, int flags, int startId) { return mStartMode; } /** A client is binding to the service with bindService() */ @Override public IBinder onBind(Intent intent) { return mBinder; } /** Called when all clients have unbound with unbindService() */ @Override public boolean onUnbind(Intent intent) { return mAllowRebind; } /** Called when a client is binding to the service with bindService()*/ @Override public void onRebind(Intent intent) { } /** Called when The service is no longer used and is being destroyed */ @Override public void onDestroy() { }

TUTORIALS POINT Simply Easy Learning

}

Example
This example will take you through simple steps to show how to create your own Android Service. Follow the following steps to modify the Android application we created in Hello World Examplechapter: Step 1 2 3 4 5 6 7 Description You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify main activity file MainActivity.java to add startService() and stopService() methods. Create a new java file MyService.java under the package com.example.helloworld. This file will have implementation of Android service related methods. Define your service in AndroidManifest.xml file using tag. An application can have one or more services without any restrictions. Modify the detault content of res/layout/activity_main.xml file to include two buttons in linear layout. Define two constants start_service and stop_service in res/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.helloworld/MainActivity.java. This file can include each of the fundamental lifecycle methods. We have added startService() and stopService() methods to start and stop the service. package com.example.helloworld; import import import import import android.os.Bundle; android.app.Activity; android.view.Menu; android.content.Intent; android.view.View;

public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // Method to start the service public void startService(View view) { startService(new Intent(getBaseContext(), MyService.class)); } // Method to stop the service public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); }

TUTORIALS POINT Simply Easy Learning

} Following is the content of src/com.example.helloworld/MyService.java. This file can have implementation of one or more methods associated with Service based on requirements. For now we are going to implement only two methods onStartCommand() and onDestroy(): package com.example.helloworld; import import import import android.app.Service; android.content.Intent; android.os.IBinder; android.widget.Toast;

public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } } Following will the modified content of AndroidManifest.xml file. Here we have added tag to include our service: Following will be the content of res/layout/activity_main.xml file to include two buttons:

TUTORIALS POINT Simply Easy Learning

Following will be the content of res/values/strings.xml to define two new constants: Stop Service

Let's try to run our modified Hello World! application we just modified. I assume you had created yourAVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

TUTORIALS POINT Simply Easy Learning

Now to start your service, let's click on Start Service button, this will start the service and as per our programming in onStartCommand() method, a message Service Started will appear on the bottom of the the simulator as follows:

TUTORIALS POINT Simply Easy Learning

To stop the service, you can click the Stop Service button.

TUTORIALS POINT Simply Easy Learning

CHAPTER

9

Broadcast Recievers

B
 

roadcast 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 inAndroidManifest.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. Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiverand 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 android.intent.action.BATTERY_CHANGED android.intent.action.BATTERY_LOW android.intent.action.BATTERY_OKAY android.intent.action.BOOT_COMPLETED android.intent.action.BUG_REPORT android.intent.action.CALL android.intent.action.CALL_BUTTON android.intent.action.DATE_CHANGED android.intent.action.REBOOT Description Sticky broadcast containing the charging state, level, and other information about the battery. Indicates low battery condition on the device. Indicates the battery is now okay after being low. This is broadcast once, after the system has finished booting. Show activity for reporting a bug. Perform a call to someone specified by the data. The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. The date has changed. 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 thesendStickyBroadcast(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("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent); } This intent com.tutorialspoint.CUSTOM_INTENT can also be regsitered in similar way as we have regsitered system generated intent.

TUTORIALS POINT Simply Easy Learning

Example
This example will explain you how to create BroadcastReceiver to intercept custom intent. Once you are familiar with custom intent, then you can program your application to intercept system generated intents. So let's follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 2 3 4 5 6 7 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify main activity file MainActivity.java to add broadcastIntent() method. Create a new java file called MyReceiver.java under the package com.example.helloworld to define a BroadcastReceiver. An application can handle one or more custom and system intents without any restrictions. Every indent you want to intercept must be registered in your AndroidManifest.xml file using tag Modify the detault content of res/layout/activity_main.xml file to include a button to broadcast intent. Define a constant broadcast_intent in res/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.helloworld/MainActivity.java. This file can include each of the fundamental lifecycle methods. We have added broadcastIntent() method to broadcast a custom intent. package com.example.helloworld; import import import import import android.os.Bundle; android.app.Activity; android.view.Menu; android.content.Intent; android.view.View;

public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // broadcast a custom intent. public void broadcastIntent(View view)

TUTORIALS POINT Simply Easy Learning

{ Intent intent = new Intent(); intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent); } } Following is the content of src/com.example.helloworld/MyReceiver.java: package com.example.helloworld; import import import import android.content.BroadcastReceiver; android.content.Context; android.content.Intent; android.widget.Toast;

public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); } } Following will the modified content of AndroidManifest.xml file. Here we have added tag to include our service: Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent: Following will be the content of res/values/strings.xml to define two new constants: Broadcast Intent

Let's try to run our modified Hello World! application we just modified. I assume you had created yourAVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

TUTORIALS POINT Simply Easy Learning

Now to broadcast our custom intent, let's click on Broadcast Intent button, this will broadcast our custom intent "com.tutorialspoint.CUSTOM_INTENT" which will be intercepted by our registered BroadcastReceiver ie. MyReceiver and as per our implemented logic a toast will appear on the bottom of the the simulator as follows:

TUTORIALS POINT Simply Easy Learning

You can try implementing other BroadcastReceiver to intercept system generated intents like system bootup, date changed, low battery etc.

TUTORIALS POINT Simply Easy Learning

10
Content Providers

CHAPTER

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. 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 {

Content URIs
To query a content provider, you specify the query string in the form of a URI which has following format: ://// Here is the detaial of various parts of the URI: Part prefix authority Description This is always set to content:// This specifies the name of the content provider, for example contacts, browser etc. For third-party content providers, this could be the fully qualified name, such ascom.tutorialspoint.statusprovider

This indicates the type of data that this particular provider provides. For example, if you are getting all data_type the contacts from the Contacts content provider, then the data path would be people and URI would look like this content://contacts/people Id This specifies the specific record requested. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like thiscontent://contacts/people/5.

TUTORIALS POINT Simply Easy Learning

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 ContentProviderbaseclass. 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, theonCreate() 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 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.

Example
This example will explain you how to create your own ContentProvider. So let's follow the following steps to similar to what we followed while creating Hello World Example: Step Description 1 2 3 4 5 6 7 You will use Eclipse IDE to create an Android application and name it as MyContentProviderunder a package com.example.mycontentprovider, with blank Activity. Modify main activity file MainActivity.java to add two new methods onClickAddName() andonClickRetrieveStudents(). Create a new java file called StudentsProvider.java under the packagecom.example.mycontentprovider to define your actual provider and associated methods. Register your content provider in your AndroidManifest.xml file using tag Modify the detault content of res/layout/activity_main.xml file to include a small GUI to add sudents records. Define required constants in res/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.mycontentprovider/MainActivity.java. This file can include each of the fundamental lifecycle methods. We have added two new methods onClickAddName() andonClickRetrieveStudents() to handle user interaction with the application. package com.example.mycontentprovider;

TUTORIALS POINT Simply Easy Learning

import import import import import import import import import import

android.net.Uri; android.os.Bundle; android.app.Activity; android.content.ContentValues; android.content.CursorLoader; android.database.Cursor; android.view.Menu; android.view.View; android.widget.EditText; android.widget.Toast;

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public void onClickAddName(View view) { // Add a new student record ContentValues values = new ContentValues(); values.put(StudentsProvider.NAME, ((EditText)findViewById(R.id.txtName)).getText().toString()); values.put(StudentsProvider.GRADE, ((EditText)findViewById(R.id.txtGrade)).getText().toString()); Uri uri = getContentResolver().insert( StudentsProvider.CONTENT_URI, values); Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show(); } public void onClickRetrieveStudents(View view) { // Retrieve student records String URL = "content://com.example.provider.College/students"; Uri students = Uri.parse(URL); Cursor c = managedQuery(students, null, null, null, "name"); if (c.moveToFirst()) { do{ Toast.makeText(this, c.getString(c.getColumnIndex(StudentsProvider._ID)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)), Toast.LENGTH_SHORT).show(); } while (c.moveToNext()); } } }

TUTORIALS POINT Simply Easy Learning

Create new file StudentsProvider.java under com.example.mycontentprovider package and following is the content of src/com.example.mycontentprovider/StudentsProvider.java: package com.example.mycontentprovider; import java.util.HashMap; import import import import import import import import import import import import android.content.ContentProvider; android.content.ContentUris; android.content.ContentValues; android.content.Context; android.content.UriMatcher; android.database.Cursor; android.database.SQLException; android.database.sqlite.SQLiteDatabase; android.database.sqlite.SQLiteOpenHelper; android.database.sqlite.SQLiteQueryBuilder; android.net.Uri; android.text.TextUtils;

public class StudentsProvider extends ContentProvider { static final String PROVIDER_NAME = "com.example.provider.College"; static final String URL = "content://" + PROVIDER_NAME + "/students"; static final Uri CONTENT_URI = Uri.parse(URL); static final String _ID = "_id"; static final String NAME = "name"; static final String GRADE = "grade"; private static HashMap STUDENTS_PROJECTION_MAP; static final int STUDENTS = 1; static final int STUDENT_ID = 2; static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS); uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID); } /** * Database specific constant declarations */ private SQLiteDatabase db; static final String DATABASE_NAME = "College"; static final String STUDENTS_TABLE_NAME = "students"; static final int DATABASE_VERSION = 1; static final String CREATE_DB_TABLE = " CREATE TABLE " + STUDENTS_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL, " + " grade TEXT NOT NULL);"; /** * Helper class that actually creates and manages * the provider's underlying data repository. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context){

TUTORIALS POINT Simply Easy Learning

super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME); onCreate(db); } } @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); /** * Create a write able database which will trigger its * creation if it doesn't already exist. */ db = dbHelper.getWritableDatabase(); return (db == null)? false:true; } @Override public Uri insert(Uri uri, ContentValues values) { /** * Add a new student record */ long rowID = db.insert( STUDENTS_TABLE_NAME, "", values); /** * If record is added successfully */ if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to add a record into " + uri); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(STUDENTS_TABLE_NAME); switch (uriMatcher.match(uri)) { case STUDENTS: qb.setProjectionMap(STUDENTS_PROJECTION_MAP); break; case STUDENT_ID: qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1)); break;

TUTORIALS POINT Simply Easy Learning

default: throw new IllegalArgumentException("Unknown URI " + uri); } if (sortOrder == null || sortOrder == ""){ /** * By default sort on student names */ sortOrder = NAME; } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); /** * register to watch a content URI for changes */ c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs); break; case STUDENT_ID: String id = uri.getPathSegments().get(1); count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs); break; case STUDENT_ID: count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri ); } getContext().getContentResolver().notifyChange(uri, null);

TUTORIALS POINT Simply Easy Learning

return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)){ /** * Get all student records */ case STUDENTS: return "vnd.android.cursor.dir/vnd.example.students"; /** * Get a particular student */ case STUDENT_ID: return "vnd.android.cursor.item/vnd.example.students"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } } Following will the modified content of AndroidManifest.xml file. Here we have added tag to include our content provider: Following will be the content of res/layout/activity_main.xml file to include a button to broadcast your custom intent: Make sure you have following content of res/values/strings.xml file: MyContentProvider Settings Hello world! ; Let's try to run our modified MyContentProvider application we just created. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window, be patience because it may take sometime based on your computer speed:

TUTORIALS POINT Simply Easy Learning

Now let's enter student Name and Grade and finally click on Add Name button, this will add student record in the database and will flash a message at the bottom showing ContentProvider URI along with record number added in the database. This operation makes use of our insert() method. Let's repeat this process to add few more students in the database of our content provider.

TUTORIALS POINT Simply Easy Learning

Once you are done with adding records in the database, now its time to ask ContentProvider to give us those records back, so let's click Retrieve Students button which will fetch and display all the records one by one which is as per our the implementation of our query() method.

TUTORIALS POINT Simply Easy Learning

You can write activities against update and delete operations by providing callback functions inMainActivity.java file and then modify user interface to have buttons for update and deleted operations in the same way as we have done for add and read operations. This way you can use existing Content Provider like Address Book or you can use Content Provider concept in developing nice database oriented applications where you can perform all sort of database operations like read, write, update and delete as explained above in the example.

TUTORIALS POINT Simply Easy Learning

11
Fragments

CHAPTER

A
      

Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which

enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-acitivity. Following are important points about fragment: A fragment has its own layout and its own behavior with its own lifecycle callbacks. You can add or remove fragments in an activity while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI. A fragment can be used in multiple activities. Fragment life cycle is closely related to the lifecycle of its host activity which means when the activity is paused, all the fragments available in the acivity will also be stopped. A fragment can implement a behavior that has no user interface component. Fragments were added to the Android API in Honeycomb version of Android which API version 11.

You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a element. Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single acitivity but each acitivity can comprise of multiple fragments which will have their own layout, events and complete lifecycle. Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

TUTORIALS POINT Simply Easy Learning

The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article.

Fragment Life Cycle
Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.

TUTORIALS POINT Simply Easy Learning

Phase I: When a fragment gets created, it goes through the following states:

   

onAttach() onCreate() onCreateView() onActivityCreated()

Phase II: When the fragment becomes visible, it goes through these states:

 

onStart() onResume() Phase III: When the fragment goes into the background mode, it goes through these states:

 

onPaused() onStop() Phase IV: When the fragment is destroyed, it goes through the following states:

    

onPaused() onStop() onDestroyView() onDestroy() onDetach()

How to use Fragments?
This involves number of simple steps to create Fragments.

 

First of all decide how many fragments you want to use in an activity. Fors example let's we want to use two fragments to handle landscape and portrait modes of the device. Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments. Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

 

TUTORIALS POINT Simply Easy Learning

Here is the list of important methods which you can to override in your fragment class:

  

onCreate() The system calls this when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. onCreateView() The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI. onPause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.

Example
This example will explain you how to create your own Fragments. Here we will create two fragments and one of them will be used when device is in landscape mode and another fragment will be used in case of portrait mode. So let's follow the following steps to similar to what we followed while creatingHello World Example: Step Description 1 2 3 4 5 6 7 You will use Eclipse IDE to create an Android application and name it as MyFragments under a package com.example.myfragments, with blank Activity. Modify main activity file MainActivity.java as shown below in the code. Here we will check orientation of the device and accordingly we will switch between different fragments. Create a two java files PM_Fragment.java and LM_Fragement.java under the packagecom.example.myfragments to define your fragments and associated methods. Create layouts files res/layout/lm_fragment.xml and res/layout/pm_fragment.xml and define your layouts for both the fragments.< Modify the detault content of res/layout/activity_main.xml file to include both the fragments. Define required constants in res/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.mycontentprovider/MainActivity.java: package com.example.myfragments; import import import import import import android.os.Bundle; android.app.Activity; android.app.FragmentManager; android.app.FragmentTransaction; android.content.res.Configuration; android.view.WindowManager;

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Configuration config = getResources().getConfiguration(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); /** * Check the device orientation and act accordingly

TUTORIALS POINT Simply Easy Learning

*/ if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { /** * Landscape mode of the device */ LM_Fragment ls_fragment = new LM_Fragment(); fragmentTransaction.replace(android.R.id.content, ls_fragment); }else{ /** * Portrait mode of the device */ PM_Fragment pm_fragment = new PM_Fragment(); fragmentTransaction.replace(android.R.id.content, pm_fragment); } fragmentTransaction.commit(); } } Create two files LM_Fragement.java and PM_Fragment.java undercom.example.mycontentprovider package. Following is the content of LM_Fragement.java file: package com.example.myfragments; import import import import import android.app.Fragment; android.os.Bundle; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; fragment

public class LM_Fragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * Inflate the layout for this fragment */ return inflater.inflate( R.layout.lm_fragment, container, false); } } Following is the content of PM_Fragement.java file: package com.example.myfragments; import import import import import android.app.Fragment; android.os.Bundle; android.view.LayoutInflater; android.view.View; android.view.ViewGroup;

public class PM_Fragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /**

TUTORIALS POINT Simply Easy Learning

* Inflate the layout for this fragment */ return inflater.inflate( R.layout.pm_fragment, container, false); } } Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory. Following is the content of lm_fragement.xml file: -->

TUTORIALS POINT Simply Easy Learning

android:name="com.example.fragments" android:id="@+id/lm_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> Make sure you have following content of res/values/strings.xml file: MyFragments Settings Hello world! This is Landscape mode fragment This is Portrait mode fragment Let's try to run our modified MyFragments application we just created. I assume you had created yourAVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window where you will click on Menu button to see the following window. Be patience because it may take sometime based on your computer speed:

TUTORIALS POINT Simply Easy Learning

To change the mode of the emulator screen, let's do the following:

  

fn+control+F11 on Mac to change the landscape to portrait and vice versa. ctrl+F11 on Windows. ctrl+F11 on Linux.

Once you changed the mode, you will be able to see the GUI which you have implemented for landscape mode as below:

TUTORIALS POINT Simply Easy Learning

This way you can use same activity but different GUIs through different fragments. You can use different type of GUI components for different GUIs based on your requirements.

TUTORIALS POINT Simply Easy Learning

12
Intents and Filters

CHAPTER

A

n Android Intent is an object carrying an intent ie. message from one component to another component

with-in the application or outside the application. The intents can communicate messages among any of the three core components of an application - activities, services, and broadcast receivers. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. 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. 1 Method & Description Context.startActivity() The Intent object is passed to this method to launch a new activity or get an existing activity to do something new. Context.startService() The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service. Context.sendBroadcast() The Intent object is passed to this method to deliver the message to all interested broadcast receivers.

2

3

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:

TUTORIALS POINT Simply Easy Learning

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. Here is a list of Android Intent Standard Actions

Android Intent Standard Actions:
Following table lists down various important Android Intent Standard Actions. You can check Android Official Documentation for a complete list of Actions: S.N. 1 Activity Action Intent & Description ACTION_ALL_APPS List all the applications available on the device. ACTION_ANSWER Handle an incoming phone call. ACTION_ATTACH_DATA Used to indicate that some piece of data should be attached to some other place ACTION_BATTERY_CHANGED This is a sticky broadcast containing the charging state, level, and other information about the battery. ACTION_BATTERY_LOW This broadcast corresponds to the "Low battery warning" system dialog. ACTION_BATTERY_OKAY This will be sent after ACTION_BATTERY_LOW once the battery has gone back up to an okay state. ACTION_BOOT_COMPLETED This is broadcast once, after the system has finished booting. ACTION_BUG_REPORT Show activity for reporting a bug. ACTION_CALL Perform a call to someone specified by the data. ACTION_CALL_BUTTON The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. ACTION_CAMERA_BUTTON The "Camera Button" was pressed. ACTION_CHOOSER Display an activity chooser, allowing the user to pick what they want to before proceeding. ACTION_CONFIGURATION_CHANGED The current device Configuration (orientation, locale, etc) has changed. ACTION_DATE_CHANGED The date has changed. ACTION_DEFAULT A synonym for ACTION_VIEW, the "standard" action that is performed on a piece of data.

2

3

4

5

6

7

8

9

10

11

12

13

14

15

TUTORIALS POINT Simply Easy Learning

16

ACTION_DELETE Delete the given data from its container. ACTION_DEVICE_STORAGE_LOW A sticky broadcast that indicates low memory condition on the device. ACTION_DEVICE_STORAGE_OK Indicates low memory condition on the device no longer exists. ACTION_DIAL Dial a number as specified by the data. ACTION_DOCK_EVENT A sticky broadcast for changes in the physical docking state of the device. ACTION_DREAMING_STARTED Sent after the system starts dreaming. ACTION_DREAMING_STOPPED Sent after the system stops dreaming. ACTION_EDIT Provide explicit editable access to the given data. ACTION_FACTORY_TEST Main entry point for factory tests. ACTION_GET_CONTENT Allow the user to select a particular kind of data and return it. ACTION_GTALK_SERVICE_CONNECTED A GTalk connection has been established. ACTION_GTALK_SERVICE_DISCONNECTED A GTalk connection has been disconnected. ACTION_HEADSET_PLUG Wired Headset plugged in or unplugged. ACTION_INPUT_METHOD_CHANGED An input method has been changed. ACTION_INSERT Insert an empty item into the given container. ACTION_INSERT_OR_EDIT Pick an existing item, or insert a new item, and then edit it. ACTION_INSTALL_PACKAGE Launch application installer. ACTION_LOCALE_CHANGED The current device's locale has changed. ACTION_MAIN Start as a main entry point, does not expect to receive data. ACTION_MEDIA_BUTTON The "Media Button" was pressed.

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

TUTORIALS POINT Simply Easy Learning

36

ACTION_MEDIA_CHECKING External media is present, and being disk-checked. ACTION_MEDIA_EJECT User has expressed the desire to remove the external storage media. ACTION_MEDIA_REMOVED External media has been removed. ACTION_NEW_OUTGOING_CALL An outgoing call is about to be placed. ACTION_PASTE Create a new item in the given container, initializing it from the current contents of the clipboard. ACTION_POWER_CONNECTED External power has been connected to the device. ACTION_REBOOT Have the device reboot. This is only for use by system code. ACTION_RUN Run the data, whatever that means. ACTION_SCREEN_OFF Sent after the screen turns off. ACTION_SCREEN_ON Sent after the screen turns on. ACTION_SEARCH Perform a search. ACTION_SEND Deliver some data to someone else. ACTION_SENDTO Send a message to someone specified by the data. ACTION_SEND_MULTIPLE Deliver multiple data to someone else. ACTION_SET_WALLPAPER Show settings for choosing wallpaper. ACTION_SHUTDOWN Device is shutting down. ACTION_SYNC Perform a data synchronization. ACTION_TIMEZONE_CHANGED The timezone has changed. ACTION_TIME_CHANGED The time was set. ACTION_VIEW Display the data to the user.

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

TUTORIALS POINT Simply Easy Learning

56

ACTION_VOICE_COMMAND Start Voice Command. ACTION_WALLPAPER_CHANGED The current system wallpaper has changed. ACTION_WEB_SEARCH Perform a web search.

57

58

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. 1 2 3 4 5 6 Action/Data Pair & Description ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is "1". ACTION_DIAL content://contacts/people/1 Display the phone dialer with the person filled in. ACTION_VIEW tel:123 Display the phone dialer with the given number filled in. ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is "1". ACTION_VIEW content://contacts/people/ 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. Here is a list of Android Intent Standard Categories.

Android Intent Standard Categories
Following table lists down various important Android Intent Standard Categories. You can check Android Official Documentation for a complete list of Categories: S.N. 1 Categories & Description CATEGORY_APP_BROWSER

TUTORIALS POINT Simply Easy Learning

Used with ACTION_MAIN to launch the browser application. 2 CATEGORY_APP_CALCULATOR Used with ACTION_MAIN to launch the calculator application. CATEGORY_APP_CALENDAR Used with ACTION_MAIN to launch the calendar application. CATEGORY_APP_CONTACTS Used with ACTION_MAIN to launch the contacts application. CATEGORY_APP_EMAIL Used with ACTION_MAIN to launch the email application. CATEGORY_APP_GALLERY Used with ACTION_MAIN to launch the gallery application. CATEGORY_APP_MAPS Used with ACTION_MAIN to launch the maps application. CATEGORY_APP_MARKET This activity allows the user to browse and download new applications. CATEGORY_APP_MESSAGING Used with ACTION_MAIN to launch the messaging application. CATEGORY_APP_MUSIC Used with ACTION_MAIN to launch the music application. CATEGORY_BROWSABLE Activities that can be safely invoked from a browser must support this category. CATEGORY_CAR_DOCK An activity to run when device is inserted into a car dock. CATEGORY_CAR_MODE Used to indicate that the activity can be used in a car environment. CATEGORY_DEFAULT Set if the activity should be an option for the default action (center press) to perform on a piece of data. CATEGORY_DESK_DOCK An activity to run when device is inserted into a car dock. CATEGORY_DEVELOPMENT_PREFERENCE This activity is a development preference panel. CATEGORY_EMBED Capable of running inside a parent activity container. CATEGORY_FRAMEWORK_INSTRUMENTATION_TEST To be used as code under test for framework instrumentation tests. CATEGORY_HE_DESK_DOCK An activity to run when device is inserted into a digital (high end) dock. CATEGORY_HOME This is the home activity, that is the first activity that is displayed when the device boots.

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

TUTORIALS POINT Simply Easy Learning

21

CATEGORY_INFO Provides information about the package it is in. CATEGORY_LAUNCHER Should be displayed in the top-level launcher. CATEGORY_LE_DESK_DOCK An activity to run when device is inserted into a analog (low end) dock. CATEGORY_MONKEY This activity may be exercised by the monkey or other automated test tools.

22

23

24

25

CATEGORY_OPENABLE Used to indicate that a GET_CONTENT intent only wants URIs that can be opened with ContentResolver.openInputStream.

26

CATEGORY_PREFERENCE This activity is a preference panel. CATEGORY_TAB Intended to be used as a tab inside of a containing TabActivity. CATEGORY_TEST To be used as a test (not part of the normal user experience). CATEGORY_UNIT_TEST To be used as a unit test (run through the Test Harness).

27

28

29

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. Here is a list of Android Intent Standard Extra Data

Android Intent standard Extra Data
Following table lists down various important Android Intent Standard Extra Data. You can check Android Official Documentation for a complete list of Extra Data: S.N. Extra Data & Description EXTRA_ALARM_COUNT Used as an int extra field in AlarmManager intents to tell the application being invoked how many pending alarms are being delievered with the intent. EXTRA_ALLOW_MULTIPLE Used to indicate that a ACTION_GET_CONTENT intent can allow the user to select and return multiple

1

2

TUTORIALS POINT Simply Easy Learning

items. 3 EXTRA_ALLOW_REPLACE Used as a boolean extra field with ACTION_INSTALL_PACKAGE to install a package. EXTRA_BCC A String[] holding e-mail addresses that should be blind carbon copied. EXTRA_CC A String[] holding e-mail addresses that should be carbon copied. EXTRA_CHANGED_COMPONENT_NAME_LIST This field is part of ACTION_PACKAGE_CHANGED, and contains a string array of all of the components that have changed. EXTRA_DATA_REMOVED Used as a boolean extra field in ACTION_PACKAGE_REMOVED intents to indicate whether this represents a full uninstall or a partial uninstall EXTRA_DOCK_STATE Used as an int extra field in ACTION_DOCK_EVENT intents to request the dock state. EXTRA_DOCK_STATE_CAR Used as an int value for EXTRA_DOCK_STATE to represent that the phone is in a car dock. EXTRA_DOCK_STATE_DESK Used as an int value for EXTRA_DOCK_STATE to represent that the phone is in a desk dock. EXTRA_EMAIL A String[] holding e-mail addresses that should be delivered to. EXTRA_HTML_TEXT A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text. EXTRA_INTENT An Intent describing the choices you would like shown with ACTION_PICK_ACTIVITY. EXTRA_KEY_EVENT A KeyEvent object containing the event that triggered the creation of the Intent it is in. EXTRA_LOCAL_ONLY Used to indicate that a ACTION_GET_CONTENT intent should only return data that is on the local device. EXTRA_ORIGINATING_URI Used as a URI extra field with ACTION_INSTALL_PACKAGE and ACTION_VIEW to indicate the URI from which the local APK in the Intent data field originated from. EXTRA_PHONE_NUMBER A String holding the phone number originally entered in ACTION_NEW_OUTGOING_CALL, or the actual number to call in a ACTION_CALL. EXTRA_SHORTCUT_ICON The name of the extra used to define the icon, as a Bitmap, of a shortcut. EXTRA_SHORTCUT_INTENT The name of the extra used to define the Intent of a shortcut.

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

TUTORIALS POINT Simply Easy Learning

20

EXTRA_SHORTCUT_NAME The name of the extra used to define the name of a shortcut. EXTRA_STREAM URI holding a stream of data associated with the Intent, used with ACTION_SEND to supply the data being sent. EXTRA_SUBJECT A constant string holding the desired subject line of a message. EXTRA_TEMPLATE The initial data to place in a newly created record. Use with ACTION_INSERT. EXTRA_TEXT A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent. EXTRA_TITLE A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER. EXTRA_UID Used as an int extra field in ACTION_UID_REMOVED intents to supply the uid the package had been assigned.

21

22

23

24

25

26

FLAGS
These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it after it's launched etc.

COMPONENT NAME
This optional field is an android ComponentName object representing either Activity, Service or BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated class otherwise Android uses other information in the Intent object to locate a suitable target. The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().

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

TUTORIALS POINT Simply Easy Learning

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");

Example
Following example shows the functionality of a Android Intent to launch various Android built-in applications. Step Description 1 You will use Eclipse IDE to create an Android application and name it as IntentDemo under a package com.example.intentdemo. While creating this project, make sure you Target SDKand Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/MainActivity.java file and add the code to define two listeners corresponding two buttons ie. Start Browser and Start Phone. Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. Modify res/values/strings.xml to define required constant values Run the application to launch Android emulator and verify the result of the changes done in the aplication.

2 3 4 5

Following is the content of the modified main activity filesrc/com.example.intentdemo/MainActivity.java. package com.example.intentdemo; import import import import import import import android.net.Uri; android.os.Bundle; android.app.Activity; android.content.Intent; android.view.Menu; android.view.View; android.widget.Button;

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) {

TUTORIALS POINT Simply Easy Learning

super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBrowser = (Button) findViewById(R.id.start_browser); startBrowser.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.example.com")); startActivity(i); } }); Button startPhone = (Button) findViewById(R.id.start_phone); startPhone.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel:9510300000")); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action // bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content of res/layout/activity_main.xml file: Following will be the content of res/values/strings.xml to define two new constants: Start Phone

TUTORIALS POINT Simply Easy Learning

Following is the default content of AndroidManifest.xml: Let's try to run your IntentDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Now click on Start Browser button, which will start a browser configured and display http://www.example.com as shown below:

TUTORIALS POINT Simply Easy Learning

Similar way you can launch phone interface using Start Phone button, which will allow you to dial already given phone number.

Intent Filters
You have seen how an Intent has been used to call an another activity. Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. You will use element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver. Following is an example of a part of AndroidManifest.xml file to specify an activitycom.example.intentdemo.CustomActivity which can be invoked by either of the two mentioned actions, one category, and one data: Once this activity is defined along with above mentioned filters, other activities will be able to invoke this activity using either the android.intent.action.VIEW, or using the com.example.intentdemo.LAUNCHaction provided their category is android.intent.category.DEFAULT. The element specifies the data type expected by the activity to be called and for above example our custom activity expects the data to start with the "http://" There may be a situation that an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. An exception is raised if no target can be found.

TUTORIALS POINT Simply Easy Learning

There are following test Android checks before invoking an activity:



A filter may list more than one action as shown above but this list cannot be empty; a filter must contain at least one element, otherwise it will block all intents. If more than one actions are mentioned then Android tries to match one of the mentioned actions before invoking the activity. A filter may list zero, one or more than one categories. if there is no category mentioned then Android always pass this test but if more than one categories are mentioned then for an intent to pass the category test, every category in the Intent object must match a category in the filter. Each element can specify a URI and a data type (MIME media type). There are separate attributes like scheme, host, port, and path for each part of the URI. An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter.





Example
Following example is a modification of the above example. Here we will see how Android resolves conflict if one intent is invoking two activities defined in , next how to invoke a custom activity using a filter and third one is an exception case if Android does not file appropriate activity defined for an intent. Step Description 1 You will use Eclipse IDE to create an Android application and name it as IntentDemo under a package com.example.intentdemo. While creating this project, make sure you Target SDKand Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/MainActivity.java file and add the code to define three listeners corresponding to three buttons defined in layout file. Add a new src/CustomActivity.java file to have one custom activity which will be invoked by different intents. Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. Add one layout XML file res/layout/custom_view.xml to add a simple to show the passed data through intent. Modify res/values/strings.xml to define required constant values Modify AndroidManifest.xml to add to define rules for your intent to invoke custom activity. Run the application to launch Android emulator and verify the result of the changes done in the aplication.

2 3 4 5 6 7 8

Following is the content of the modified main activity filesrc/com.example.intentdemo/MainActivity.java. package com.example.intentdemo; import import import import import import import android.net.Uri; android.os.Bundle; android.app.Activity; android.content.Intent; android.view.Menu; android.view.View; android.widget.Button;

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

TUTORIALS POINT Simply Easy Learning

setContentView(R.layout.activity_main); // First intent to use ACTION_VIEW action with correct data Button startBrowser_a = (Button) findViewById(R.id.start_browser_a); startBrowser_a.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.example.com")); startActivity(i); } }); // Second intent to use LAUNCH action with correct data Button startBrowser_b = (Button) findViewById(R.id.start_browser_b); startBrowser_b.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse("http://www.example.com")); startActivity(i); } }); // Third intent to use LAUNCH action with incorrect data Button startBrowser_c = (Button) findViewById(R.id.start_browser_c); startBrowser_c.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse("https://www.example.com")); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Following is the content of the modified main activity filesrc/com.example.intentdemo/CustomActivity.java. package com.example.intentdemo; import import import import android.app.Activity; android.net.Uri; android.os.Bundle; android.widget.TextView;

public class CustomActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_view); TextView label = (TextView) findViewById(R.id.show_data);

TUTORIALS POINT Simply Easy Learning

Uri url = getIntent().getData(); label.setText(url.toString()); } } Following will be the content of res/layout/activity_main.xml file: Following will be the content of res/layout/custom_view.xml file: Following will be the content of res/values/strings.xml to define two new constants: Exception Condition

Following is the default content of AndroidManifest.xml:

TUTORIALS POINT Simply Easy Learning

Let's try to run your IntentDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

TUTORIALS POINT Simply Easy Learning

Now let's start with first button "Start Browser with VIEW Action". Here we have defined our custom activity with a filter "android.intent.action.VIEW", and there is already one default activity against VIEW action defined by Android which is launching web browser, So android displays following two options to select the activity you want to launch.

TUTORIALS POINT Simply Easy Learning

Now if you select Browser, then Android will launch web browser and open example.com website but if you select IndentDemo option then Android will launch CustomActivity which does nothing but just capture passed data and displays in a text view as follows:

TUTORIALS POINT Simply Easy Learning

Now go back using back button and click on "Start Browser with LAUNCH Action" button, here Android applies filter to choose define activity and it simply launch your custom activity and again it displays following screen:

Again, go back using back button and click on "Exception Condition" button, here Android tries to find out a valid filter for the given intent but it does not find a valid activity defined because this time we have used data as https instead of http though we are giving a correct action, so Android raises an exception and shows following screen:

TUTORIALS POINT Simply Easy Learning

13
UI Layouts

CHAPTER

T

he 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 usingView/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:

TUTORIALS POINT Simply Easy Learning

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 1 2 3 4 5 6 7 Linear Layout LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. Relative Layout RelativeLayout is a view group that displays child views in relative positions. Table Layout TableLayout is a view that groups views into rows and columns. Absolute Layout AbsoluteLayout enables you to specify the exact location of its children. Frame Layout The FrameLayout is a placeholder on screen that you can use to display a single view. List View ListView is a view group that displays a list of scrollable items. Grid View GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Linear Layout
Android LinearLayout is a view group that aligns all children in a single direction, vertically orhorizontally.

LinearLayout Attributes
Following are the important attributes specific to LinearLayout: Attribute android:id android:baselineAligned android:divider android:gravity android:orientation Description This is the ID which uniquely identifies the layout. This must be a boolean value, either "true" or "false" and prevents the layout from aligning its children's baselines. This is drawable to use as a vertical divider between buttons. You use a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. This specifies the direction of arrangmet and you will use "horizontal" for a row, "vertical" for a column. The default is horizontal.

Example
This example will take you through simple steps to show how to create your own Android application using Linear Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description

TUTORIALS POINT Simply Easy Learning

1 2 3 4

You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify the detault content of res/layout/activity_main.xml file to include few buttons in linear layout. Define required constants start_service, pause_service and stop_service inres/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.helloworld/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content of res/layout/activity_main.xml file: 100dp 38dp characters monospace 1.2 1.2 2 #494948/> center 3dp 5pt #000000 Following will be the content of res/layout/activity_main.xml file: of res/values/style.xml file which will have addition

TUTORIALS POINT Simply Easy Learning

Following will be the content of res/values/strings.xml to define two new constants: StyleDemo Settings Hello world! Small Font Large Font Following is the default content of AndroidManifest.xml:

TUTORIALS POINT Simply Easy Learning

Let's try to run your StyleDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. Its simple, to create a new style LargeFont that inherits the CustomFontStyle style defined above, but make the font size big, you can author the new style like this: 20ps You can reference this new style as @style/CustomFontStyle.LargeFont in your XML Layout file. You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend FontStyle.LargeFont to be Red, with: #FF0000/>

TUTORIALS POINT Simply Easy Learning

This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference an Android built-in style, such as TextAppearance, you must use the parent attribute as shown below: fill_parent wrap_content characters monospace 12pt #00FF00/>

Android Themes
Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font. To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the tag to include the android:theme attribute with the style name. For example: But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the tag only. For example: There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows: ... To understand the concept related to Android Theme, you can check Theme Demo Example given below:

TUTORIALS POINT Simply Easy Learning

Following example demonstrates how you can use a theme for an application. For demo purpose we will modify our default AppTheme wehere default text, its size, family, shadow etc will be changed. Let's start with creating a simple Android application as per the following steps: Step 1 2 3 Description You will use Eclipse IDE to create an Android application and name it as ThemeDemo under a package com.example.themedemo as explained in the Hello World Example chapter. Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined. Define your style in global style file res/values/style.xml to define custom attributes for a button and change default theme of the application to play with the text. Modify the detault content of res/layout/activity_main.xml file to include a set of Android UI controls and make use of the defined style. Define required constants in res/values/strings.xml file Run the application to launch Android emulator and verify the result of the changes done in the aplication.

4 5 6

Following is the content of the modified main activity filesrc/com.example.themedemo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.themedemo; import import import import import import android.os.Bundle; android.app.Activity; android.view.Menu; android.view.View; android.widget.Button; android.widget.TextView;

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //--- find both the buttons--Button sButton = (Button) findViewById(R.id.button_s); Button lButton = (Button) findViewById(R.id.button_l); // -- register click event with first button --sButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // --- find the text view -TextView txtView = (TextView) findViewById(R.id.text_id); // -- change text size -txtView.setTextSize(20); } }); // -- register click event with second button --lButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // --- find the text view -TextView txtView = (TextView) findViewById(R.id.text_id); // -- change text size --

TUTORIALS POINT Simply Easy Learning

txtView.setTextSize(24); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content styleCustomButtonStyle defined: characters monospace 1.2 1.2 2 #494948/> center 3dp 5pt #000000 100dp 38dp Following will be the content of res/layout/activity_main.xml file: Following will be the content of res/values/strings.xml to define two new constants: ThemeDemo Settings Hello world! Small Font Large Font Following is the default content of AndroidManifest.xml. Here we do not need to change anything because we kept out theme name unchanged. But if you define fresh new theme or inherit a default them with different name then you will have to replace AppTheme name with the new them name.

TUTORIALS POINT Simply Easy Learning

Let's try to run your ThemeDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Default Styles & Themes
The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with "@android:style/Theme.NoTitleBar". You can see the following source code for Android styles and themes:

 

Android Styles (styles.xml) Android Themes (themes.xml)

TUTORIALS POINT Simply Easy Learning

17
Custom Components

CHAPTER

A

ndroid offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox,

RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element. This tutorial explains you how to create custom Views and use them in your application using simple and easy steps.

Creating a Simple Custom Component
The simplest way to create your custom component is to extend an existing widget class or subclass with your own class if you want to extend the functionality of existing widget like Button, TextView, EditText, ListView, CheckBox etc. otherwise you can do everything yourself by starting with theandroid.view.View class. At its simplest form you will have to write your constructors corresponding to all the constructors of the base class. For example if you are going to extend TextView to create a DateView then following three constructors will be created for DateView class: public class DateView extends TextView { public DateView(Context context) { super(context); //--- Additional custom code -}

public DateView(Context context, AttributeSet attrs) { super(context, attrs); //--- Additional custom code --

TUTORIALS POINT Simply Easy Learning

}

public DateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //--- Additional custom code -} } Because you have created DateView as child of TextView so it will have access on all the attributes, methods and events related to TextView and you will be able to use them without any further implementation. You will implement additional custom functionality inside your own code as explained in the given examples below. If you have requirement for implementing custom drawing/sizing for your custom widgets then you need to override onMeasure(int widthMeasureSpec, int heightMeasureSpec) and onDraw(Canvas canvas) methods. If you are not going to resize or change the shape of your built-in component then you do not need either of these methods in your custom component. The onMeasure() method coordinate with the layout manager to report the widget's width and height, and you need to call setMeasuredDimension(int width, int height) from inside this method to report the dimensions. You can then execute your custom drawing inside the onDraw(Canvas canvas) method, where android.graphis.Canvas is pretty similar to its counterpart in Swing, and has methods such as drawRect(), drawLine(), drawString(), drawBitmap() etc. which you can use to draw your component. Once you are done with the implementation of a custom component by extending existing widget, you will be able to instantiate these custom components in two ways in your application development:

INSTANTIATE USING CODE INSIDE ACTIVITY CLASS
It is very similar way of instantiating custom component the way you instantiate built-in widget in your activity class. For example you can use following code to instantiate above defined custom component: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

DateView dateView = new DateView(this); setContentView(dateView); } Check this below given example to understand how to Instantiate a Basic Android Custom Component using code inside an activity:

Instantiate a Basic Android Custom Component(using code)
Following example shows you how to define a simple Android custom component and then how to instantiate it inside activity code without using layout file. Step Description

TUTORIALS POINT Simply Easy Learning

1 2 3 4

You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. Create src/DateView.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. Modify src/MainActivity.java file and add the code to create DateView instance and usesetContentView() method to set it in the layout. Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date: package com.example.dateviewdemo; import java.text.SimpleDateFormat; import java.util.Calendar; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; public class DateView extends TextView { public DateView(Context context) { super(context); setDate(); } public DateView(Context context, AttributeSet attrs) { super(context, attrs); setDate(); } public DateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setDate(); } private void setDate() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); String today = dateFormat.format(Calendar.getInstance().getTime()); setText(today); // self = DateView is a subclass of TextView } } Following is the content of the modified main activity filesrc/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

TUTORIALS POINT Simply Easy Learning

setContentView(R.layout.activity_main); //-- Create DateView instance and set it in layout. DateView dateView = new DateView(this); setContentView(dateView); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content of res/layout/activity_main.xml file: Following will be the content of res/values/strings.xml to define two new constants: DateViewDemo Settings Hello world! Following is the default content of AndroidManifest.xml:

TUTORIALS POINT Simply Easy Learning

Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

INSTANTIATE USING LAYOUT XML FILE
Traditionally you use Layout XML file to instantiate your built-in widgets, same concept will apply on your custom widgets as well so you will be able to instantiate your custom component using Layout XML file as explained below. Here com.example.dateviewdemo is the package where you have put all the code related to DateView class and DateView is Java class name where you have put complete logic of your custom component.

It is important to note here that we are using all TextView attributes along with custom component without any change. Similar way you will be able to use all the events, and methods along with DateView component. Check this example to understand how to Instantiate a Basic Android Custom Component using Layout XML file.

Instantiate a Basic Android Custom Component (using Layout XML file)
Following example shows you how to define a simple Android custom component and then how to instantiate it inside activity code without using layout file. Step Description 1 2 3 4 You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. Create src/DateView.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes. Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date: package com.example.dateviewdemo;

import java.text.SimpleDateFormat; import java.util.Calendar;

TUTORIALS POINT Simply Easy Learning

import android.content.Context; import android.util.AttributeSet; import android.widget.TextView;

public class DateView extends TextView { public DateView(Context context) { super(context); setDate(); }

public DateView(Context context, AttributeSet attrs) { super(context, attrs); setDate(); }

public DateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setDate(); }

private void setDate() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); String today = dateFormat.format(Calendar.getInstance().getTime()); setText(today); } // self = DateView is a subclass of TextView

} Following is the content of the modified main activity filesrc/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo;

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

TUTORIALS POINT Simply Easy Learning

import android.view.Menu;

public class MainActivity extends Activity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content of res/layout/activity_main.xml file:

Following will be the content of res/values/strings.xml to define two new constants:

DateViewDemo Settings Hello world!

Following is the default content of AndroidManifest.xml:

Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Custom Component with Custom Attributes
We have seen how we can extend functionality of built-in widgets but in both the examples given above we saw that extended component can make use of all the default attributes of its parent class. But consider a situation when you want to create your own attribute from scratch. Below is a simple procedure to create and use new attributes for Android Custom components. Consider we want to introduce three attributes and will use them as shown below:

STEP 1
The first step to enable us to use our custom attributes is to define them in a new xml file underres/values/ and call it attrs.xml. Let's have a look on an example attrs.xml file: Here the name=value is what we want to use in our Layout XML file as attribute, and the format=type is the type of attribute.

STEP 2
Your second step will be to read these attributes from Layout XML file and set them for the component. This logic will go in the constructors that get passed an AttributeSet, since that is what contains the XML attributes. To read the values in the XML, you need to first create a TypedArray from theAttributeSet, then use that to read and set the values as shown in the below example code: TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView);

final int N = a.getIndexCount(); for (int i = 0; i < N; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.DateView_delimiter: String delimiter = a.getString(attr); //...do something with delimiter... break; case R.styleable.DateView_fancyText: boolean fancyText = a.getBoolean(attr, false);

TUTORIALS POINT Simply Easy Learning

//...do something with fancyText... break; } } a.recycle();

STEP 3
Finally you can use your defined attributes in your Layout XML file as follows:

The important part isxmlns:custom="http://schemas.android.com/apk/res/com.example.dateviewdemo". Note thathttp://schemas.android.com/apk/res/ will remain as is, but last part will be set to your package name and also that you can use anything after xmlns:, in this example I used custom, but you could use any name you like. Check this below given example to understand how to Create Custom Attributes for Android Custom Componentwith simple steps.

Create Custom Attributes for Android Custom Component
TUTORIALS POINT Simply Easy Learning

Following example shows you how to define a simple Android custom component with custom attributes. Step Description 1 2 3 You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. Create an XML res/values/attrs.xml file to define new attributes alongwith their data type. Create src/DateView.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. You will provide attributes parsing logic in of the constructors having AttributeSet as a parameter. Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes and new attributes. Run the application to launch Android emulator and verify the result of the changes done in the aplication.

4 5

Following is the content of the modified main activity filesrc/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } Following will be the content of res/values/attrs.xml file: Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date: package com.example.dateviewdemo;

TUTORIALS POINT Simply Easy Learning

import java.text.SimpleDateFormat; import java.util.Calendar; import import import import import import android.content.Context; android.content.res.TypedArray; android.graphics.Color; android.util.AttributeSet; android.util.Log; android.widget.TextView;

public class DateView extends TextView { public String delimiter; public boolean fancyText; public DateView(Context context) { super(context); setDate(); } public DateView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView ); final int N = a.getIndexCount(); for (int i = 0; i < N; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.DateView_delimiter: delimiter = a.getString(attr); setDate(); break; case R.styleable.DateView_fancyText: fancyText = a.getBoolean(attr, false); fancyText(); break; } } a.recycle(); } public DateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setDate(); } private void setDate() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy" + delimiter + "MM" + delimiter + "dd"); String today = dateFormat.format(Calendar.getInstance().getTime()); setText(today); // self = DateView = subclass of TextView } private void fancyText() { if( this.fancyText){ setShadowLayer(9, 1, 1, Color.rgb(44, 44, 40)); } }

TUTORIALS POINT Simply Easy Learning

} Following will be the content of res/layout/activity_main.xml file: Following will be the content of res/values/strings.xml to define two new constants: DateViewDemo Settings Hello world! Following is the default content of AndroidManifest.xml:

TUTORIALS POINT Simply Easy Learning

Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

8 9 10 11 12 13 14 15 16

NotificationCompat.Builder setDefaults (int defaults) Set the default notification options that will be used. NotificationCompat.Builder setLargeIcon (Bitmap icon) Set the large icon that is shown in the ticker and notification. NotificationCompat.Builder setNumber (int number) Set the large number at the right-hand side of the notification. NotificationCompat.Builder setOngoing (boolean ongoing) Set whether this is an ongoing notification. NotificationCompat.Builder setSmallIcon (int icon) Set the small icon to use in the notification layouts. NotificationCompat.Builder setStyle (NotificationCompat.Style style) Add a rich notification style to be applied at build time. NotificationCompat.Builder setTicker (CharSequence tickerText) Set the text that is displayed in the status bar when the notification first arrives. NotificationCompat.Builder setVibrate (long[] pattern) Set the vibration pattern to use. NotificationCompat.Builder setWhen (long when) Set the time that the event occurred. Notifications in the panel are sorted by this time.

TUTORIALS POINT Simply Easy Learning

Example
Following example shows the functionality of a Android notification using a NotificationCompat.BuilderClass which has been introduced in Android 4.1. Step Description 1 You will use Eclipse IDE to create an Android application and name it as NotificationDemounder a package com.example.notificationdemo. While creating this project, make sure youTarget SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/MainActivity.java file and add the code to define three methods startNotification(), cancelNotification() and updateNotification() to cover maximum functionality related to Android notifications. Create a new Java file src/NotificationView.java, which will be used to display new layout as a part of new activity which will be started when user will click any of the notifications Copy image woman.png in res/drawable-* folders and this image will be used as Notification icons. You can use images with different resolution in case you want to provide them for different devices. Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. Create a new layout XML file res/layout/notification.xml. This will be used as layout file for new activity which will start when user will click any of the notifications. Modify res/values/strings.xml to define required constant values Run the application to launch Android emulator and verify the result of the changes done in the aplication.

2 3 4 5 6 7 8

Following is the content of the modified main activity filesrc/com.example.notificationdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.notificationdemo; import import import import import import import import import import import android.os.Bundle; android.app.Activity; android.app.NotificationManager; android.app.PendingIntent; android.app.TaskStackBuilder; android.content.Context; android.content.Intent; android.support.v4.app.NotificationCompat; android.util.Log; android.view.View; android.widget.Button;

public class MainActivity extends Activity { private NotificationManager mNotificationManager; private int notificationID = 100; private int numMessages = 0; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBtn = (Button) findViewById(R.id.start); startBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayNotification(); } });

TUTORIALS POINT Simply Easy Learning

Button cancelBtn = (Button) findViewById(R.id.cancel); cancelBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { cancelNotification(); } }); Button updateBtn = (Button) findViewById(R.id.update); updateBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { updateNotification(); } }); } protected void displayNotification() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message."); mBuilder.setTicker("New Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID, mBuilder.build()); } protected void cancelNotification() { Log.i("Cancel", "notification"); mNotificationManager.cancel(notificationID); } protected void updateNotification() { Log.i("Update", "notification");

TUTORIALS POINT Simply Easy Learning

/* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("Updated Message"); mBuilder.setContentText("You've got updated message."); mBuilder.setTicker("Updated Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* Update the existing notification using same notification ID */ mNotificationManager.notify(notificationID, mBuilder.build()); } } Following is the content of the filesrc/com.example.notificationdemo/NotificationView.java. package com.example.notificationdemo; import android.os.Bundle; import android.app.Activity; public class NotificationView extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification); } } Following will be the content of res/layout/activity_main.xml file: modified main activity

TUTORIALS POINT Simply Easy Learning

Following will be the content of res/layout/notification.xml file: Following will be the content of res/values/strings.xml to define two new constants: Update Notification

Following is the default content of AndroidManifest.xml: Let's try to run your NotificationDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Now click Start Notification button, you will see at the top a message "New Message Alert!" will display momentarily and after that you will have following screen having a small icon at the top left corner.

TUTORIALS POINT Simply Easy Learning

Now lets expand the view, long click on the small icon, after a second it will display date information and this is the time when you should drag status bar down without releasing mouse. You will see status bar will expand and you will get following screen:

Now let's try to click on the image icon, this will launch your new activity which you have set using intent and you will have following screen:

TUTORIALS POINT Simply Easy Learning

Next, you can click on "Detail of notification" and it will take you back to the main screen where you can try using Update Notification button which will update existing notification and number will increase by 1 but if you will send notification with new notification ID then it will keep adding in the stack and you see them separately listed on the screen.

Big View Notification
The following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style. I'm going to update displayNotification() modification method to show this functionality: protected void displayNotification() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message."); mBuilder.setTicker("New Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Add Big View Specific Configuration */ NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events events[0] = new events[1] = new events[2] = new events[3] = new events[4] = new events[5] = new = new String[6]; String("This is first line...."); String("This is second line..."); String("This is third line..."); String("This is 4th line..."); String("This is 5th line..."); String("This is 6th line...");

// Sets a title for the Inbox style big view inboxStyle.setBigContentTitle("Big Title Details:"); // Moves events into the big view

TUTORIALS POINT Simply Easy Learning

for (int i=0; i < events.length; i++) { inboxStyle.addLine(events[i]); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID, mBuilder.build()); } Now if you will try to run your application then you will find following result in expanded form of the view:

TUTORIALS POINT Simply Easy Learning

Similar Documents

Premium Essay

Android Tutorial

...1 Android 3.0 User’s Guide February 23, 2011 AUG-3.0-100 Android™ mobile technology platform 3.0 AUG-3.0-100 Android User’s Guide 2 Legal Copyright © 2011 Google Inc. All rights reserved. Google, the stylized Google logo, Android, the stylized Android logo, Nexus, the stylized Nexus logo, Nexus S, the stylized Nexus S logo, Android Market, the stylized Android Market logo, Gmail, Google Apps, Google Calendar, Google Checkout, Google Earth, Google Latitude, Google Maps, Google Talk, Picasa, SafeSearch, and YouTube are trademarks of Google Inc. All other company and product names may be trademarks of the companies with which they are associated. Availability of Google applications, services, and features may vary by country, carrier, Android device model, and manufacturer. AUG-3.0-100 Android User’s Guide 3 Contents About this guide 5 Starting Android the first time 7 Welcome to Android! 8 Activating your mobile data service 9 Setting your location preferences 10 Signing into your Google Account 11 Resetting your Google Account password 12 Additional accounts 12 Backing up and restoring your data 13 Finishing setup 15 Working with widgets 34 Optimizing battery life 35 Working with apps 37 Opening and switching apps 38 Managing how apps use memory 40 Managing downloads 44 Entering and editing text 45 Using the onscreen keyboard 46 Entering text by speaking 50 Editing text 52 Home and Android basics 17 Getting to know Home 18 Using the...

Words: 25338 - Pages: 102

Free Essay

Android Development for Beginners

...1.Android - Overview What is Android? Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2. Why Android ? Features of Android Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below: Feature | Description | Beautiful UI | Android OS basic screen provides a beautiful and intuitive user interface. | Connectivity | GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE...

Words: 798 - Pages: 4

Free Essay

Android Based Webstatic Server

...Project Report On ANDROID BASED STATIC WEBSERVER BY CONTENTS TITLE ABSTRACT INTRODUCTION…………………………………………………. 1 Purpose……………………………………………………..………… 1.1 Scope…………………………………………………..…….……….. 1.2 Definitions, Acroynms, Abbrivations……………………. 1.3 Overview……………………..………………………………………. 1.4 SYSTEM ANALYSIS……………………………………… 3 Software Requirements Specification…..………………. 3.1 Hardware Requirements……………………………………….. 3.1.1 Software Requirements………………………………………… 3.1.2 IMPLEMENTATION……………………………………… 4 Modules……………………………………………………………….. 4.1 Accounts…………………………………………………………..4.1.1 Transactions………………………………………………………….. 4.1.2 DESIGN………………..…………………………….……… 5 UML Diagrams………………………………………………………… 5.1 Class Diagram………………………………………………………… 5.1.1 Usecase Diagram….……………………………………………….. 5.1.2 Sequence Diagram….……………………………………………….. 5.1.3 RESULT FOR IMPLEMENTATION…………………… 6 Output Screens………………………………………………………. 6.1 SYSTEM TESTING………………………………………….7 Types of Testing………………………………………………………. 7.1 TESTCASES…………………………………………………..8 CONCLUSION………………………………………………..9 ANDROID BASED STATIC WEBSERVER ABSTRACT Android is software platform and operating system for mobile devices. Being an open-source, it is based on the Linux kernel. It was developed by Google and later the Open Handset Alliance (OHA). It allows writing managed code in the Java language. Due to Android here is the possibility...

Words: 9090 - Pages: 37

Free Essay

Phcare

...College Biñan In Partial Fulfillment Of the Requirements for the Degree of Bachelor of Science of Computer Engineering Biñan, Laguna December, 2014 Table of Contents Title Page i List of Figures ii List of Tables iii CHAPTER I I. INTRODUCTION 6 Background of the Study 6 Conceptual Framework 8 Statement of the Problem 9 Objectives of the Study 10 Significance of the Study 11 Scope and Limitation 11 Definition of Terms 12 Conceptual Definition 12 Operational Definition 14 CHAPTER II II. REVIEW OF RELATED LITERATURES AND STUDIES 15 Related Literatures 15 Mobile Health Monitoring 15 Biomedical Sensors 16 Android 15 Wireless Technology 22 Interfacing UART 30 Arduino 33 Related Studies 37 Foreign Studies 37 Local Studies 39 Synthesis 40 CHAPTER III III. RESEARCH METHODOLOGY 41 Research Design 42 Respondents of the Study 43 Sampling Design and Techniques 44 Research Instruments 45 Sources of Data 45 Data Gathering Procedures 45 Statistical Treatment 46 System Design 47 System Overview 47 System Block Diagram 49 System Schematic Diagram 52 Material Listing and Specification 56 Hardware Component Design 62 Hardware Program Design 68 Software Design 70 Implementation 75 Project Timeline...

Words: 12900 - Pages: 52

Premium Essay

Mobile Application Security

...rather than from behind corporate firewalls and intrusion-protection systems. Security of mobile devices focuses on controlling access through the use of device locks and hardware data encryption. While this may be sufficient for individual users, it is insufficient for defense needs. Many documented examples exist of hacking of the device lock, as well as defeats of the hardware-level encryption. Once the device is unlocked, there is generally unfettered access to all apps and their associated data. Military applications require additional application-level access controls to provide data security. Unfortunately, there are gaps in the application-level security model of the two predominant mobile operating systems: iOS from Apple and Google Android. Our ongoing research1 looks to address these gaps by developing innovative approaches for fine-grained data protection and access control, taking into account mobile device usage patterns, device characteristics, and usability. Mobile Applications Security Threat Vectors Many threat vectors for infecting personal computers arise from social-engineering attacks that bypass anti-virus defenses. Similar techniques are used in the smartphone and tablet world by...

Words: 4009 - Pages: 17

Premium Essay

Shakespere

...ALERT SYSTEM FOR INDIAN FISHERMAN IN ANDROID PLATFORM Ms.P.Selvi Grija1, T.Preethi2, V.Ranjitha3, R.Vinothini4 Assistant Professor, CSE, Christ College of Engg&Tech, Pondicherry, India 1 Student, CSE, Christ College of Engg&Tech, Pondicherry, India2 Student, CSE, Christ College of Engg&Tech, Pondicherry, India 3 Student, CSE, Christ College of Engg&Tech, Pondicherry, India 4 Abstract: The main aim is to give a well understandable user friendly environment for Indian Fisherman to handle hazardous situation with the help of modern technology gadgets. One of the huge problems faced by Indian Fisherman is being threatened by neighbor country coastal guards for crossing IMBL. This is because of lack in knowledge of position system. This paper comes with a reliable solution for this problem and protects the Indian fisherman from dangerous situation and being crossing the maritime boundary and save their life and improve the safety of fisherman. This made possible by developing an application in Android Mobile OS which is feeded in mobile computing smartphone device. The application uses the information of smartphone inbuilt GPS & GSM module. For positioning and give alert messages to base stations, friends & family. Keeping the lives of Fisherman in mind, this system has been developed to help them not to move beyond Indian Boundaries. On the whole it’s an attempt to build a suitable device for fisherman at low cost & user friendly. Keywords: Android, Mobile Computing, Smartphones, GSM...

Words: 2085 - Pages: 9

Premium Essay

Harshit

...tools and runtimes for building, deploying and managing software across the lifecycle. The Eclipse Project was originally created by IBM in November 2001. The vast majority of Android apps owe their existence to Eclipse. It is an open source IDE (integrated development environment) for Java projects (and more). Basically, the place where the application software is crafted is supported through various stages of its lifecycle. Google officially supports it, and has created the Android Development Tools plug-in for Eclipse and integrated its AVD Manager virtual device management into the tool as well. SDK The Android SDK (software development kit) is a set of development tools used to develop applications for Android platform. The Android SDK includes the following: * Required libraries * Debugger * An emulator * Relevant documentation for the Android application program interfaces (APIs) * Sample source code * Tutorials for the Android OS Every time Google releases a new version of Android, a corresponding SDK is also released. To be able to write programs with the latest features, developers must download and install each version’s SDK for the particular phone.  Emulator The emulator lets you prototype, develop and test Android applications without using a physical device. The Android emulator mimics all of the hardware and software features of a typical mobile device, except that it cannot place actual phone calls. It provides a variety of navigation and control...

Words: 1324 - Pages: 6

Free Essay

Wp7 for Android

...Microsoft6/6/2011Rev 1.0 | | Windows Phone 7 Guide for Android Application Developers | | About this Document 4 Target Audience 4 Conventions Used in this Document 4 Chapter 1: Introducing Windows Phone 7 Platform to Android Application Developers 5 The Developer Tools 5 Windows Phone 7 Architecture 5 Comparing the Programming Stack of Windows Phone 7 with Android 7 Summary 11 Related Resources 11 Chapter 2: User Interface Guidelines 12 Designing the Application Interface 13 Application User Interface Design 14 Comparing Windows Phone 7 and Android Navigation 18 Windows Phone 7 Frame and Page Structure 19 Application Templates 21 Summary 21 Related Resources 21 Chapter 3: The Developer and Designer Tools 23 A Comparison of Android and Windows Phone 7 Tools 23 Development Life Cycle and Windows Phone 7 Developer Tools 24 The UI Design Tools 26 Building Applications 33 Debugging 34 Summary 38 Chapter 4: C# programming 39 Managed Programming 40 A Comparison between C# Features and Java Classes 41 A Comparison of Important Class Libraries 51 The New features of C# 54 Comparing API Documentation Tools 58 NDoc 58 NDocs vs. Javadoc 61 Summary 61 Related Resources 62 Chapter 5: A Comparison of Application Life Cycles in Windows Phone 7 and Android 63 Multitasking in Android and Windows Phone 7 63 Tombstoning of Applications in Windows Phone 7 64 Life Cycle of a Windows Phone 7 Application...

Words: 19181 - Pages: 77

Free Essay

Android

...Android operating system revolution in mobile technology Published: 23, March 2015 Android (Operating System) - Revolution in Mobile Technology Abstract Android's mobile operating system is based on the Linux kernel and it is a software stack for mobile devices. This operating system is one of the world's best-selling Smartphone platform. Android involves many developers writing applications that helps in extended the functionality of the devices. There are currently over 1,50,000 applications available for Android. Android Market is the online application store run by Google, though applications can also be downloaded from third-party sites. Developers write in the Java language. The unveiling of the Android distribution on 5 November 2007 was announced with the founding of the Open Handset Alliance, a consortium of 80 hardware, software, and telecom companies devoted to advancing open standards for mobile devices. Most of the Android code is released by Google under the Apache License. The Android open-source software stack consists of Java applications running on a Java-based, object-oriented applicationlication framework on top of Java core libraries . Libraries written in C include SQLite relational database management system, WebKit layout engine, SGL graphics engine, SSL. The Android operating system, including the Linux kernel, consists of roughly 12million lines of code including 3million lines of XML, 2.8million lines of C, 2.1million lines of Java, and 1.75million lines...

Words: 1342 - Pages: 6

Free Essay

Reco

...the play store ? Then this blog post is for you. This will help you decide whether it is safe to import nexus 4 from outside India. If you want to buy a nexus 4, read my article on how to buy nexus 4 in india. Does Nexus 4 work well on Indian SIM cards ? Yes it does. See the screenshot below which shows Nexus 4 running on Airtel prepaid sim. But the only catch is that it requires you to have a micro sim .. just like iPhones and iPads. Its easy to ask your connection providers like Idea, BSNL etc to provide you a new micro sim with the same number, but if you are impatient, you could as well cut out your regular sized sim card to micro sim. This is what I did with my Airtel sim and it works without a glitch. There are loads of tutorials which help you in cutting your sim, in addition to that you can buy a cheap micro sim cutter from ebay for 150 bucks. I personally used a micro sim template (a print out which helps you cut your sim), and it need not be a perfect cut for the sim to work. Nexus 4 works well on both 3G and 2G bands on all India mobile service providers, although it is incompatible with the upcoming Airtel 4g postpaid connections. The call quality is good and I have never experienced call drops on nexus. Can Nexus 4 download India-only apps from...

Words: 2914 - Pages: 12

Premium Essay

College Homework Help

...COLLEGE HOMEWORK HELP Through college homework help, we aim to provide you with all necessary material and solution you require for the understanding of whole of your college’s curriculum. If you are searching for homework help from experts who are well-read in the subjects of mathematics, calculus, statistics and algebra you have come to right place. All scholars are verified degree holders who have years of experience helping students with their maths, accountancy and English problems. Here you can submit anything from simple queries to complex or lengthy assignments and receive expert guidance to help you develop fully-worked solutions. We can assist with any type of project - homework assignments, practice questions, laboratory write-ups, and more. Every subject has its own characteristics like English you need to learn writing skills and in maths you need to learn formulae but every subject demands a single similar thing that is dedication and if you are dedicated to actually learn a subject our experts are equally dedicated to teach you that. Generally, classroom lectures are not enough for the student to be able to cope up with the complexities of problems given for homework, and that is why additional homework help is so essential. College homework help provided by expert and qualified tutors has been always proved to be of immense help and has often been back bone support for students who do well in class. Having problems with your homework or feeling too lazy to figure...

Words: 404 - Pages: 2

Premium Essay

Psy Tut 1

...        PSY1004F/PSY1006F Work piece 3 Biopsychology and Memory Name & Surname:       Student Number:                    Tutorial group:                  Tutor:                      Date:         _________________________________________________________________________________________________ 1. There are a number of clients at the Shady Pines Nursing Home who have suffered neurological damage. Given the limited, and admittedly oversimplified, information provided in your handbook about the patients at Shady Pines Nursing Home, make an educated guess as to the part of the brain that has been damaged. a. Anna: Click here to enter text. b. Lindiwe: Click here to enter text. c. Luke: Click here to enter text. d. Tarryn: Click here to enter text. e. Matthew: Click here to enter text. f. Benson: Click here to enter text. g. Craig: Click here to enter text. [15 marks] 2. Read the examples outlined in your tutorial handbook and for each one (i) identify the probable cause of forgetting, (ii) provide a definition for the probable cause, and (iii) provide an explanation of the cause with reference to the example. ...

Words: 252 - Pages: 2

Free Essay

Apa Assignment

...APA Assignment CSS101 February 13, 2013 The purpose of this essay is to tell you about the resources that are available to me and the amount of help they have provided. I will discuss all of the resources and provide all of the resources and give great information why I have chosen them. There a few program like SHARC, Tutoring Center, and my local library. I will now discuss the information I’ve come across in this essay. At Stevens Henager College that have a program called SHARC. This resource is very helpful and reliable in many ways. I constantly use this resource to help me out on a couple of assignment’s I’ve had problems with. I believe that SHARC is being a crucial part of my college life as I try to peruse my future career. They are there to help in any way they can just to prepare you for your future job. SHARC provides so much important information to help any student succeed. Another resource I truly count on is the tutoring center. They have plenty of certified tutors and tons or other academic tutors and tutor sessions. This tutoring center has helped me so many times on my classes and assignments. I believe that the tutoring center will be a huge influence and a constant stop throughout my college life. It would always be a place to go to get things I’ve had problems with and I know that they’re to help. The last resource I use is my local library. It’s always been a great place to go since I was in high school to get any...

Words: 376 - Pages: 2

Premium Essay

Dennis

... Contents Paper Description and Aims .............................................................................................................. 1 Learning Outcomes .......................................................................................................................... 1 Teaching & Support Staff.................................................................................................................. 2 Course Delivery ................................................................................................................................. 3 i. ii. i. ii. iii. iv. Lectures................................................................................................................................ 3 Tutorials ............................................................................................................................... 3 Prescribed textbook ............................................................................................................. 4 Blackboard ........................................................................................................................... 4 Podcast of lectures ............................................................................................................... 5 Student Webmail.................................................................................................................. 5 Course Learning Resources ......................................................

Words: 3081 - Pages: 13

Premium Essay

Peer Tutoring and the Conversation of Mankind.Doc

...87 .,~. Peer Tutoring and the "Conversation of Mankind" by Kenneth A. Bruffee The beginnings of peer tutoring lie in practice, not in theory. A decade or so ago, faculty and administrators in a few institutions around the country became aware that, increasingly, students entering college had difficulty doing as well in academic studies as their abilities suggested they should be able to do. Some of these students were in many ways poorly prepared academically. Many more of them, however, had on paper excellent secondary preparation. The common denominator among the poorly prepared and the apparently well prepared seemed to be that, for cultural reasons we may not yet fully under­ stand, all these students had difficulty adapting to the traditional or "normal" conventions of the college classroom. One symptom of the difficulty was that many of these students refuSed .help when it was offered. Mainly, colleges offered ancillary programs staffed by professionals. Students avoided them in droves. Many solutions to this problem were suggested and tried, from mandated programs to sink-or-swim. One idea that seemed at the time among the most exotic and unlikely (that is, in the jargon of the Sixties, among the most "radical") turned out to work rather well. Some of us had guessed that students were refusing the help we were providing because it seemed to them merely an extension of the work, the expectations, and above all the social structure of traditional classroom learning. And...

Words: 5727 - Pages: 23