Mad 3
Mad 3
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
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.
</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
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,
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.
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"
<intent_fiter>
<action android: name="android.intent.i tion.MAIN/>
</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,
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.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;
@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();
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
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
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
thread.start()
new Runnable()
private Runnable doBackgroundThreadProcessing
backgroundThreadProcessing();
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 );
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"
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:
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):