0% found this document useful (0 votes)
23 views16 pages

Mad 3

The document discusses mobile application development, focusing on the use of Intents in Android to launch activities, pass data, and handle user actions. It explains explicit and implicit Intents, how to start new activities, and how to retrieve results from activities. Additionally, it covers native actions available in Intents and provides examples of sending SMS and making phone calls using Intents.

Uploaded by

yeahmr83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views16 pages

Mad 3

The document discusses mobile application development, focusing on the use of Intents in Android to launch activities, pass data, and handle user actions. It explains explicit and implicit Intents, how to start new activities, and how to retrieve results from activities. Additionally, it covers native actions available in Intents and provides examples of sending SMS and making phone calls using Intents.

Uploaded by

yeahmr83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

MobileApplication Development

Essayy Questions with Answers

1 INTENTs AND BROADCASTS, After the Start Activity is called, the new Activity
Shat is an Intent? How to use Intent to (in the example, MyOtherActivity) will be created, started
launch a new Activitý? and resumed by moving the top of the activity stack.
I n t e n t : An Intent is an object used to request an On the new Activity, by calling finish or pressing
ion from another component. Intent is a data the hardward back.button, it closes and removes it from
ructure
holding an bstract description of operation to the stack. Alternatively, we can continue to navigate to
nerfomed. It is used to request functionalities from other activities by calling start Activity. Each fimé we
het Android components. Intent is an intention to do call Start Activity, a new activity will be added to the
mething. We can do many things by using intent like stack, pressing back (or calling finish) then it will remove
wiaate from one activity to another activity, take picture each of these activities.
a camera app, web search search location on map
Q3. Explain briefly about Implicit Intents.
An Android Intent is an abstract description of
Ans: An implicit intent is a mechanism that allows you
describe an application components service action
n operation to be performed. It can be used with start
Activity to launch an Activity, broadcastlntent to send it requests. That means when you ask the system to start
an activity to perfom an action without knowing which
o any interested BroadCastReceivercomponents, and application, or activitywillbe started.
SartService(Intent) or bind Service(Intent, Service
Connection, int) to communicate with a background Eg: Let users make calls from our application,
service. that could implement a new dialer or we could use an
For example, let's assurme that you have an
implicit intent and that requests the action (dialing) to
be performed on a phone number (represented as URI).
Activity that needs to launch an email client and sends
an email using your Android device. For this purpose, f(somethingwired && it DontL.ookGood)
your Activity would send an ACTION_SEND along with
appropriate chooser, tothe Android Intent Resolver. The
specified chooser gives the proper interface for the user Intent intent = new Intent (Intent.ACTION DIAL
to pick how to send your email data.
Uri. Phase("tel:555-2368");
Intentemail=newIntent{Intent.ACTION_SEND
uri.parse("mail to:")); startActivity(tintent};
email.putExtra(lntent.EXTRA_EMAIL,
tecipients); .This intent, resolves by Android and starts an
activity and provides the dial action on a telephone
email.putExtra(Intent. EXTRA_SUBJECT, number.
Subject.getText( ).toStringl );
When we construct a new implicit intent, that we
can specity an action to perform and, optionally, supply
ipuExtral(ntent.EXTRA TEXTbody getText( ).to
Sring I) the URI of the data on which to perform that action. We
can also send additional data to the target. Activity by
StartActivity(ntent.createChooser(email, "choose adding extras to the Intent.
anemail client from"))
To start an Activity we use an implicit Intent then
.How to explicity start new Activity. Android will resolve it into activity classandit performs
Ans: therequiredaction onthe type of data that specified.
locrate a new Intent, we have to select a specific
This means we can create projects and that use
C Class to start, then specify the currentActivity's
context
and the class of the Activity to laurich. Then functionality from other 'applications withoutknouwing
pass
i s Intent into StartActivity which is shown in the
the exactly which application are browsingfunctionality
ollowing code as fromahead oftime.
Intent ent=new Intent(MyAetivity.this, Explaln how topass data to intents

MyOtherActivity.class); Ans: We can pass data from one activity to another


using Intents. We need to enhance the code for
Warin startActivity(intent);
AOXUPhotocopyingof this book is a CRIMINAL AG Anyone found gullty LIABLE to face LEGAL proceedings
Mobile Application Development import android.content.Intent;

MainActivity to include extra data in the startintent


an

add code in SecondaryActivity to receive this


data and import android.support. V7.app.Action
use it. Activity:
one line of code is
added to the import android.os.Bundde;
In MainActivity,
Intent definition. The putExtra( ) method passes a key
com.talkingandroid. import android.View.Menu
and a vale. In this case, the key is
MESSAGE and the value is "Hello Secondary Activity import android.View.Menultem;

new Intent(gotApplication
Intent startintent =

View. View
context(). SecondaryActivity.class) import android.
startintent.putExtra("com.talkingandroid. import android. Widget.Button;
MESSAGE", Helo Secondary Activity):
public class MainActivity exten
startActivity(startlntent): ActionBarActivity{
to Secondary
You also need to make changes @Overide
Activity to receive this data.
The goal is to change
data and show the protected void onCreate(BundleSavedinstand
Secondary Activity to receive the
passed message in the
TextView. State)
You are going to add a TextView called message super.onCreate(SavedinstanceState);
file. Openthe
to the secondary-activity.xml layout
folder. setContentView(R.Layout.Activity_main);
activity_secondary.xml file under the res/layout
either design mode or text
You can edit the layout in Button activityButton= (Button)findViewByi
mode. Find the TextView that was generated and verify
that it has a property called id. In the design view, you (R.id.button
can find the id property and enter the message as the activityButton.setOnClickl.istener(new View.au
new id. In the text view. you willsee android:id="@+id | Clicklistener(){
message.
@Override
In the onCreate() method of SecondaryActivity,
you get the passed Intent by calling the getlntent() public void onCick{View view){
method. After you have the Intent, you can get the string Intent startlntent = new IntentlgetApplication
that was passed by using getStringExtra( ) method with
same key that was used in MainActivity.
Context(),
SecondaryActivity.class);
The below program give the getlntent( }method
on line 1 and the getStringExtra() method on line 2.
The passed message is displayed by called seeText( ) on startintent.putExtra( "com.talkingandroidl.MESSAGE
line 4.
"HeloSecondaryActivity");
1:Intent = getintent( );
startActivity(startlntent);
2: String message = Intent.getStringExtra
(com.talkingandroid.MESSAGE");
3:TextView MessageTextView= (Textview) find
ViewByldRid.message);
4:Message TextView.sefText(message); IMenu code excluded
Thebelowfigure shows both activities for this app.
Programs (A) and (B) Shows the code for
MainActivily.java and SecondayActivity.java. When In Program(B), the message passed inthelntent
Ardroid studio generates Activity code, the methods on is read and displayed,
CreateOptionsMenu() and onOptionsltemSelected( )are Secondary Activityjava
included This code handles menus
package com.talkingandroid.hour2application
Program (A) MainActivityjava
import android.comtent.Intent
package com.talking android.hour 2 application;
warrng:Xerox/Pholocopying ofthis bookisa CRIMINALAct. Anyonefound gultybUABLE to face LEGp
Mobile Application Development
import android.support. V7.app.ActionBar public void StartActivityForResult (Intent intent,
int request code, Bundle options)
Activity
import android.os.Bundle: here, request code value will be used later uniquely
import android. View.Menu; to identify the sub-activity that has returned as a result.

import android. View.Menultem Returning Result:


import android. View. TextView When our sub-activity is ready to retum, then call
setResult before finish to return a tesult to the calling
Dublic class Secondary Activity extends activity. The setResult method takes two parameters,
ActionBarActivity
result code and result data, represented as an Intent.
This result code is the "result" of running the sub-activity
generally, either Activity. RESULT_OK or
@Overide ACTIVITYRESULT CANCELLED.
protected void onCreate (Bundle Saved Q6. Explain native actions in the Intent.
hstanceState){
Ans: The following list shows some of the native actions
super.onCreate(Saved Instance State); that are available as static string constants ín the Intent
class. When we create implicit Intents, we can use these
setContentView{R.layout.Activity_Secondary); actions, they are known as Activity Intents, to start
Intent=getntent( ); Activities and sub-activities within our own applications.
String message = intent.getStringExtra 1. Action ALL_Apps This is handled by the
'com.talkingandroid.MESSAGE); launcher. It opens an Activity and that lists all
the installed applications.
TextView messageTextView =(TextView)
FindViewByld(R.id.message); 2. ACTIONANSWER : This is handled by tho
native in-call screen. It opens an activity and that
message TextView.setText(message); handles incoming calls
3. ACTION BUG_REPORT:This is handled by
/menu code excluded the native bug-report mechanism and it displays
an activity that can report a bug.

ACTION CALL : t is used only for activities


Q5. Explain how to get results from activities.. that replace the native dialer applications It brings
upa phone dialer and initiates immediately a cal
Ans: Ifan activity which is started via start Activity is
independent ofits patent, it does not provide any feedback by using the number supplied in the Intents data
when it closes. When a feedback is required, then we URI.

can start an Activity as a sub-activity that can pass results


ACTION_CALL_BUTTON: It initiates the
back to its parent. .

dialer activity. It triggered when the user presses a


By the help of android startActivityForResult() hardward "call button".
method, we can get result from another activity. Using
this method, we can send information from one activity ACTION DELETE : t starts an activity and let
us to delete the data that specified in the intent is
to another and vice-versa. The android startActivityFor data URI.
KesultMethod, requires a result from the second activity
(activity to be invoked). 7. ACTION DIAL: tbrings dialer application with
In such case, we need to overide the onActivity
the number to dial prepopulated from the intene's
data URI. This is handled by the native Android
esui method that is invoked automatically when second phone dialer.
activity returns result.
Method Signature: ACTION EDIT: t requests an activity and that
can edit the data at that intent's data URI.
There are two variants ofstartActivityForResut()
method. 9. ACTION INSERT: ltopens anactivity capable
of inserting new items into the cursor specified in

public void startActivityForResult(Intent intent.int the Intent's data URI.


request code )
ing : Xerox/Photocopying ofthis bookIs a CRIMINAL Act.Anyone found gulty is LIABLE to face LEGAL proceedilings
Mobile Application Development
Dlaler
ACTION PICK It launches a sub-activity andd| Replaclng Natlve
:
10. the
that lets to pick an item from the content provider Replacing tha native dialer application invojv
specified by the intent's data URI two step
the natlve dialer,
ACTION SEARCH: It is used to launch Intercept intents serviced by
a
11.
specific search activity. It is fired without a speclfic
select Initlate and managa outgoing
calls.
activity, then theuser will be prompted to 2.
from all applications that support
search,
applicatlon responds to Inte
The native dialer
This is user pressing the hardw
ACTIONSEARCH LONG_PRESS: actions corresponding to a
12. data using the tel:schema,
handled by the system to provide
a shortcut to a
call button, asking to view
key it using fhe tel:scheT
voice search. On the
hardware search making an ACTION_DIAL.request
enables you to intercept long presses. includes intent-fike
To-intercept these requests,
ACTION_SENDTO : lt launches an activity
to entires for your replacement diale
13. tags on the manifest
Activity that listens for the following actions
the intent's
send data to the contact specified by
data URI.
Intent.ACTION_ CAL_BUTTON; Thls action
It launches an activily and device's hardware cal
is broadcast when the
ne
14 ACTION_SEND
intent. The
that sends the data specified in the button is pressed, Create an Intent flter thatlister
needs to be.
recipient contact for this action as default action.
15. ACTION_VIEW: In this, viewasks that the data Intent.ACTION_DIAL: This lntent action, is ud
2.
is supplied in the intent's data URI be viewed
in
the most reasonable manner. Different appliations by applicatlons that want to initiate a phone cal
The Intent Filter used to capture this àctlon shoud
will handle view request depending on the URI be both default and browsable,
schema of the data supplied.
Intent.ACTION_VIEW: The view actlon is used
16. ACTION_ WEB_SEARCH: It opens the 3,
browser and to perform a web search that based by applicatlons wantingto vlewaplece ofdata
on the query supplied by using the Search Q8. Explaln how to use Intent to send SMS.
Manager.QUERY key. Ans: SMS technology is designed to send short tex r
Q7. Explain how to use intent to dall a number, messages between mobile phone. It provldes support fo
Ans: Android provides Built-in applications for phone sending both text messages and data message
calls, in some occasions we may need to make a phone Multimedla Messaging Servlce (MMS) messages allow
call through our application. This could easily be done users to send and recelve messages that Includ
by using implicit Intent with appropriate actions. Also, multimedia attachments such as a photos, videosand
we can use PhoneStatel.istener and TelephonyManager audlo.
classes, in order to monitor the changes in some telephony
states on the device. In most cases Its best práctice to use an Intento
send SMS using another application-typlcally the nati
Intent object Actlon to make phone call: SMS applicatlon-rather than implementlng a full SMS
You will use ACTION OCALL action to trigger bult client
in phone call functionality available in Androld device.
To do so, startActivity with an Intent.ACTION
Following is simple syntax to create an intent with SENDTO actlon Intent.Speclfy a target numberustn
ACTION CALL action. sms:schema notation as the Intent data. Include the
Intent calllntent new Intent (Intent. message you want to send within Intent payload using
ACTION CALL); an sms body extra,
You can use ACTION DIAL actlon Instead of Intentsmsintent new Intent(lntent.ACTION
ACTION CALL, In that case you wll have option to
modify hard coded phone number before maklng a call
SENDTO, Uri.Parse("ams:555123456')
irisead of making a direct call. smslntant.putExtra("sms_bodly", 'Prus wend
send me")
Intent object-Data/Type to make phone call:
To make a
phone call at a glven number 91-000- startActlvity(smslntent);
000-0000, you need to specify tel; as URI using set To attach fles to your message, add to
Dalal) method as follows Intent.EXTRASTREAM with the URI of the resour
Callnternt.setDala (Uri.parse("tell :91-000-000 | to atach and set the Intwnt type to the MIME type
(KHO")); the attach resource

LIABLE to face LRGAL prooge


VWarning Kerox/Phxotocopylng of thie book le a CRIMINAL Agt. Anyone tound gullty lo
Mobile Application Development
dingSMSmessages using theSMS manager: 4. SmsManager.RESULT ERROR
SMS messaging in Android is handled by the SMS NULL PDU To indicate a PDU (Protocol
class. You can get a reference to the SMS Description Unit) faihure.
n a g e r

using the static smsManager.getDefault method, 5.


nager SmsManager.RESULT ERROR
SmsManager smsManager = SmsManager. NO_SERVICE; To indicate that no ceular
service is curently available.
Defauh():
To send SMS messages. your application must The second pending Intet Parameter is fired only
h the SEND_SMS user-pemission, after the recipient receives your SMS message.

<user-permission android:name= "android. Confirming to Maximum SMS Message Size :


mission. SEND_SMS"/>
The maximum length of each SMS text message
can vary by carrier, but are typically kimited to 160
ding Text Messages
characters. As a result longer messages need to be broken
To send a text message, use sendTextMessage from into a services of smaller parts. The SMS manager
SMS Manager. passing in the address of your recept includes the divideMessage method, which accepts of
the next message you want to send, string as an input and breaks it into an Array List of
SmsManager SmsManager = SmsManager. messages, wherein is each less than maximum allowable
Defauk( }: size.
StringsendTo = "5551235"; You can then use the sentMultipartTextMessage
method on the SMS Manager to transmit the array of
String MyMessage = "Android supports
messages,
pgrarmmatic SMS Messaging!";
ArayList<String>messageArray smsManager
SmsManager. sendTextMessage (sendTo, null, dividemessage(myMessage);
Message. null nul);
ArrayList <Pendinglntent> sentlntents = new
The second parameter can be used to specity the ArrrayList<Pendinglntent>();
Sservice center to use. If you enter nul, the default
for(int i = 0; i<messageArray.size( ); i++)
wice center for the device's carier wil be used.
The final two parameters let you specifty Intents sentlntents.add(sentPl);
tack the transmission and successful delivery of you
smsManages.sendMultiparflextMessage(sendTo,
sages. To react to these Intents, create and register nil, messageAray.sentintents.nul);
adcast Receivers.
The sentlntent and deliverylntent Parameters in
How to track and confirm SMS Message the sendMultipareTextMessage method are Aray Lists
delivery. thatcan be uised to specify different pending Intents to
To track the transmission and delivery success of fire for each message part.
rOutgoing SMS messages, implement and register 3.2 BrOADCAST RECEIVERS.
aacast Receivers that listen for the actions you specity
reating the Pendinglntents you pass into the Q10. How to set up a Broadcast Receiver in
d lextMessage method. android application.
he first Pending Intent Parameter is fired when Ans: To set up a Broadcast Receiver in android
ESsage is either successfully sent or failed to send. application we need to do the following two-things.
at code for the Broadcast Receiver that receives
intent uill be one of the following: Creating a Broadcast Receiver.
2. Registering a Broadcast Receiver.
ctvity RESULT OK:To indicate a successful
transmission. Creating the Broadcast Receiver : Abroad
cast reçeiver is implemented as a subclass of
mManger.RESULT ERROR BroadcastReceiver class and overriding the
ENERIC FAILURE To indicate a
non
specific failure. onReceiver () method where each message is received
as a Intent object parameter.
ms ager.RESULT_ERROR
ADIOOFF To indicate the phoneradio is Eg: pubic class MyReceiver extends Broadcast
turned off. Receiver
ing Xerox/Photocopying
OPhotocopying of this book is a CRIMINAL Act. Anyone found guilty Is LIABLEtoface LEGAL proceedings
13.1
Mobile Application Development Intent filters to
service Imp
Q11. Explain using
@ovemide Intents.
Intent for an action to
onReceiver(Context context, an intent
is requested
public void Ans: If how does
Android kn
on a set of data, ?p
intent) performed servicé that request
to use to can deca
which application components
Intent filters, appliçation
using
data they support.
Toast.makeText(context, "Intent Detected" the actions and
to register an actiy
Intent handler
Toast.LENGTH LONG).show() As a potential
add an intent_filter tag to
or service
then w e have to
following tags,
manifest node and by using the
android:name attribute
Action: lt uses the
1. action being serviced
n a m e of the
specify the for each inten
2.
Registering Broadcast Receiver must have at
one action tag
least
strings and that are se
for specific broadcast intents Actions should be unique
An appication listens
a broadcast receiver in
AndroidManifest.xml
describing.
by registering for
to registerMyReceiver android.name attribute
file. Consider we are going 2. Category:It uses the action sho
the circumstances the
ACTION_BO0T_COMPLETED
event
system generated
once the Android system
specify under also inclu
which is fired by the system intent Filter tag can
be serviced. Each
has completed the boot process. the multiple category tags.
Broadcast Receiver, values or we can as
Following Fig. shows a Following are the'standard
observe specify our own categories that provided b
Registers for intents to
Android,
This category specifiestha
i) ALTERNATIVE:
this action should be available as an altemati
Android Broadcast to the default action performed on an item
System Receiver
this data type.
i) SELECTED_ALTERNATIVE: It is very simia
to the ALTERNATIVE category, but in t
Gets notfication when intents occur
category it will always resolve to a single adtio
by using the intent resolution, thi
application> SELECTED_ALTERNATIVE is used when
android: icon = "@drawable/ic_launcher" list of possibilities is required.

android:label = "@string/app_name" ii) BROWSABLE: It specifies an action that


available from within the browser. Within t
android: theme = "@style/Apptheme"> browser when an intent is fired, it will alway
include the browsable category.
<receiver android:name = "MyReceiver">
iu) DEFAULT: Set this to make a compone
<intent fiter> the default action for the data type specif
in the Intentfitler. It is necessary for activib
<action android:name="android.intent.action.
and that are lunched using an explicitinten3
BOOT COMPLETED">
u) HOME: By setting an intent filter category
<laction> home without specifying an action, then

</intent filter>
arepresenting it as an alternative to the nat
home screen.
<receiver> vi) LAUNCHER : By using this category it ma
an activity appear in
S/application> theapplicationlaunch
Whenever, your Android device gets booted, then
3. Data: This tag enables us to specifty whi
BroadcastReceiver MyReceiver
datatypes our components can act on. We
it will be intercepted by include several data tagsas appropriate. We
inside onReceive() will be
and implemented logic use any combination of the following attribul
executed. to specify the data our
component supports
NinXeroxdPhotocopying of this bookis a CRIMINAL Act. Anyone found guilty is, LIABLE to face LEGAL proceedi
Mobile Application Development
It specifies a valid hostname. i) The part of the URI scheme is "Protocol".
android: host:
eg: google.com Eg: http:, mailto: or tel:
andrdid.mimetype: it specifies which type of i) The host name or data authority is the section
data our component is capable of handling. of the URI between the scheme and the path.
ea<typeandroid:value= "vnd.android.
cusor.dir/**/>
Eg:developer.android.com
iv) The data path is what it comes after the
match any Android cursor.
It would authority.
ilandroid:path: It specifies the valid path values
that for URI. Eg:/training.
e g transport/boats/ 4. When we implicity start an activity, then more
d than one component is resokved from this process
en al android:port: It specifies valid ports for the
then all the matching possibilities are offered to
Se specified host.
the user. For broadcast receivers, each matching
android: scheme It requires a particular receiver will receive the broadcast intent.
scheme.
Q13. Explain how to find and use intents received
Ou
eg:Content or http. within an Activity.
Intent Filters. Ans: An application component is started through a
012. How ro resolve
simplicity intent, then it needs to find the action it is to
ns: In a start activity the proces of deciding which perform and the data to perform it on.
The main aim of intent
iity is called Intent resolution.
soluion is to find best intènt filter that match possible Start the activity to find the intent, call getintent,
of the following process, as shown in the following code,
thameans
Android puts together a list of all the intent filters @Overide
available from the installed packages.
public void onCreate(Bunde SavedinstanceState)
The intent filters that do not match the action or
category associated with the intent that being
Cuo
resolved are removable from the list. super.onCreate(SavedinstanceState);
Action matches are made only if the intent setContentView(R.layoutmain);
en filter includes the specified by the action. If
the intent fitler will fail the action then the string action=intent.getAction( );
match check if none of the actions matches. URI data=intent.getData( );
nat
int i) Intent filters must include all categories which
wa are defined in resolving intent for category
matching, but when we include the additional
To find thedata and action, use the getData and
getAction methods, respectively, associated with the
categories that are not included in the intent
with no categories the intent filter specified Intent. Use the Type-safe get<type>Extra methods to
extract the addition that stored in its extras bundle. The
yiD
then matches only intents with no categories.
getlntent method always returns the initial intent that
ter The intent's data URI is compared to the intent used to create the activity.
filters data tag. If these intent fitler specifies a
When we overide the onNewintent handler within
scheme, host/authority, path or MIME type, then
n our activity to receive and handle new intents after the
ab
these values are compared to the intene's URI. f
any mismatch happens then it will remove the activity has created,
intent filter from list. In Intent Filter, it specifies @Overide
nak
no data values and result will match with all Intent public void onNewlntent(lntent newlntent)
data values.
i)The MIME type i_ data type ofthe data being
e matched when matching data types, we can ITo Do React to the new intent
e use wildcards to match subtypes.
super.onNewlntent(new intent);
Eg: earthquakes/*

ng:Xerox/Photocopying of this bookis aCRIMINAL At. Anyone found guilty is LIABLE toface LEGAL proceedings
Mobile Application Development
3.3 NonFICATIONS.
Q14. What is a notification? Explain how to create and send notifications.
Ans: Notification: Android Notification provides short, timely information about the action happened ine
application, even it is not running. The notification displays the icon, title and some amount of the content ter

Create and Send Notifications

Following are the steps to be followed to create a notification.

Step-1 Create Notification Builder:


As a first step is to create a notification builder using
NotificationCompat.Builder.build(). you will use NotificationBuilder to set various Notification Propert
ike its smal and large icons, title, priority etc.

Step-2 Setting Notification Properties:


Once you have Builder object, you can set its Notiication properties using Builder object as per your requirem
But this is mandatory to set at least following:
A small icon, set by setSmalllcon()
A title, setby setContentTitle()
Detail text, set by setContenfText()

Eg mBuider.setSmallcon(R.drawable. notfication.icon);
mBuilder.setContent Title("NotificationAlert, CickMe!");
mBuilder.setContentText("Hi,This is Android Notification Detail!");
Step-3 Attach Actions
This is an optional p¡rt and required if you want to attach an action
with the notification. An action all
users to go dirèctly from the notification to an Activity in your
events or do further work. The action is defined
application, where they can look at one or mas
by a Pending Intent containing an Intent that starts an Activity
your application. To associate the
Pendinglntent with a gesture, call the appropriate method
NotificationCompat.Builder. For eg., if you want to start
Activity when the user clicks the notificátion text in
notification drawer, you add the Pending Intent
by calling setContentintent().
Step-4: Issue the Notification:
Finally, you pass the Notification object to the system by calling
NotificationManager.notify( )to send your notification.Make sure you call
Notificat onConmpac t.Builder.build() method on builder
of the options that have been set and return a object before notifying it. This method combine
new Notification
object:
NotificationManager mNotificationManager= (NotificationManager)getSystemService(Cont
NOTIFICATION.SERVICE);
l/notificationlD allows you to update the notification later on.
mNotification Manager.notify(notificationlD, mBuilder.build( ); -
Q15. How to display notificaitons on the Status Bar.
Ans: To display the notifications on the status
bar we can include the following steps as follows:
Step-1: We can create new Android project by using Eclipse and name as
a

notifications.
warning: XeroxPhotocopying of this book is a CRIMINAL Act.
Anyone found guilty is LIABLE to face LEGAL procee
3.13 Mobile Application Development
2: Add a class file named NotificationView.java to the sre folder of the project and also add a new
Notification.xml file to the reslayout folder.
step-3: The following code gves how topopulate the Notification.xmlfile as,

<?xml version= "I.0" encoding = "utf-8"?>

<LinearLaout xmns:android= "http://schemas.android.com/apk/res/android"


android:orientation="vertical"
android: layout_width="fill_parent"
android: layout height="fill_parent">
<TextView

android: layout_width="ill_parent"
android: layout _height="wrap_content"
android: text="Here are the details for notification"/>
<Linearlayout>
Step-4: The following code gives how to populate the Notification View.java file as,
package net.leam2develop.Notification;
import android.app.Activity,
import android.app.NotificationManager,
import android.os.Bundle;
public class NotificationView extends Activity

@Ovemide
public void onCreate(BundleSavedlnstanceState)

super.onCreate(SavelnstanceState);
setContentView(R.layout.notification);
I-look up the notification manager
service
NotificationManager nm (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
I-cancel the notification that we started

nm.cancelgetintent().getExtras( ).getlnt("'notificationD");

fep-5
For
AndroidManifest xml file and the folle ing statenent in bold as.

Sxmlversion= "1.0" encoding="utf-8"?>


erox/Photocopying of this book is a CRIMINAL Act. Anyone.found guilty is LMABLE to face LEGAL proceedings
Mobile Application Development
manifest xmlns:android="http:!/schemas.android.com/apk/res/android

package="het.leam2develop.Notification
android:versionCode="1"
android: version Name="1.0">
application android: icon="@drawable/icon"
android: label="@string/app_name>
activity android: name="MainActivity"
android: label="@string/app_name>

<intent_filter>
<action android: name="android.intent.action.MAIN"/>

"android.intent.category.LAUNCHER"/>>
category android: name
=

</intent filter>
</activity>
<activity android.name="NotificationView"

android: label = "Details of notification">

<intent_fiter>
<action android: name="android.intent.i tion.MAIN/>

<category android: name="android.intent.category.DEFAULT"/>

</jntent_filter>
s/activity>
</application>
<user-sdk android: minsdkversion =
"9"/>
user-permission android: name="android.permission.VIBRATE"/>

</manifest>

Step-6:
To main.xml file add the following statements in bold as,

?xml version="1.0" encoding="utf-8"?>


<Linearlayout xmlns: android = "http://schemas.android.com/apk/res/android".

android: orientation= "vertical"


android: ayout_width="file.parent"
android:layout_height="fill_parent">
<Button
android:id="@id/btn_display notif"
android:layout_width="fill_parent"
android: ayout_height="wrap_content"

Warning: Xerox/Photocopying ofthis book ls a CRIMINAL Act. Anyone found guiltyis LIABLE toface LEGAL proce
, 15
Mobile Application Development
android: text= "Display notification"/>

<Linearlayout>

Step-7:

TTo the ManiActivityjava file, finally add the following statements in bold as,
ckage net.learn2deve
levelop.Notifications
import android.app.Activity;

import android.os. Bundle:

import android.app.Notification;

import android.app.NotificationManager
import android.app.Pendingintent;
import android.content.Intent;
import android.view.View;
import android.widget. Button;
publicclass MainActivity extends Activity{.
int notificationlD= 1;

called when the activity is first created/

@Overide
publicvoid onCreate (BundleSaveinstanceState){

super.onCreate(SavedinstanceState);
setContenfView(R.layout.Main),
Button button=(ButtonfindViewByld(R.id.btn_display notifi);

buton.setOnChcklistener(fnew Button.onClickl.istener(){
public void onCick{View V){
dísplayNotification();

protected void displayNotification)

-Pendinglntent to launch activity if the user selects


Ithis notification
Intenti= new Intent(this, NofiticationView.Class);

putExtra("'notificationlD", notificationl
Fendinglntent pendinglntent = Pendinglntent.getActivity(this, o, i, o);
arning : XeroxlPhotoGOP
NIPhotocopying of this book is a CRIMINAL Act. Anyone found guilty is LIABLE to face LEGAL proceedings
Mobile Application Development
NotficationManager nm - (NotificationManager) getSystemService(NOTIFICATION SERVICE

Notification notf=new Notification


R.drawable.icon,
"Reminder:Meeting startsin 5 minutes"
System.Cument Time Millis);
CharSequence from = "System Alam";

CharSequence message = "Meting with customer at 3PM."

notif setLatestEventlnfo(this, from, message, pending Intent);


--100ms delay, vibrate for 250ms, pause for
/10ms
and the vibrate for 500ms=
notifi.vibrate = new longl 1(100, 250, 100, 500);
nm.notffnotification!D,notif;

Step-8:On the Android Emulator press F11 to debug the application.

Step-9:Click the display notification button and a notification that will appear on the status bar.
Step-10:The following fig. shows how to click and drag the status bar down to reveal the notifications.

Jan.3, 2011 ld
Android Clear
Notifications
O System Alam
Meeting with.

Fig.
Step-11:Clicking on the notification it will reveal the
Notification View activity. This causes the notification dismis
fromstatus bar
Q16. What is Toast ? Define Toast class and
describe the methods Toast class
Ans: Android Toast can be used to display information Toast class is used to show notification t
fo the the short period of time. A toast contains particiülar interval of time. After sometime it cisappe
message It doesn't block the user
to be displayed quickly and disappear after sometime. interaction.
The android.widget.Toast class is the subclass of Constants of Toast Class:
java.lang.object class. There are only 2 constants of Toast class wn
are given below:
Object

Toast
Warning :Xerox/Photocopying of thls book ls a CRIMINAL Act. Anyone found gullty ls LIABLE to face LEGAL Pro
3.17 Mobile Application Development
Constant
Deacripton
h Public
static final Displays view for the long
LONG duration of time
int 1INGT1H
Pubic static final Displays view for the short
int Length Shont duration of time

Methods of Tdaet Class


The widely used methods of Toast class are given
below
Method
Descrlptlon
Public Static Toast Makes the toast
makeText(content containing text and duration
context, charSequence
text, int duration)

Public void show() Displays toast It will remain on-screen for approximately
2 seconds before
Public void setMargin
fading out. The application behind it
Changes the horizontal and remains responsive and interactive while the toast is
(fioat horizontal vertical margin diffrence. visible.
Margin, float vertical
Margin) Cutomizing Toasts
We can modify a Toast by setting the
Q17. Explain how to display and customize display
toasts. position and assigning its alternative views or layouts.
The fallowing code explains how to align a toast
Ans: Toasts are transient notification that remains visible to thebottom of the screen by using the setGravity
for only a few second before fading out. Toasts do not
method.
interupt the active application because it do not steal
focus and are non-modal. Toasts are perfect for informing Context context = this;
users of events without forcing them to
open an activity String msg= "To bride and groom"
orread a notification, without interrupting foreground
int duration
application, they can provide an ideal mechanism for Toast.LENGTH SHORT;
alerting users to events occuring in the background
Toast toast =
Toast.makeText(context, msg,
services.
duration);
The toast cass includes a static makeText method int offsetX = 0;
to creates a standard toast display window. To construct
int offsetY = O;
a new toast, we have to
pass the current context, and to
display the text message and length of the time to display toast.setGravity(Gravity.Bottom, offsetX,
Ssed it into the makeText method. After
creating a toast, we offsetY);
can display it by method
calling show as follows
toast.show
Displaying a Toast Q18. Explain using Toast in Threads.
Context context = this,
Ans: Toast must be created and shown on the GUI
String msg= "To health and happiness!"; thread because they are GUI components, otherwise we
risk on throwing a cross-thread exception.
int duration =
Toast.LENGTH SHORT; The following program shows how a handler is
Toast toast =
Toast.makeText(context, msg, used to ensure that the toast is opened on the GUl thread,
duration);
Handler handler = new Handler():
toast.show();
private void mainProcessing(
The following Fig. shows as Toast

gXerox/Photocopylngofthebookiea CRIMINAL Act. Anyonefound gulity isLIABLEtoface LEGAL proceedings


3.18
Mobile Applicatlon Development
Thread thread = newThread(nul, doBackgroundThreadprocessing, "Background"';

thread.start()
new Runnable()
private Runnable doBackgroundThreadProcessing

public void runt)

backgroundThreadProcessing();

private void backgroundThreadProcessingl)

handler.post(dolUpdateGU;

method
/Runnable that executes the update GUI
private Runnable doUpdateGUI
= new Runnablel)

publicVoidrun()

context context=getApplicationContext( );
String msg-"To open mobile development!";
int during Toast. LENGTH SHORT;
Toast.makeText (context, msg, duration).showl );

Q19. How to create a toast notification in Parameter Description


android. Wrie the features of Toast.
Context lt's our application context|
Ans: In android, we can create a Toast by instantiating
an android. widget. Toast object using make Text( ) Message It's our custom message
method. The makeText( ) method will take three which we wantto stow in
parameters: application context, text message and the Toast notification
duration for the toast. We can display the Toast
notification by using Show( ) method. Duration It is used to define the
duration for notificationto
Following is the syntax of creating a Toast in display on screen
android applicátions. We have two ways to define the Toast duration
Toast.makeTex(context, "message", duratlon). either in LENGTH SHORT or LENGTH LONG to
show: display the toast notification for shortor longer periodo
time.

Warning: XerouPhotocopylng ofthisbook ls aCRIMINALAct. Anyonefound gulityls LIABLEtoface LEGAL procedine


s.19 Mobile Application
Development
Eg: Toast.makelext|MainActivitythis, "Details Saved Successfully.",Toast.LENGTH_SHORT)show),
Features ofToast:

t is an Android widget that is used to show a message for a short duration of time.
t disappears after a short time,
2
t doesn't block the Activity or Fragment when it runs.
3
ltcan be used to give feedback to the user regarding any operations, like from
submission etc.
o20. How to create a Custom Toast View,

And: If a simple text message isn't enough, you can create a customized layout for your toast notification. To
ate a custom layout, define a View layout, in XMLor in your application code, and pass the root View object to
theserView(View)method.

For example, you can create the layout for the toast
XML(saved as layoutcustom_toast.xml):
visible in the screenshot to the right with the following
<Linearlayout xmlns: android =

"http://schemas.android.com/apk/res/android"
android: id =

"@tid/custom_toast_container
android: orientation =
"horizontal
android: layout_width="fill_ parent"
android: layout height_"fil_ patent"
android:padding= "8dp"
android: background = "#DAAA"

<ImageView android : src =


"@drawable/droid"
android: layout_width="wrap_content"
android: layout height="wrap_ content"
android: layout_marginRight =
"8dp

TextView android: id = "@+id/text"

android :
layout width="wrap_contene"
android : layout height="wrap_content"
android : text color="#FFF"

<Linearlayout>
Notice that the ID of the Linear Layout element is "custom_toast_container". You must use this ID and the
of the XML layout file "custom toast" to inflate the layout, as shown here:

Layoutinflater inflater = getlayout Inflater( );


View
layout=inflater.inflate(R.Jayout.custom toast,(ViewGroup) find ViewByld(R.id.custom_toast_container);
lextViewtext= (TextView)layout.findViewByld(R.id.text);
text.setText("This is a custom toast");
Aerox/Photocopying of this book Is a CRIMINAL Act. Anyone found gulty is LIABLE to face LEGAL proceeding9
A
3.20
Mobile Application Development
Toast toast=new Toast(getApplicationContext( );
CENTER_VERTICAL, O, O)
toast.setGravity(Gravity.

t o a s t . s e t D u r a t i o n ( T o a s t . L E N G T H _ L O N G ) ;

toast.setview(layout):

toast Showl ): using


getlayoutinflater( ), and then infilato layout from XML
Layoutintlater with the
First, retrieve the
first parameter
is the layout resource 1D and the second is theroot view.
The
infiatelint, View Group).
in the layout, so now capture and detine tne
h i e infated layout
to find more View objects set sone
a new Toast with Toastlcontext) and
and the lextview elements. Finaly, create
content for the ImageView I
nen call setView(View) and pass it the inflated layout.
toast, such as
the gravity and
the auration.calling show( ).
properties of the custom layout by
the toast with your
You c a n n o w display

You might also like