8/12/2019 Intent Android method
1/81
AndroidApplication development
8/12/2019 Intent Android method
2/81
What is Android?
Android is a mobile operating system that is based on a modified version of Linux. It was originally
developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the
mobile space, oogle purchased Android and too! over its development wor! "as well as its develop#
ment team$.
oogle wanted Android to be open and free% hence, most of the Android code was released under
the open#source Apache License, which means that anyone who wants to use Android can do so by
downloading the full Android source code. &oreover, vendors "typically hardware manufacturers$
can add their own proprietary extensions to Android and customi'e Android to differentiate their
products from others. (his simple development model ma!es Android very attractive and has thus
pi)ued the interest of many vendors. (his has been especially true for companies affected by the phe#
nomenon of Apple*s i+hone, a hugely successful product that revolutioni'ed the smartphone
industry. uch companies include &otorola and ony -ricsson, which for many years have been
developing their own mobile operating systems. hen the i+hone was launched, many of these
manufacturers had to scramble to find new ways of revitali'ing their products. (hese manufacturers
see Android as
a solution / they will continue to design their own hardware and use Android as the operating sys#
tem that powers it.
(he main advantage of adopting Android is that it offers a unified approach to application development.
evelopers need only develop for Android, and their applications should be able to run on numerous
different devices, as long as the devices are powered using Android. In the world of smartphones, appli#
cations are the most important part of the success chain. evice manufacturers therefore see Android
as their best hope to challenge the onslaught of the i+hone, which already commands a large base of
applications.
AndroidversionsAndroid has gone through )uite a number of updates since its first release. (able 1#1 shows the vari#
ous versions of Android and their codenames.
Table1-1: A 2rief3istoryof Android4ersions
An droidverSion releASe dAte codenAme
1.1 6ebruary 200
1.5 70 April 200 8upca!e
1.9 15 eptember 200 onut
2 .0:2.1 29 ;ctober 200 -clair
2 .2 20 &ay 2010 6royo
2 .7 9 ecember 2010 ingerbread
7 .0 12 &arch 2011 3oneycomb
7.1
8/12/2019 Intent Android method
3/81
8/12/2019 Intent Android method
4/81
Featuresof Android
As Android is open source and freely available to manufacturers for customi'ation, there are no fi
hardware and software configurations. 3owever, Android itself supports the following featuresLite, a lightweight relational database, for data storage. 8hapter 9 discusdata storage in more detail.
Connectivit / upports &:--, I-?, 8&A, -4#;, =&(, luetooth "includ
A2+ and A4@8+$, i6i, L(-, and i&A. 8hapter B discusses networ!ing in more det
!essaging/ upports both & and &&. 8hapter B discusses messaging in more detai
Web bro"ser/ ased on the open#source ebCit, together with 8hrome*s 4B Davacript eng
!edia support/ Includes support for the following media< 3.297, 3.29E "in 7+ or &+
container$, &+-#E +, A&@, A&@# "in 7+ container$, AA8, 3-#AA8 "in &+E o
7+ container$, &+7, &II, ;gg 4orbis, A4, D+-, +?, I6, and &+
#ard"are support/ Accelerometer ensor, 8amera, igital 8ompass, +roximity enso
and +
!ulti#touch / upports multi#touch screens
!ulti#tas$ing/ upports multi#tas!ing applications
Flash support/ Android 2.7 supports 6lash 10.1.
Tethering/ upports sharing of Internet connections as a wired:wireless hotspot
Architectureof Android
In order to understand how Android wor!s, ta!e a loo! at 6igure 1#1, which shows the various laythat ma!e up the Android operating system ";$.
Home Contacts
APPLICATIONS
Phone Browser ...
APPLICATION FRAMEWORK
Activity Manager Window Manager Content Providers View System
Package Manager Telephony Manager eso!rce Manager "ocation Manager #oti$ication Manager
LIBRARIES ANDROID RUNTIME
S!r$ace Manager Media %ramework S&"ite Core "i'raries
(pen)" * +S %reeType We',it -alvik Virt!al Machine
S)" SS" i'c
LINUX KERNEL
-isplay -river Camera -river %lash Memory -river Binder /PC0 -river
,eypad -river Wi%i -river A!dio -rivers Power Management
8/12/2019 Intent Android method
5/81
(he Android ; is roughly divided into five sections in four main layersLite library provides database support so that an application can use it for
data storage. (he ebCit library provides functionalities for web browsing.
Android runtime/ At the same layer as the libraries, the Android runtime provides a set of core
libraries that enable developers to write Android apps using the Dava programming language. (he
Android runtime also includes the alvi! virtual machine, which enables every Android appli#
cation to run in its own process, with its own instance of the alvi! virtual machine "Android
applications are compiled into the alvi! executables$. alvi! is a speciali'ed virtual machine
designed specifically for Android and optimi'ed for battery#powered mobile devices with limited
memory and 8+=.
Application frame"or$/ -xposes the various capabilities of the Android ; to application
developers so that they can ma!e use of them in their applications.
Applications / At this top layer, you will find applications that ship with the Android device
"such as +hone, 8ontacts, rowser, etc.$, as well as applications that you download and install
from the Android &ar!et. Any applications that you write are located at this layer.
Androiddevicesin the mar$et
Android devices come in all shapes and si'es. As of late
?ovember 2010, the Android ; can be seen powering
the following types of devicesheight9:$ill>parent:=
7Te2tViewandroid5layo!t>width9:$ill>parent:android5layo!t>height9:wrap>content:android5te2t9:?string*hello:*=
=Te&t;ie"android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@This is m first Android Application@ 0B
=uttonandroid:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@
android:te&t?@And this is a clic$able button@ 0B
7*"inear"ayo!t=
2 1 (o save the changes made to your proJect, press 8trlHs.
3 ou are now ready to test your application on the Android -mulator. elect the proJect name in-clipse and press 611. ou will be as!ed to select a way to debug the application. elect Android
Application as shown in 6igure 1#25 and clic! ;C.
http://schemas.android.com/apk/res/androidmailto:@stringmailto:@stringhttp://schemas.android.com/apk/res/androidmailto:@string8/12/2019 Intent Android method
20/81
Figure1-'*
141 (he Android -mulator will now be started "if the emulator is loc!ed, you need to slide the unlocbutton to unloc! it first$. 6igure 1#29 shows the application running on the Android -mulator.
Figure1-'+
111 8lic! the 3ome button "the house icon in the lower#left corner above the !eyboard$ so that it noshows the 3ome screen "see 6igure 1#2G$.
8/12/2019 Intent Android method
21/81
Figure1-',
1'1 8lic! the application Launcher icon to display the list of applications installed on the device. ?otethat the 3elloorld application is now installed in the application launcher "see 6igure 1#2B$.
Figure1-'2
8/12/2019 Intent Android method
22/81
hichAvdille used to testyour Application?
@ecall that earlier you created a few A4s using the A4 &anager. o which one will be
launched by -clipse when you run an Android applicationN -clipse will chec! the target that
you specified "when you created a new proJect$, comparing it against the list of A4s that youhave created. (he first one that matches will be launched to run your application.
If you have more than one suitable A4 running prior to debugging the application, -clipse will
display the Android evice 8hooser window, which enables you to select the desired
emulator:device to debug the application "see 6igure 1#2$.
Figure1-'3
#o" 7t Wor$s
(o create an Android proJect using -clipse, you need to supply the information shown in (able 1#2.
Table1-': +roJect6iles8reatedby 0efault
prope rties descript ion
+roJect name (he name of the proJect
Application name A user#friendly name for your application
+ac!age name (he name of the pac!age . ou should use a reverse domain name for this .
8reate Activity (he name of the first activity in your application
&in 0C 4ersion (he minimum version of the 0C that your proJect is targeting
8/12/2019 Intent Android method
23/81
In Android, an Activity is a window that contains the user interface of your applications. An application
can have 'ero or more activities% in this example, the application contains one activity< MainActivity .
(his MainActivity is the entry point of the application, which is displayed when the application is
started. 8hapter 2 discusses activities in more detail.
In this simple example, you modified the main.2ml file to display the string (his is my first AndroidApplicationFM and a button. (he main.2ml file contains the user interface of the activity, which is dis#
played when MainActivity is loaded.
hen you debug the application on the Android -mulator, the application is automatically installed on
the emulator. And that*s it / you have developed your first Android applicationF
(he next section unravels how all the various files in your Android proJect wor! together to ma!e your
application come alive.
Anatom of an AndroidApplication?ow that you have created your first 3ello orld Android application, it is time to dissect the
innards of the Android proJect and examine all the parts that ma!e everything wor!.
6irst, note the various files that ma!e up an Android proJect in the
+ac!age -xplorer in -clipse "see 6igure 1#70$.
(he various folders and their files are as followsname defined in the strings.2ml file.
(here is one activity in the application representedby the MainActivity.1ava file. (he label
displayed for this activity is the same as the application name.
ithin the definition for this activity, there is an element named 7intent3$ilter=progress.ialogsetHrogress4/
>progress#andlersend6mpt!essage4/
F
F0D
>progress#andler ne" #andler/ I
mailto:@Overridemailto:@Override8/12/2019 Intent Android method
43/81
public void handle!essage!essage msg/ I
superhandle!essagemsg/
if >progress B 144/ I>progress.ialogdismiss/
K else I
>progressMM
>progress.ialogincrementHrogress1/>progress#andlersend6mpt!essage.elaed4E 144/K
KKF
F
?(verride
protected-ialogonCreate-ialog/intid0Eswitch/id0Ecase;5ret!rnnewAlert-ialog.B!ilder/this0**...
**....create/0D
case 1:
>progress.ialog ne" Hrogress.ialogthis/F>progress.ialogset7con5dra"able icon/F>progress.ialogsetTitleJ.o"nloading files111@/F>progress.ialogsetHrogressStleHrogress.ialogSTR%6>#578TA%/F>progress.ialogsetutton.ialog7nterfaceHS7T7;6E J#ide@E ne"
.ialog7nterfacenClic$%istener/ Ipublic void onClic$.ialog7nterface dialogE
int "hichutton/IToastmakeTextgetaseConte&t/E
J#ide clic$ed@E
Toast%689T#>S#5T/sho"/K
K/F
>progress.ialogsetutton.ialog7nterface869AT7;6E JCancel@E ne"
.ialog7nterfacenClic$%istener/ I
public void onClic$.ialog7nterface dialogE
int "hichutton/I
ToastmakeTextgetaseConte&t/E
JCancel clic$ed@E Toast%689T#>S#5T/sho"/
KK/F
return >progress.ialogFK
ret!rnn!llDF
F
' 1 +ress 611 to debug the application on the Android -mulator. 8lic! the button to display the prog#ress dialog "see 6igure 2#B$. ;bserve that the progress bar will count up to 100.
mailto:@Overridemailto:@Override8/12/2019 Intent Android method
44/81
Figure'-2
#o" 7t Wor$s
(o create a progress dialog, you first create an instance of the Progress-ialog class and set its
variousproperties, such as icon, title, and styleprogress-ialog9newProgress-ialog/this0D
>progress-ialog.setcon/.drawa'le.icon0D>progress-ialog.setTitle/-ownloading$iles...:0D>progress-ialog.setProgressStyle/Progress-ialog.ST"+>H((#TA"0D
ou then set the two buttons that you want to display inside the progress dialogprogress-ialog.setB!tton/-ialognter$ace.BTT(#>P(STV+NHide:Nnew-ialognter$ace.(nClick"istener/0E
p!'licvoidonClick/-ialognter$acedialogNintwhichB!tton0EToast.ma$e%e&t/getBaseConte2t/0NHideclickedO:NToast."+#)TH>SH(T0.show/0DF
F0D>progress-ialog.setB!tton/-ialognter$ace.BTT(#>#+)ATV+NCancel:Nnew-ialognter$ace.(nClick"istener/0E
p!'licvoidonClick/-ialognter$acedialogNintwhichB!tton0E
Toast.ma$e%e&t/getBaseConte2t/0NCancelclickedO:NToast."+#)TH>SH(T0.show/0D
8/12/2019 Intent Android method
45/81
F
F0Dret!rn>progress-ialogDF
(he preceding causes a progress dialog to appear "see 6igure 2#$.
Figure'-3
(o display the progress status in the progress dialog, you need to use a Handler obJect to run abac!#
ground threadprogress9;D>progress-ialog.setProgress/;0D>progressHandler.send+mptyMessage/;0D
(he bac!ground thread counts up to 100, with each count delayed by 100 millisecondsprogressHandler9newHandler/0Ep!'licvoidhandleMessage/Messagemsg0Es!per.handleMessage/msg0Di$/>progress=94;;0E>progress-ialog.dismiss/0D
FelseE>progressRRD
>progress-ialog.incrementProgressBy/40D>progressHandler.send+mptyMessage-elayed/;N4;;0DF
F
FD
hen the count reaches 100, the progress dialog is dismissed.
8/12/2019 Intent Android method
46/81
lin$ingActivitieSuSingintentS
An Android application can contain 'ero or more activities. hen your application has more than
activity, you may need to navigate from one activity to another. In Android, you navigate betw
activi# ties through what is !nown as an intent.
(he best way to understand this very import ant but somewhat abstract concept in Android i
experi# ence it firsthand and see what it helps you to achieve.
(he following (ry It ;ut shows how to add another activity to an existing proJect and then navig
between the two activities.
%in$ingActivities "ith intents
1 =sing theActivities proJect created earlier, add the following statements in bold to theAndroidMani$est.2ml fileT7T%6/
setContentView/.layo!t.main0D"og.#(tagNMntheonCreate/0event:0DF
public boolean onPe.o"nint $eCodeE Pe6vent event/I
if -$eCode Pe6ventP6RC.6>.HA.>C68T65/I
startActivitne" 7ntentJ inacsrmunivACT7;7TR'@//F
mailto:@Overridemailto:@Overridemailto:@Overridemailto:@Override8/12/2019 Intent Android method
49/81
K
return falseFK
p!'licvoidonStart/0E**...Fp!'licvoidonestart/0E**...F
p!'licvoidones!me/0E**...Fp!'licvoidonPa!se/0E**...Fp!'licvoidonStop/0E**...Fp!'licvoidon-estroy/0E**...FF
2 1 +ress 611 to debug the application on the Android -mulator. hen the first activity is loaded, clic!the center of the directionalpad "see 6igure 2#17% on a real device this can be achieved bypressing
down the trac!ball$. (he second activity will now be loaded.
Figure'-1(
#o" 7t Wor$s
As you have learned, an activity is made up of a =I component "for example, main.2ml$ and a class
component "for example, MainActivity.1ava$. 3ence, if you want to add another activity to aproJect,
you need to create these two components.
In the AndroidMani$est.2ml file, specifically you have added the followingheight9:$ill>parent:==Te&t;ie"
android:laout>"idth?@fill>parent@android:laout>height?@"rap>content@android:te&t?@Hlease enter our name@ 0B
=6ditTe&t
android:id?@DMid0t&t>username@android:laout>"idth?@fill>parent@android:laout>height?@"rap>content@ 0B
=uttonandroid:id?@DMid0btn>P@android:laout>"idth?@fill>parent@android:laout>height?@"rap>content@android:te&t?@P@ 0B
7*"inear"ayo!t=
' 1 Add the following statements in bold to [email protected]
6ditTe&t/ find;ie"7d5idt&t>username/F
00---set the data to pass bac$---dataset.atausernamegetTe&t/toString///
set5esult56SPE data/
00---closes the activit---
finish/F
KK/FF
F
(1
Add the following statements in bold to the MainActivity.1ava file!sername0D
**333setthedatatopass'ack333data.set-ata/ri.parse/t2t>!sername.getTe2t/0.toString/000Dsetes!lt/+S"T>(,Ndata0D
**333closestheactivity333$inish/0D
(he setes!lt/0 method sets a result code "either +S"T>(, or +S"T>CA#C+""+-$ and the data
ntent obJect$ to be returnedbac! to the calling activity. (he $inish/0 method closes the activity an
returns control bac! to the calling activity.
In the calling activity, you need to implement theonActivityes!lt/0 method,
which is called whenevan activity returnsusername
6ditTe&t/ find;ie"7d5idt&t>username/Ft&t>usernameset#intdefault8ame/
**333getthe(,'!tton333
B!tton'tn9/B!tton0$indViewByd/.id.'tn>(,0D
**333eventhandler$orthe(,'!tton333'tn.set(nClick"istener/newView.(nClick"istener/0E
**...F0DF
( +ress 611 to debug the application on the Android -mulator. hen you clic! the center button othe directional !eypad, notice that the +ditTe2t view in the target activity displays the hint text
"see 6igure 2#1G$.
Figure'-1,
8:T6 (he hinttext isplaceholdertext that iscommonlyfound in+ditTe2t views.Itisdisplayedwhen the viewisempty, and it disappearsas soon as the user types somethingintoit. Itisusefulfor displayinghintsthat tellusers what type of informationthey shouldenter.
8/12/2019 Intent Android method
59/81
#o" 7t Wor$s
(o use the ntent obJect to carry data to the target activity, you made use of a B!ndle obJect!sername.setHint/de$a!lt#ame0D
Callinguilt-inApplications using intents=ntil this point, you have seen how to call activities within your own application. ;ne of the !ey
aspects of Android programming is using the intent to call activities from other applications. Inpar#
ticular, your application can call the many built#in applications that are included with an Android
device. 6or example, if your application needs to enable a user to call a particularperson saved in
the 8ontacts application, you can simply use an ntent obJect to bring up the 8ontacts application,from which the user can select the person to call. (his enables your application to present a consis#
tent user experience, and enables you to avoid building another application to retrieve all the con#
tacts in the 8ontacts application.
(he following (ry It ;ut demonstrates how to call some of the built#in applications commonly
found on an Android device.
Calling uilt-in Applications
8/12/2019 Intent Android method
60/81
' 1 Add the following statements in bold to the main.2ml fileparent:
android5layo!t>height9:$ill>parent:=
=uttonandroid:id?@DMid0btn>"ebbro"ser@
android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@Web ro"ser@ 0B
=uttonandroid:id?@DMid0btn>ma$ecalls@
android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t@!a$e Calls@ 0B
=uttonandroid:id?@DMid0btn>sho"!ap@
android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@Sho" !ap@ 0B
=uttonandroid:id?@DMid0btn>chooseContact@
android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@Choose Contact@ 0B
7*"inear"ayo!t=
( 1 Add the following statements in bold to the MainActivity.1ava filePC,
ome examples of data include the following(,0EToast.ma$e%e&t/thisNdata.get-ata/0.toString/0NToast."+#)TH>SH(T0.show/0Dntenti9newntent/android.content.ntent.ACT(#>V+WNBri.parse/data.get-ata/0.toString/000DstartActivity/i0D
FF
F
In the case of the 8ontacts application, when you choose aparticular contact "using the ACT(#>PCconstant$, an =@L containing the contact selected is returned, li!e this;76WE
;76W/Fiset.ata
8/12/2019 Intent Android method
68/81
(he setType/0 method explicitly specifies the &I&- data type to indicate the type of data
return. (he &I&- type for ContactsContract.Contacts.C(#T+#T>TP+ is vnd.android.c!rsor
.dir*contact:.
esides specifying the action, the data, and the type, an ntent obJect can also specify a category
category groups activities into logical units so that Android can use it for further filtering. (he n
section discusses categories in more details.
(o summari'e, an ntent obJect can contain the following informationname:=7intent3$ilter=
7actionandroid5name9:android.intent.action.MA#:*=7categoryandroid5name9:android.intent.category."A#CH+: *=7*intent3$ilter=7*activity==activit android:name@!ro"serActivit@
android:label?@Dstring0app>name@B
=intent-filterB
=action android:name?@androidintentaction;76W@ 0B
=action android:name?@ inacsrmuniv!ro"ser@ 0B=categor android:[email protected](#+:*=
=uses-permission android:name@androidpermission78T6586T@ 0B
7*mani$est=
( 1 Add the following statements in bold to the main.2ml fileparent:android5layo!t>height9:$ill>parent:=7B!ttonandroid5id9:?Rid*'tn>we''rowser:android5layo!t>width9:$ill>parent:android5layo!t>height9:wrap>content:android5te2t9:We'Browser:*=7B!tton
android5id9:?Rid*'tn>makecalls:android5layo!t>width9:$ill>parent:android5layo!t>height9:wrap>content:
android5te2t9:MakeCalls:*=7B!tton
android5id9:?Rid*'tn>showMap:
android5layo!t>width9:$ill>parent:android5layo!t>height9:wrap>content:android5te2t9:ShowMap:*=
7B!ttonandroid5id9:?Rid*'tn>chooseContact:
http://schemas.android.com/apk/res/androidmailto:@drawablemailto:@stringmailto:@stringmailto:@stringhttp://schemas.android.com/apk/res/androidmailto:@+idmailto:@+idmailto:@+idmailto:@+idhttp://schemas.android.com/apk/res/androidmailto:@drawablemailto:@stringmailto:@stringmailto:@stringhttp://schemas.android.com/apk/res/androidmailto:@+idmailto:@+idmailto:@+idmailto:@+id8/12/2019 Intent Android method
70/81
android5layo!t>width9:$ill>parent:android5layo!t>height9:wrap>content:android5te2t9:ChooseContact:*==uttonandroid:id?@DMid0btn>launch!ro"ser@
android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@%aunch ! ro"ser@ 0B
7*"inear"ayo!t=
) 1 Add the following statements in bold to the MainActivity.1ava filelaunch!ro"ser/Fb*setnClic$%istenerne" nClic$%istener/
I
public void onClic$;ie" arg4/
I
7ntent i ne"7ntentJ inacsrmuniv!ro"ser@/Fiset.ataparent@android:laout>height?@fill>parent@ B
=Web;ie"android:id?@DMid0Web;ie"41@
android:laout>"idth?@"rap>content@android:laout>height?@"rap>content@ 0B
=0%inear%aoutB
+ 1 Add the following statements in bold to the MyBrowserActivity.1ava filename:=7intent3$ilter=
7actionandroid5name9:android.intent.action.MA#:*=7categoryandroid5name9:android.intent.category."A#CH+:*=7*intent3$ilter=7*activity=7activityandroid5name9:.MyBrowserActivity:android5la'el9:?string*app>name:=7intent3$ilter=
7actionandroid5name9:android.intent.action.V+W:*=7actionandroid5name9: in.ac.srm!niv.MyBrowser:*=7categoryandroid5name9:android.intent.category.-+%A"T:*==categor android:name?@ inacsrmunivApps@ 0B
http://schemas.android.com/apk/res/androidmailto:@drawablemailto:@stringmailto:@stringmailto:@stringhttp://schemas.android.com/apk/res/androidmailto:@drawablemailto:@stringmailto:@stringmailto:@string8/12/2019 Intent Android method
75/81
7dataandroid5scheme9:http:*=7*intent3$ilter=7*activity=7*application=7!ses3sdkandroid5minSdkVersion9::*=
7!ses3permissionandroid5name9:android.permission.CA"">PH(#+:*=
7!ses3permissionandroid5name9:android.permission.#T+#+T: *=7*mani$est=
In this case, the following code will invo!e the MyBrowerActivity activityV+WNBri.parse/http5**www.amaUon.com:00DiaddCategorJ inacsrmunivApps@/FstartActivity/i0D
ou add the category to the ntent obJect using the addCategory/0 method. If you omit the
addCategory/0 statement, the preceding code will still invo!e the MyBrowerActivity activity
because it will stil l match the default category android.intent.category.-+%A"T:.
3owever, if you specify a category that does not match the category defined in the intent filter, it
will not wor!height9:$ill>parent:==Te&t;ie"android:laout>"idth?@fill>parent@
android:laout>height?@"rap>content@android:te&t?@#ere are the details for the notification@ 0B
7*"inear"ayo!t=
) 1 +opulate the #oti$icationView.1ava file as followsS65;7C6/F
00---cancel the notification that "e started
nmcancelget7ntent/get6&tras/get7nt Jnotification7.@//FK
K
*1 Add the following statements in bold to the AndroidMani$est.2ml file