Best PDF
Best PDF
Best PDF
Created By:-
Affle Appstudioz
Android Training Material
1. Introduction
2. Android Architecture
3. Android Application Components
4. Android - Hello World Example
5. Android Resources Organizing & Accessing
6. Activity
7. Service
8. Broadcast Receiver
9. Intent Filter
Introduction
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.
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.1Jelly 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
Media support 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
Web browser Based on the open-source WebKit layout engine, coupled with
Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
Multi-touch Android has native support for multi-touch which was initially
made available in handsets such as the HTC Hero.
Multi-tasking User can jump from one task to another and same time various
application can run simultaneously.
Resizable widgets Widgets are resizable, so users can expand them to show more
content or shrink them to save space
Wi-Fi Direct A technology that lets apps discover and pair directly, over a
high-bandwidth peer-to-peer connection.
Android Beam A popular NFC-based technology that lets users instantly share,
just by touching two NFC-enabled phones together.
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,SlideME,Opera Mobile Store,Mobango,F-
droid and 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.
Categories of Android applications
There are many android applications in the market. The top categories are:
History of Android
The code names of android ranges from A to L currently, such as Aestro, Blender,
Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly
Bean, KitKat and Lollipop. Let's understand the android history in a sequence.
What is API level?
API Level is an integer value that uniquely identifies the framework API revision
offered by a version of the Android platform.
Android 2.3.3
Android 2.3.2 9 GINGERBREAD
Android 2.3.1
Android 2.3
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This
provides a level of abstraction between the device hardware and it contains all the
essential hardware drivers 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.
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 Libraries
This category encompasses those Java-based libraries that are specific to Android
development. Examples of libraries in this category include the application framework
libraries in addition to those that facilitate user interface building, graphics drawing
and database access. A summary of some key core Android libraries available to the
Android developer is as follows −
Having covered the Java-based core libraries in the Android runtime, it is now time to
turn our attention to the C/C++ based libraries contained in this layer of the Android
software stack.
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
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.
ANDROID - APPLICATION COMPONENTS
Application components are the essential building blocks of an Android application.
These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the application and how
they interact.
There are following four main components that can be used within an Android
application:
Components Description
Activities They dictate the UI and handle the user interaction to the
smart phone screen
Services
Broadcast Receivers
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.
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 Description
So let us proceed to write a simple Android Application which will print "Hello
World!".
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:
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
−
Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in the
Android project −
S.N. Folder, File & Description
1 src
This contains the .java source files for your project. By default, it includes
anMainActivity.java source file having an activity class that runs when your
app is launched using the app icon.
2 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.
3 bin
This folder contains the Android package files .apk built by the ADT during
the build process and everything else needed to run an Android application.
4 res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density
screens.
5 res/layout
This is a directory for files that define your app's user interface.
6 res/values
This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.
7 AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the
app and defines each of its components.
Following section will give a brief overview few of the important application files.
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 android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
@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;
}
}
Whatever component you develop as a part of your application, you must declare all
its components in a manifest.xml which resides 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 −
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
The <activity> 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 <activity> 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.
Following is the list of tags which you will use in your manifest file to specify
different Android application components:
<activity>elements for activities
<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers
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 −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
The R File
package com.example.helloworld;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This tutorial will explain you how you can organize your application resources,
specify alternative resources and access them in your applications.
You should place each type of resource in a specific sub directory 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 sub directories. 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.
anim/ XML files that define property animations. They are saved in
res/anim/ folder and accessed from the R.anim class.
color/ XML files that define a state list of colors. They are saved in res/color/
and accessed from the R.color class.
drawable/ Image files like .png, .jpg, .gif or XML files that are compiled into
bitmaps, state lists, shapes, animation drawable. They are saved in
res/drawable/ and accessed from the R.drawable class.
layout/ XML files that define a user interface layout. They are saved in
res/layout/ and accessed from the R.layout class.
menu/ 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.
values/ XML files that contain simple values, such as strings, integers, and
colors. For example, here are some filename conventions for
resources you can create in this directory −
Alternative Resources
Below is an example which specifies images for a default screen and alternative
images for high resolution screen.
MyProject/
src/
main/
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml
Below is another example which specifies layout for a default language and
alternative layout for Arabic language.
MyProject/
src/
main/
java/
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
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:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>
Now you can set the text on a TextView object with ID msg using a resource ID as
follows:
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);
Example
Consider a layout res/layout/activity_main.xml with the following definition:
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate method as
follows −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
Consider the following resource XML res/values/strings.xml file that includes a color
resource and a string resource −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>
Now you can use these resources in the following layout file to set the text color and
text string as follows:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />
ACTIVITY
An activity represents a single screen with a user interface just like window or frame
of Java.Android activity is the subclass of ContextThemeWrapper class.
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 an Activity 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 life cycle diagram: (image courtesy : android.com )
The Activity class defines the following call backs i.e. events. You don't need to
implement all the callbacks methods. However, it's important that you understand
each one and implement those that ensure your app behaves the way users expect.
Callback Description
onCreate This is the first callback and called when the activity is first created.
onStart This callback is called when the activity becomes visible to the user.
onResume This is called when the user starts interacting with the application.
onPause 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.
onDestroy This callback is called before the activity is destroyed by the system.
onRestart This callback is called when the activity restarts after stopping it.
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 Examplechapter:
Step Description
1 You will use eclipse IDE to create an Android application and name it
as HelloWorldunder a package com.example.helloworld as explained in
the Hello World Examplechapter.
3 Run the application to launch Android emulator and verify the result of the
changes done in the application.
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
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 <intent-filter>
that includes the MAIN action and LAUNCHER category as follows:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
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 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 Emulator window and you should see following log
messages in LogCat window in Eclipse IDE:
Let us again try to click Menu button on the Android emulator and it will generate
following events messages in LogCat window in Eclipse IDE:
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 Activity Life Cycle for an Android Application.
State Description
A service has life cycle 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 life cycle when the service is created with
startService and the diagram on the right shows the life cycle when the service is
created with bindService: imagecourtesy:android.com
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
onStartCommand 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.
onBind 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.
onUnbind The system calls this method when all clients have disconnected
from a particular interface published by the service.
onRebind The system calls this method when new clients have connected
to the service, after it had previously been notified that all had
disconnected in itsonUnbindIntent.
onCreate The system calls this method when the service is first created
usingonStartCommand or onBind. This call is required to
perform one-time set-up.
onDestroy 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.
The following skeleton service demonstrates each of the life cycle methods −
package com.affleappstudioz;
import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
}
}
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 Description
1 You will use Android StudioIDE to create an Android application and name it
as My Application under a package com.example.My Application as explained
in the Hello World Example chapter.
Modify main activity file MainActivity.java to
add startService and stopServicemethods.
2
7 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
@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));
}
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
@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
<service.../> tag to include our service:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.MyApplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="22" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of services"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Affle Appstudioz "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Start Services"
android:onClick="startService"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Services"
android:id="@+id/button"
android:onClick="stopService"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2" />
</RelativeLayout>
<resources>
<string name="app_name">My Application</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
BROADCAST RECEIVERS
Broadcast Receivers simply respond to broadcast messages from other applications
or from the system itself. These messages are sometime called events or intents. For
example, applications can also initiate broadcasts to let other applications know that
some data has been downloaded to the device and is available for them to use, so this
is broadcast receiver who will intercept this communication and will initiate
appropriate action.
There are following two important steps to make BroadcastReceiver works for the
system broadcasted intents −
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.
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
There are several system generated events defined as final static fields in
the Intent class. The following table lists a few important system events.
If you want your application itself should generate and send custom intents then you
will have to create and send those intents by using the sendBroadcast method inside
your activity class. If you use the sendStickyBroadcastIntent method, the Intent
is sticky, meaning the Intent you are sending stays around after the broadcast is
complete.
<intent-filter>
<action android:name="com.affleappstudioz.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
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 You will use Android studio to create an Android application and name it
as My Application under a package com.example.My Application as
explained in the Hello World Example chapter.
4 An application can handle one or more custom and system intents without
any restrictions. Every indent you want to intercept must be registered in
yourAndroidManifest.xml file using <receiver.../> tag
7 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
@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;
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
Following will the modified content of AndroidManifest.xml file. Here we have added
<service.../> tag to include our service:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.My Application"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.affleappstudioz.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Affle Appstudioz "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Broadcast Intent"
android:onClick="broadcastIntent"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
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.
Above syntax is calling startActivity method to start an email activity and result
should be as shown below
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.
String q = "affleappstudioz";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
Above example will search as affleappstudioz on android search engine and it gives
the result of affleappstudioz in your an activity
There are separate mechanisms for delivering intents to each type of component -
activities, services, and broadcast receivers.
2 Context.startService
The Intent object is passed to this method to initiate a service or deliver new
instructions to an ongoing service.
3 Context.sendBroadcast
The Intent object is passed to this method to deliver the message to all
interested broadcast receivers.
Intent Objects
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.
The action in an Intent object can be set by the setAction method and read by
getAction.
Data
Adds a data specification to an intent filter. The specification can be just a data
type themimeTypeattribute, just a URI, or both a data type and a URI. A URI is
specified by separate attributes for each of its parts −
These attributes that specify the URL format are optional, but also mutually
dependent −
If a scheme is not specified for the intent filter, all the other URI attributes are
ignored.
If a host is not specified for the filter, the port attribute and all the path
attributes are ignored.
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.
1 ACTION_VIEW content://contacts/people/1
2 ACTION_DIAL content://contacts/people/1
3 ACTION_VIEW tel:123
Display the phone dialer with the given number filled in.
4 ACTION_DIAL tel:123
Display the phone dialer with the given number filled in.
5 ACTION_EDIT content://contacts/people/1
7 ACTION_SET_WALLPAPER
8 ACTION_SYNC
9 ACTION_SYSTEM_TUTORIAL
10 ACTION_TIMEZONE_CHANGED
11 ACTION_UNINSTALL_PACKAGE
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.
You can check detail on Intent Filters in below section to understand how do we use
categories to choose appropriate activity corresponding 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
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.
1 FLAG_ACTIVITY_CLEAR_TASK
2 FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task,
then instead of launching a new instance of that activity, all of the other
activities on top of it will be closed and this Intent will be delivered to
the nowontop old activity as a new Intent.
3 FLAG_ACTIVITY_NEW_TASK
Component Name
Types of Intents
Explicit Intents
// Starts TargetActivity
startActivity(i);
Implicit Intents
These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For
example −
Step Description
1 You will use Android studio IDE to create an Android application and name it
as My Application under a package com.example.saira_000.myapplication.
While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
4 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
startActivity(i);
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Affle Appstudioz"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Phone"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio, open
one of your project's activity files and click Run icon from the toolbar.Android
Studio 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 −
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 <intent-filter> element in the manifest file to
list down actions, categories and data types associated with any activity, service, or
broadcast receiver.
<activity android:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.My Application.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
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.My Application.LAUNCH action provided their category
is android.intent.category.DEFAULT.
The <data> 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.
A filter <intent-filter> may list more than one action as shown above but this
list cannot be empty; a filter must contain at least one <action> 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 <intent-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 <data> element can specify a URI and a data type MIMEmediatype. 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 android studio to create an Android application and name it
as My Application under a package com.example.saira_000.myapplication.
While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
7 Run the application to launch Android emulator and verify the result of the
changes done in the application.
package com.example.saira_000.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.example.com")
);
startActivity(i);
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.example.My
Application.LAUNCH",Uri.parse("http://www.example.com"));
startActivity(i);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.example.My
Application.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.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Affle Appstudioz"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start browsing with view action"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start browsing with launch action"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exceptional condition"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
<TextView android:id="@+id/show_data"
android:layout_width="fill_parent"
android:layout_height="400dp"/>
</LinearLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.saira_000.myapplication"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.saira_000.myapplication.CustomActivity"
<android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.saira_000.myapplication.LAUNCH"
/>
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio, open
one of your project's activity files and click Run icon from the toolbar. Android
Studio 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 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.
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 −
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
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 −