Android Programming
Unit II
Understanding android resources - String resources, Layout resources, Resource
reference syntax, Defining own resource IDs - Enumerating key android resources,
string arrays, plurals, Colour resources, dimension resources, image resources,
Understanding content providers - Android built in providers, exploring databases on
emulator, architecture of content providers, structure of android content URIs,
reading data using URIs, using android cursor, working with where clause, inserting
updates and deletes, implementing content, Understanding intents basics of intents,
available intents, exploring intent composition, Rules for Resolving Intents to Their
Components, ACTION PICK, GET CONTENT, pending intents
ANDROID RESOURCE
▪ A resource in Android is a file or a value that is bound to an executable application in such a
way that you can change them or provide alternatives without recompiling the application.
▪ Examples of resources include strings, colors, bitmaps, and layouts
STRING RESOURCES
▪ String resource provides text strings for applications with optional text styling and
formatting
▪ 3 types of string resources
• String–XML resource that provides a single string
• String Array –XML resource that provides an array of strings
• Quantity strings(plurals )-XML resource that carries different strings for pluralization
STRING
▪ A single string that can be referenced from the application or from other resource file
▪ Located in res/values/[Link]
▪ getString() method is used to retrieve strings
▪ Syntax of string resource:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string name=“string_name”>text_string</string>
</resources>
▪ Example:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string name=“hello”>hello world</string>
</resources>
▪ Retrieves a string:
String name=getString([Link]);
STRING ARRAY
▪ String arrays are used to describe the array of strings that can be referenced from the
application
▪ getStringArray() method is used to retrieve strings
▪ Syntax:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string-array name=“string_array_name”>
<item>text_string</tem>
</string-array>
</resources>
▪ Example:
<resources >
<string-array name="test_array">
<item>one</item>
<item>two</item>
<item>three</item>
</string-array>
</resources>
▪ retrieve this array in the Java code as shown
//Get access to Resources object
Resources res = getResources();
String strings[] = [Link]([Link].test_array);
//Print strings
for (String s: strings)
{ Log.d("example", s); }
PLURALS
▪ Also known as quantity strings
▪ The resource plurals is a set of strings.
▪ These strings are various ways of expressing a numerical quantity, such as how many eggs
are in a nest
• There is 1 egg.
• There are 2 eggs.
• There are 0 eggs.
• There are 100 eggs.
▪ Full set supported by android is zero, one, two, few, manyand other
▪ getQuantityString() method is used to retrieve strings
▪ Syntax:
<resources...>
<plurals name=“plural_name">
<item
quantity=[“zero”|"one“|”two”|”few”|”many”|”other”]>text_string</item>
</plurals> </resources>
▪ Example:
<resources...>
<plurals name=“EggsInANestText">
<item quantity="one">There is 1 egg</item>
<item quantity="other">There are %d eggs</item> </plurals> </resources>
▪ Application code for retrieving plural strings array:
int count=getEggsInANestText();
Resources res=getResources();
String eggs=[Link]([Link],count,count);
FORMATTING AND STYLING
▪ Escaping apostrophes and quotes
<string name=“ex1”>”this’ll work”</string>
<string name=“ex2”>this\’ll work</string>
<string name=“ex3”>this doesn’t work</string>
▪ Styling with HTML markup
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string name=“welcome”>
Welcome to <b>Android</b>
</string>
</resources>
LAYOUT RESOURCES
▪ A layout resource defines the architecture for the UI in an activity or a component of a UI
▪ Located in res/layout/[Link]
▪ In Android, the view for a screen is often loaded from an XML file as a resource.
▪ These XML files are called layout resources
<?xml version="1.0" encoding="utf-8"?>
<ViewGroupxmlns:android="[Link]
android:id=“@[+][package:]id/resource_name”
android:layout_height=[“dimension”|“match_parent“|”wrap_content”>
android:layout_width=[“dimension”|" match _parent“|”wrap_content”>
[ViewGroup-specific attributes]>
<View android:id="@[+][package:]id/resource_name"
android:layout_height=[“dimension”|" match _parent“|”wrap_content”>
android:layout_width=[“dimension”|" match _parent“|”wrap_content”>
[View-specific attributes]>
</view>
</ViewGroup>
▪ ViewGroup–root [Link] must contain xmlns:androidattribute with android namespace
▪ Different ViewGroupobjects include LinearLayout, RelativeLayout, FrameLayout
▪ Individual UI component generally referred to as widget can be defined using <view>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="[Link]
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextViewandroid:id="@+id/text" android:layout_width=“wrap_content"
android:layout_height="wrap_content" android:text="@string/hello"/>
<Button android:id="@+id/button" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text=“hello I am a button"/>
</LinearLayout>
COLOR RESOURCE
▪ A color value defined in xml
▪ Color is specified with an RGB value and alpha channel
▪ Value always begins with # and followed by Alpha-Red-Green-Blue information
• #RGB
• #ARGB
• #RRGGBB
• #AARRGGBB
▪ File is saved in res/values/[Link]
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<colorname=“color_name”>
Hex_color
</color>
</resources>
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<colorname=“opaque_red”>#f00</color>
<colorname=“translucent_red”>#80ff0000</color>
</resources>
▪ Code that retrieves colorresource
Resources res=getResources();
int color=[Link]([Link].opaque_red);
▪ Layout XML that applies colorto an attribute
<TextView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:textColor=“@color/translucent_red”
android:text=“Hello”/>
DIMENSION RESOURCES
▪ Dimension resources can be used to style and localize Android UIs without changing the
source code
▪ Dimension is specified with a number followed by unit of measure :10px,2in
▪ Dimensions can be specified in any of the following units:
• px: Pixels
• in: Inches
• mm: Millimeters
• pt: Points
• dp: Density-independent pixels based on a 160dpi (pixel density per inch) screen
(dimensions adjust to screen density)
• sp: Scale-independent pixels (dimensions that allow for user sizing; helpful for use in
fonts)
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<dimenname=“dimension_name”> dimen</dimen>
</resources>
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<dimenname=“textview_height”>25dp</dimen>
<dimenname=“textview_ width”>150dp </dimen>
<dimenname=“font_size”>16sp </dimen>
</resources>
▪ Code that retrieves a dimension
Resources res=getResources();
float fontSize=[Link]([Link].font_size);
▪ Layout XML that applies dimension to an attribute
<TextView
android:layout_height=“@dimen/textview_height”
android:layout_width=“@dimen/textview_width”
android:textSize=“@dimen/font_size”/>
IMAGE RESOURCES
▪ A drawable resource is a general concept for a graphic that can be drawn to the screen
▪ It can be retrieved using getDrawable()
▪ image files are placed in the /res/drawable subdirectory.
▪ The supported image types include .gif, .jpg, and .png.
<ImageView
android:layout_height=“wrap_content”
android:layout_width=“wrap_content”
android:src=“@drawable/myimage”/>
▪ Code that retrieves an image
Resources res=getResources();
Drawable drawable=[Link]([Link]);
RESOURCE REFERENCE SYNTAX
▪ Regardless of the type of resource all Android resources are identified (or referenced) by
their IDs in Java source code.
▪ The syntax that is used to allocate an ID to a resource in the XML file is called resource
reference syntax.
▪ This syntax is not limited to allocating just ids: it is a way to identify any resource such as a
string, a layout file, or an image
▪ This resource reference has the following formal structure:
@[package:]type/name
▪ The type corresponds to one of the resource-type namespaces available in [Link], some of
which follow:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
▪ The name part in the resource reference @[package:]type/name is the name given to the
resource
▪ If you don’t specify any package in the syntax @[package:]type/name, the pair type/name
is resolved based on local resources and the application’s local [Link] package.
▪ If you specify android:type/name, the reference is resolved using the package android and
specifically through the [Link] file.
▪ You can use any Java package name in place of the package
<TextViewandroid:id=”@+id/text1” …./>
• “The + indicates that if the id of text1 is not defined as a resource, go ahead and define
it with a unique number.
DEFINING OWN RESOURCE IDs
▪ The general pattern for allocating an ID is either to create a new one or to use the one
created by the Android package.
▪ However, it is possible to create IDs beforehand and use them later in your own packages
▪ The line <TextViewandroid:id="@+id/text"> indicates that an ID named text is used if it
already exists.
▪ If the ID doesn’t exist, a new one is created.
▪ Predefining an ID
<resources> <item type="id" name="text"/> </resources>
▪ Reusing a Predefined ID
<TextViewandroid:id="@id/text"> .. </TextView>
ENUMERATING KEY ANDROID RESOURCES
CONTENT PROVIDERS
▪ Content providers are Android's central mechanism that enables to access data of other
applications -mostly information stored in databases or flat files.
▪ Content providers support the four basic operations, normally called CRUD-operations.
Create, Read, Update and Delete
▪ Provide data abstraction and encapsulation and provide mechanism for defining data
security
▪ A content provider component supplies data from one application to others on request.
▪ Such requests are handled by the methods of the ContentResolverclass.
▪ 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.
NEED OF CONTENT PROVIDER
▪ Database in android is private to the application that creates it
▪ No common storage area in android that every applications can access
▪ For different applications to use a database android needs an interface that allows inter-
application and inter-process data exchange
ANDROID BUILT IN PROVIDERS
Number of content providers are part of Android's API.
All these standard providers are defined in the package [Link]
ARCHITECTURE OF CONTENT PROVIDER
▪ A content provider presents data to external applications as one or more tables similar to
tables in relational database
▪ A content provider coordinates access to the data storage layer in your application for a
number of different APIs and components
• Sharing access to your application data with other applications
• Sending data to a widget
• Returning custom search suggestions for your application through the search
framework using SearchRecentSuggestionsProvider
• Synchronizing application data with your server using an implementation of
AbstractThreadedSyncAdapter
• Loading data in your UI using a CursorLoader
Relationship between content provider and other components
▪ To access data in a content provider, use the ContentResolverobject to communicate with
the provider as a client.
▪ The ContentResolverobject communicates with the provider object, an instance of a class
that implements ContentProvider.
▪ The provider object receives data requests from clients, performs the requested action, and
returns the results.
▪ The ContentResolvermethods provide the basic "CRUD" (create, retrieve, update, and
delete) functions of persistent storage.
▪ A common pattern for accessing a ContentProviderfrom UI uses a CursorLoader to run an
asynchronous query in the background.
▪ The Activity or Fragment in UI call a CursorLoader to the query, which in turn gets the
ContentProvider using the ContentResolver.
▪ This allows the UI to continue to be available to the user while the query is running.
▪ This pattern involves the interaction of a number of different objects, as well as the
underlying storage mechanism,
Interaction between ContentProvider, other classes, and storage
STRUCTURE OF ANDROID CONTENT URI
▪ Whenever you want to access data from a content provider you have to specify a URI.
▪ To query a content provider, you specify the query string in the form of a URI
▪ has following format −
▪ <scheme>://<authority>/<path>/<id>
▪ 4 parts
• Scheme :It has a constant value: content
• Authority: symbolic name of the provider for ex contacts , browser. unique for each one
• Path: helps distinguish the required data from complete database
• Id: specifies specific record requested . should be numeric
▪ Looking for contact number 5 in contacts then URI
Content://contacts/people/5
READING DATA USING URI
▪ To retrieve data from a content provider, you need to use URIs supplied by that content
provider.
▪ Because the URIs defined by a content provider are unique to that provider, it is important
that these URIs are documented and available to programmers to see and then call.
▪ The providers that come with Android do this by defining constants representing these URI
strings.
▪ Consider these three URIs defined by helper classes in the Android SDK:
▪ [Link].INTERNAL_CONTENT_URI
[Link].EXTERNAL_CONTENT_URI
[Link].CONTENT_URI
▪ The equivalent textual URI strings would be as follows:
content://media/internal/images
content://media/external/images
content://[Link]/contacts/
▪ Code to retrieve a single row of people from the Contacts provider
Uri peopleBaseUri= [Link].CONTENT_URI;
Uri myPersonUri= [Link](peopleBaseUri, "23");
▪ To retrieve data from a provider,
• Request the read access permission for the [Link] you need this
permission in the manifest using<uses-permission>element
USING ANDROID CURSOR
▪ A cursor represents the result of a query and basically points to one row of the query result
▪ It is an interface which represents a 2D table of any database
▪ When retrieving data using SELECT statement, database will first create CURSOR object and
return its reference
▪ The pointer of this returned reference is pointing to the 0thlocation which is otherwise
called as before first location of the cursor
▪ To retrieve data from cursor, we have to move to the first record using moveToFirst()
CURSOR
▪ moveToFirst() method takes the cursor pointer to the first location and data in the first
record can be accessed
▪ moveToNext()-to get the next data from cursor
▪ moveToLast()-last data in the result
▪ moveToPrevious()
▪ isAfterLast()-checks whether the end of the query result has been reached
▪ isBeforeFirst()-used to determine whether the cursor is at the default position of the
Resultset
▪ getCount()-To find the number of rows in a cursor
WORKING WITH WHERE CLAUSE
▪ Content providers offer two ways of passing a where clause to retrieve data:
• Through the URI
• Through the combination of a string clause and a set of replaceable string-array
arguments (explicit where clause)
Through the URI
▪ To retrieve a note whose ID is 23 from the Google notes database
Activity someActivity;
//initialize someActivity
String noteUri= "content://[Link]/notes/23";
Cursor managedCursor= [Link]( noteUri,
projection, //Which columns to return.
null, // WHERE clause
null); // Order-by clause.
• Here where clause argument of the managedQuerymethod is null
• id is embedded in the URI itself
• URI is used as a vehicle to pass the where clause
Using Explicit where Clauses
▪ Method by which Android send a list of explicit columns and their corresponding values as
a where clause
public final Cursor managedQuery(Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder);
▪ Argument named selection represents a filter (a where clause) declaring which rows to
return, Passing null will return all rows for the given URI.
▪ In the selection string we can include ?s, which will be replaced by the values from
selectionArgsin the order that they appear in the selection.
▪ Query for a note whose ID is 23 using either of these two methods:
//URI method
managedQuery("content://[Link]/notes/23" ,null ,null
,null ,null);
OR
//explicit where clause
managedQuery("content://[Link]/notes" ,null ,"_id=?" ,new
String[] {23} ,null);
▪ The convention is to use where clauses through URIs where applicable and use the explicit
option as a special case
INSERTING RECORDS
▪ Android uses a class called [Link] to hold the values for a single
record that is to be inserted. ContentValues is a dictionary of key/value pairs, like column
names and their values.
▪ Records are inserted by first populating a record into ContentValues and then asking
[Link] to insert that record using a URI.
▪ Populating a single row of notes in ContentValues in preparation for an insert:
ContentValuesvalues = new ContentValues();
[Link]("title", "New note");
[Link]("note","Thisis a new note");
//values object is now ready to be inserted
//get a reference to ContentResolverby asking the Activity class:
ContentResolvercontentResolver= [Link]();
▪ URI for notepad is [Link].CONTENT_URI
▪ take this URI and the ContentValuesand make a call to insert the row:
Uri uri= [Link]([Link].CONTENT_URI, values);
▪ This call returns a URI pointing to the newly inserted record.
▪ This returned URI would match the following structure:
[Link].CONTENT_URI/new_id
UPDATES AND DELETES
▪ Performing an update is similar to performing an insert, in which changed column values are
passed through a ContentValuesobject.
▪ int numberOfRowsUpdated= [Link]().update(Uri uri,
ContentValuesvalues, String whereClause, String[] selectionArgs)
▪ The whereClauseargument constrains the update to the applicable rows.
▪ The signature for the delete method is
▪ int numberOfRowsDeleted = [Link]().delete( Uri uri, String
whereClause, String[] selectionArgs)
IMPLEMENTING CONTENT
▪ To write a content provider, you have to extend [Link] and
implement the following key methods:
• onCreate()-method is called when the provider is started
• Query()-receives a request from a [Link] is returned as cursor object
• Insert()-inserts a new record into the content provider
• Delete()-deletes an existing record from the content provider
• Update()-this method updates an existing record from the content provider
• getType()-returns the MIME type of the data at the given URI
Content-provider implementation steps :
1. Plan your database, URIs, column names, and so on, and create a metadata class that
defines constants for all of these metadata elements.
2. Extend the abstract class ContentProvider.
3. Implement these methods: query, insert, update, delete, and getType
4. Register the provider in the manifest file.
INTENTS
▪ At the simplest level, an intent is an action that you can tell Android to perform (or invoke).
The action Android invokes depends on what is registered for that action.
▪ Intents facilitate communication b/w components in several ways.
▪ 3 fundamental use cases
▪ Starting an activity:-an activity represents single screen in an [Link] start a new instance of
an activity ,pass an intent to startActivity(). To receive a result from an activity when
finishes, call startActivityForResult()
▪ Starting a service:-a service is a component that performs operations in the background
without a user [Link] start a service to perform a one-time operation, pass an intent to
startService()
▪ Delivering a broadcast:-broadcast is a message that any app can [Link] deliver a
broadcast to other apps, pass an intent to sendBroadcast() or sendOrderedBroadcast()
AVAILABLE INTENTS IN ANDROID
▪ The set of available applications could include
▪ A browser application to open a browser window
▪ An application to call a telephone number
▪ An application to present a phone dialer so the user can enter the numbers and make a call
through the UI
▪ A mapping application to show the map of the world at a given latitude and longitude
coordinate
public static void invokeWebSearch(Activity activity)
{
Intent intent= new Intent(Intent.ACTION_WEB_SEARCH);
[Link]([Link]("[Link]
[Link](intent);
}
INTENT STRUCTURE
▪ Primary pieces of information in an intent
• ACTION:-The general action to be
performed.ACTION_VIEW,ACTION_EDIT,ACTION_MAIN
• DATA :-The data to operate on such as person record in the contact database ,expressed
as uri
▪ Examples of action/data pairs:
• ACTION_VIEW content://contacts/people/1 :- display information about person whose
ID=1
• ACTION_DIAL content://contacts/people/1 :- display phone dialer with person filled in
• ACTION_VIEW [Link] [Link] :- display phone dialer with given number
filled in
• ACTION_EDIT content://contacts/people/1 :- EDIT information about person whose
ID=1
SECONDARY ATTRIBUTES OF INTENTS
▪ CATEGORY:-gives additional information about kind of component that should handle the
intent. addCategory() places a category in an intent object, removeCategory() deletes a
category previously added, getCategories() gets the set of all categories currently in the
object.
▪ For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level
application, while CATEGORY_ALTERNATIVE means it should be included in a list of
alternative actions the user can perform on a piece of data.
▪ EXTRAS: This is a Bundle of anyadditional information. Used to provide extended
information to the [Link] set and read using putExtras() and getExtras()
▪ For example, if we have a action to send an e-mail message, we could also include extra
pieces of data here to supply a subject, body, etc.
▪ FLAGS: optional part of intent object that instruct android system how to launch an activity
and how to treat it after it is launched
▪ FLAG_ACTIVITY_CLEAR_TASK, FLAG_ACTIVITY_NEW_TASK
TYPES OF INTENTS
▪ Implicit intents: Do not specify the android components which should be called .
▪ Only specifies action to be performed. A Uri can be used with implicit intent to specify the
datatype
▪ Intent intent=new Intent(ACTION_VIEW,[Link]([Link]
▪ Explicit intent: Use explicit intents when you know exactly which activity can handle the
request.
▪ Explicit intents are used in applications wherein one activity can switch to other activity.
▪ Typically used for application-internal-messages Such as an activity starting a subroutine
service or launching a sister activity
Intent i=newIntent([Link],[Link])
startActivity(i);
RULES FOR RESOLVING INTENTS TO THEIR COMPONENTS
▪ Android uses multiple strategies to match intents to their target activities based on intent
filters.
▪ At the top of the hierarchy is the component name attached to an intent. If this is set, the
intent is known as an explicit intent.
▪ For an explicit intent, only the component name matters; every other aspect or attribute of
the intent is ignored.
▪ When a component name is not present on an intent, the intent is said to be an implicit
intent.
▪ When the system receives an implicit intent to start an activity, it searches for the best
activity for the intent by comparing it to intent filters based on 3 aspects
• Action
• Data(URI and datatype)
• Category
▪ Intent filter will specify type of intents it will accept. They are declared in manifest file
▪ Action test:
• If an intent has an action on it, the intent filter must have that action as part of its action
list
• To specify accepted intent actions, an intent filter can declare zero or more <action>
elements
<intent-filter>
<action android:name=“[Link]”/>
<action android:name=“[Link]”/>
….
</intent-filter>
• To pass this filter, the action specified in the intent must match one of the actions listed
in the filter
• If the filter doesn’t list any action,thenall intents fail the test
• If an intent doesn't specify an action, it passes the test as long as filter contains at least
one action
▪ Category Test:
• To specify accepted intent categories, an intent filter can declare zero or more
<category> elements
<intent-filter>
<category android:name=“[Link]”/>
<category android:name=“[Link]”/>
….
</intent-filter>
• For an intent to pass the category test, every category in the intent must match a
category in the filter.
• Reverse is not necessary
• An intent with no categories always passes the test regardless of what categories are
declared in the filter
▪ Data test:
• To specify accepted intent data, filter can declare zero or more <data> elements
<intent-filter>
<data android:mimeType=“video/mpeg” android:scheme=“http”…./>
<data android:mimeType=“audio/mpeg” android:scheme=“http”…./>
….
</intent-filter>
• Each <Data> element contains a URI structure and a data type(mime type)
• Each part of URI is a separate attribute
• <scheme>://<host>:<port>/<path>
• Ex: content://[Link]/folder/subfolder/etc
• Data test compares both URI and MIME type in the intent to that of the filter
• An intent that contains neither URI nor MIME passes the test only if filter doesn’t
specify any URIs or MIME types
• An intent that contains a URI but no MIME passes the test only if its URI matches the
filter’s URI and filter doesn’t specify any MIME types
• An intent that contains MIME but not URI passes the test only if filter list same MIME
types and doesn’t specify any URI
• An intent that contains both URI & MIME passes the MIME type part of the test if it
matches a type listed in the filter. It passes URI part of test if its URI matches a URI in the
filter or if it has a content: or file: URI and filter doesn’t specify any URI
Action_pick
▪ The idea of ACTION_PICK is to start an activity that displays a list of
items.
▪ The activity then should allow a user to pick one item from that list.
▪ Once the user picks the item, the activity should return the URI of
the picked item to the caller.
▪ This allows reuse of the UI’s functionality to select items of a certain
type.
▪ It helps to pick an image item from a data source like camera or
gallery
Intent photoPickerIntent= new
Intent(Intent.ACTION_PICK);
[Link]("image/*");
startActivityForResult(photoPickerIntent,
SELECT_PHOTO);
Action_get_content
▪ Allow the user to select a particular kind of data and return it.
▪ This is different than ACTION_PICK in that here we just say what kind of data is desired, not
a URI of existing data from which the user can pick
Intent pickIntent= new Intent(Intent.ACTION_GET_CONTENT);
int requestCode= 2;
[Link]("[Link]/[Link]");
[Link](pickIntent, requestCode);
PENDING INTENT
▪ Android allows a component to store an intent for future use in a location from which it can
be invoked again.
▪ For example, in an alarm manager, you want to start a service when the alarm goes off.
▪ Android does this by creating a wrapper pending intent around a normal corresponding
intent and storing it away so that even if the calling process dies off, the intent can be
dispatched to its target.
Creating a pending intent:
▪ Syntax:
[Link](Context context, //originating context int
requestCode, //1,2, 3, etc Intent intent, //original intent int
flags //flags )
▪ Usually, you can pass a zero for requestCodeand flags to get the default behavior.
Intent regularIntent;
PendingIntentpi = [Link](context, 0, regularIntent,0);
ACTION_PICK
▪ The idea of ACTION_PICK is to start an activity that displays a list of
items.
▪ The activity then should allow a user to pick one item from that list.
▪ Once the user picks the item, the activity should return the URI of
the picked item to the caller.
▪ This allows reuse of the UI’s functionality to select items of a
certain type.
▪ It helps to pick an image item from a data source like camera or
gallery
▪ Launches a sub-Activity that lets you pick an item from the Content
Provider specified by the Intent’s data URI.
▪ When closed, it should return a URI to the item that was picked.
▪ The Activity launched depends on the data being picked
▪ for example, passing content://contacts/people will invoke the native contacts list
▪ Almost all core android applications (eg: Messaging, Gallery, Contacts etc) provide this
facility.
▪ All you need is the URI of the data you need and required permissions to access that data.
startActivityForResult:
▪ public void startActivityForResult(Intent intent, int requestCode)
▪ The requestCodehelps you to identify from which Intent you came back.
▪ For example, imagine your Activity A (Main Activity) could call Activity B (Camera Request),
Activity C (Audio Recording), Activity D (Select a Contact).
▪ Whenever the subsequently called activities B, C or D finish and need to pass data back to A,
now you need to identify in your onActivityResultfrom which Activity you are returning from
and put your handling logic accordingly.
private static final int REQUEST_PICK_IMAGE = 1;
Intent pickImageIntent= new Intent(Intent.ACTION_PICK,
[Link].
Media. EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, REQUEST_PICK_IMAGE);
private static final int PICK_CONTACT_SUBACTIVITY = 2;
Uri uri= [Link](“content://contacts/people”);
Intent intent= new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);
ACTION_GET_CONTENT
▪ Allow the user to select a particular kind of data and return it.
▪ This is different than ACTION_PICK in that here we just say what kind of data is desired, not
a URI of existing data from which the user can pick
▪ An ACTION_GET_CONTENT could allow the user to create the data as it runs (for example
taking a picture or recording a sound), let them browse over the web and download the
desired data, etc.
▪ There are two main ways to use this action:
▪ For a specific kind of data, such as a person contact, set the MIME type to the kind of data
you want and launch it with Context #startActivity(Intent).
▪ The system will then launch the best application to select that kind of data
Intent intent= new Intent(Intent.ACTION_GET_CONTENT);
[Link]([Link].CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
▪ It is possible to wrap the GET_CONTENT intent with a chooser (through
createChooser(Intent, CharSequence)), which will give the proper interface for the user to
pick how to send your data and allow you to specify a prompt indicating what they are
doing.
Intent intent= new Intent();
[Link]("image/*");
[Link](Intent.ACTION_GET_CONTENT);
startActivityForResult([Link](intent,"SelectPicture"),
SELECT_PICTURE);
PENDING INTENT
▪ Android allows a component to store an intent for future use in a location from which it can
be invoked again.
▪ For example, in an alarm manager, you want to start a service when the alarm goes off.
▪ Android does this by creating a wrapper pending intent around a normal corresponding
intent and storing it away so that even if the calling process dies off, the intent can be
dispatched to its target.
▪ Android PendingIntent is an object that wraps up an intent object and it specifies an action
to be taken place in future.
▪ In other words, PendingIntent pass a future Intent to another application and allow that
application to execute that Intent as if it had the same permissions as our application,
whether or not our application is still around when the Intent is eventually invoked.
▪ A PendingIntent is generally used in cases were an AlarmManager needs to be executed or
for Notification (that we’ll implement later in this tutorial).
▪ A PendingIntent provides a means for applications to work, even after their process exits.
▪ Each explicit intent is supposed to be handled by a specific app component like Activity,
BroadcastReceiveror a Service.
▪ Hence PendingIntentuses the following methods to handle the different types of intents:
▪ [Link]() : Retrieve a PendingIntentto start an Activity
▪ [Link]() : Retrieve a PendingIntentto perform a Broadcast
▪ [Link]() : Retrieve a PendingIntentto start a Service
Intent intent= new Intent(this, [Link]);
// Creating a pending intent and wrapping our intent
PendingIntentpendingIntent= [Link](this, 1, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
[Link]();
▪ The operation associated with the pendingIntent is executed using the send() method.
▪ The parameters inside the getActivity() method :
• this (context) : This is the context in which the PendingIntentstarts the activity
• requestCode: “1” is the private request code for the sender
• intent : Explicit intent object of the activity to be launched
• flag : FLAG_UPDATE_CURRENT. This one states that if a previous PendingIntent already
exists, then the current one will update it with the latest intent. There are many other
flags like FLAG_CANCEL_CURRENT etc.
THANK YOU