5 INTENTS, MESSAGING & WIDGETS
Context
Context is probably the most used
element in Android applications…
but, it may also be the most
misused, if not understood properly.
Context defines methods that access
system resources, retrieve
application's static assets, check
permissions, perform UI
manipulations and many more.
Context
A Context is used for many
operations but mostly to load and
access resources. This is why all the
widgets receive a Context parameter
in their constructor. In a regular
Android application, you usually have
two kinds of Context Activity and
Application.
It’s usually the first one that the
developer passes to classes and
View.getContext(): Returns the
context the view is currently running
in. Usually the currently active
Activity.
Activity.getApplicationContext():
Returns the context for the entire
application (the process all the
Activities are running inside of). Use
this instead of the current Activity
context if you need a context tied to
ContextWrapper.getBaseContext(): If
you need access to a Context from
within another context, you use a
ContextWrapper. The Context referred to
from inside that ContextWrapper is
accessed via getBaseContext().
Context Capabilities
The common actions you can safely take
with a given Context object depends on
where it came from originally. Below is a
table of the common places an
application will receive a Context, and in
each case what it is useful for:
1. An application CAN start an Activity from
here, but it requires that a new task be
created. This may fit specific use cases,
but can create non-standard back stack
behaviors in your application and is
generally not recommended or considered
good practice.
2. This is legal, but inflation will be done
with the default theme for the system on
which you are running, not what’s defined
in your application.
The Rule of Thumb
In most cases, use the Context directly
available to you from the enclosing
component you’re working within. You
can safely hold a reference to it, using
this, as long as that reference does not
extend beyond the lifecycle of that
component.
As soon as you need to save a reference
to a Context from an object that lives
beyond your Activity or Service, even
temporarily, switch that reference you
Intents
Intents
Intents : request for an action to
be performed (usually on a set of
data)
Intent Filters : register Activities,
Services, and Broadcast
Receivers (as being capable of
performing an action on a set of
data)
Broadcast Receivers : listens to
intents
Intents
Intents are asynchronous
messages which allow Android
components to request
functionality from other
components of the Android
system. For example, an Activity
can send an Intent to the Android
system which starts another
Activity.
An Intent can also contain data.
This data can be used by the
receiving component.
Types of Intents
Explicit Intents
Implicit Intents
Explicit Intent
Explicit Intents explicitly defines
the component which should be
called by the Android system, by
using the Java class as identifier.
The following shows an explicit
Intent.
I n t e n t i = new I n t e n t ( t h i s , Act ivit y
T wo. class) ;
Explicit Intents are typically used
within an application as the
classes in an application are
controlled by the application
Implicit Intent
Implicit Intents do not directly
specify the Android components
which should be called.
For example the following tells the
Android system to view a
webpage.
I n t e n t i = new I n t e n t ( I n t e n t .
ACTION_ VIEW , U r i . p a r s e (
“http:/ / w w w . google.com" ) ) ;
or telling the Android system to
open the camera:
Intent i = new
Changes in
AndroidManifest.xml
<uses-feature
android:name="android.hardware.camera
"/>
<uses-permission
android:name="android.permission.CAME
RA"/>
<uses-permission
android:name="android.permission.WRIT
E_EXTERNAL_STORAGE"/>
How Implicit Intent is
delivered
Activity A creates an Intent with an
action description and passes it to
startActivity().
The Android System searches all apps
for an intent filter that matches the
intent.
When a match is found, the system
starts the matching activity (Activity B)
by invoking its onCreate() method and
passing it the Intent.
Starting activity or services
To start an activity, use the method
startActivity(intent).
This method is defined on
the Context object
which Activity extends.
Intent i = new Intent(this,
ActivityTwo.class); startActivity(i);
If these Intents are sent to the
Android system, it searches for
all components which are
registered for the specific action
and the data type.
If only one component is found,
Android starts this component
directly. If several components
are identifier by the Android
system, the user will get a
selection dialog and can decide
which component should be
Email intent
Intent email = new
Intent(Intent.ACTION_SEND,
Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL,
recipients);
email.putExtra(Intent.EXTRA_SUBJE
CT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT,
body.getText().toString());
startActivity(Intent.createChooser(e
mail, "Choose an email client
Dial Intent
Intent i = new
intent(Intent.ACTION_DIAL,
Uri.parse(“tel:93675359”));
startActivity(i);
Intent Filter
Required for Intent resolution to
match Intents to Activities,
Services, or BroadcastReceivers
Most Intent Filters are declared in
AndroidManifest.xml of an
application
Sending Data to Intents
To send data from one intent to another,
we need to use the putExtra method.
This method works like a Hashtable: it
expects to receive arguments as a key
and a value.
The following shows how to send
information to an intent:
I n t e n t i = new I n t e n t (this,
ActivityTwo.class);
i . p u t E x t r a ( " key 1 " , 1 ) ;
i . p u t E x t r a ( " key 2 " , " h e l l o " ) ;
i . p u t E x t r a ( " key 3 " , new c h a r [ ] { ’ a ’ , ’ b
Receiving data from Intents
The component which receives the
Intent can use the getIntent().getExtras()
method call to get the extra data.
Bundle e x t r a s = getIntent( ).getExtras( );
i f ( e x t r a s != n u l l )
{
int val1 = e x t r a s . g e t I n t ( " key 1
");
String val2 = extras. getString("
key 2 " ) ;
c h a r [] v a l 3 = e x t r a s . g e t C h a r A r r a
y ( " key 3 " ) ;
}
Calling sub-activity for
result data
If you need some information from the
called Activity use the
startActivityForResult() method.
If you use the startActivityForResult()
method then the started Activity is
called a Sub-Activity.
CameraDemo
Calling sub-activity for
result data
An activity can be closed via the back
button on the phone.
In this case the finish() method is
performed. If the activity was started
with the startActivity(Intent) method call,
the caller requires no result or feedback
from the activity which now is closed.
If you start the activity with the
startActivityForResult() method call, you
expect feedback from the sub-activity.
Once the sub-activity ends,
the onActivityResult() method on the
In the startActivityForResult() method
call you can specify a result code to
determine which activity you started.
This result code is returned to you. The
started activity can also set a result code
which the caller can use to determine if
the activity was canceled or not.
The sub-activity uses the finish() method
to create a new intent and to put data
into it. It also sets a result via
the setResult() method call.
public void onClick(View view) {
Intent i = new Intent(this,
ActivityTwo.class);
i.putExtra("Value1", "This value one for
ActivityTwo ");
i.putExtra("Value2", "This value two
ActivityTwo");
// set the request code to any code you
like,
// you can identify the callback via this
If you use
the startActivityForResult() method, then
the started activity is called a sub-
activity.
If the sub-activity is finished, it can send
data back to its caller via an Intent. This
is done in the finish() method.
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star.
");
data.putExtra("returnKey2", "You could be better
then you are. ");
// Activity finished ok, return the data
setResult(RESULT_OK, data);
super.finish();
}
Once the sub-activity finishes, the
onActivityResult() method in the
calling activity is called.
@Override
protected void onActivityResult(int requestCode, int
resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode ==
REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this,
data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
Toast
A toast provides simple feedback about
an operation in a small popup. It only fills
the amount of space required for the
message and the current activity
remains visible and interactive. Toasts
automatically disappear after a timeout.
For example, clicking Send on an email
triggers a "Sending message..." toast, as
shown in the following screen capture:
Creating & positioning Toast
Toast.makeText(context, text,
duration).show();
Positioning your Toast
toast.setGravity(Gravity.TOP|
Gravity.LEFT, 0, 0);
Snackbar
Snackbar in android is a new widget
introduced with the Material Design
library as a replacement of a Toast.
Android Snackbar is light-weight widget
and they are used to show messages in
the bottom of the application with
swiping enabled. Snackbar android
widget may contain an optional action
button.
Snackbar Vs Toast
A Toast messages can be customized and
printed anywhere on the screen, but a
Snackbar can be only showed in the
bottom of the screen
A Toast message don’t have action button,
but Snackbar may have action button
optionally. Though, A Snackbar shouldn’t
have more than one action button
Toast message cannot be off until the time
limit finish, but Snackbar can be swiped
off before the time limit
Creating Snackbar
Snackbar snackbar =
Snackbar .make(View, Text,
Snackbar.LENGTH_LONG);
snackbar.show();
Swipe works only with Coordinator
Layout
Action Taking Snackbar
Snackbar snk = Snackbar
.make(view,"This is action taking
snackbar",Snackbar.LENGTH_LONG)
.setAction("UNDO", new
View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view,"Action
taken",Snackbar.LENGTH_LONG).show(
);
}
ListView
Android ListView is a view which groups
several items and display them in
vertical scrollable list. The list items are
automatically inserted to the list using
an Adapter that pulls content from a
source such as an array or database.
An adapter actually bridges UI
components and the data source that fill
data into UI Component. Adapter holds
the data and send the data to adapter
view, the view can take the data from
ArrayAdapter
The ListView and GridView are
subclasses of AdapterView and they
can be populated by binding them to
an Adapter, which retrieves data from
an external source and creates a View
that represents each data entry.
You can use this adapter when your data
source is an array. By default,
ArrayAdapter creates a view for each
array item by calling toString() on each
item and placing the contents in
Create an XML file with
listview
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
Define a new Adapter
// First parameter – Context
// Second parameter - Layout for the row, here
default internal view of layout
// Third parameter - ID of the TextView to which the
data is written, default textid where text will be
written from array
// Forth - the Array of data, here it’s String array
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1, values);
// Assign adapter to ListView
Event Handling in
ArraryAdpater
listView.setOnItemClickListener(new
OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String)
listView.getItemAtPosition(position);
//Take necessary action….
}
Gridview
Android GridView shows items in two-
dimensional scrolling grid (rows &
columns) and the grid items are not
necessarily predetermined but they
automatically inserted to the layout
using a ListAdapter
XML file
<GridView
xmlns:android="http://schemas.android.co
m/apk/res/android"
android:id="@+id/grid_view"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:numColumns="3"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp"
android:background="#ff5555"
android:columnWidth="75dp"
android:layout_margin="15dp" > <!--
ImageAdpater in Gridview
Android GridView shows items in two-
dimensional scrolling grid (rows &
columns) and the grid items are not
necessarily predetermined but they
automatically inserted to the layout
using a ListAdapter
Expandable ListView
Data source is
required in the form of
array list or database
A class extending
BaseExpandableListAd
apter
Main Activity creating
ExpandableListAdapte
r
XML layouts for Group
headers and Group