0% found this document useful (0 votes)
64 views209 pages

Android All Questions Combined

Uploaded by

Ash
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)
64 views209 pages

Android All Questions Combined

Uploaded by

Ash
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/ 209

Data D

Pago OL

Mobtte PPLicatioON o

maila a Sofrtulasu alcatian olesigntd


to LLle m, mobile olees, Such as Jmarit
Phonsamd dahlets, Hather ham deskt
lagte omfuterA. obila al a Lusually
atad, to Lmformm -to he ddmands_aamd
Lmitatmi of the duuices amd aldo
Haae acivamiag
ci amy specialiasea Caabit
Hhi have mobile afpltcazion aldo may
h Kmotul a Cm a Web app, cnline
appiPhan af o SmatPhne ap.

Theu seweral dulek o afp Coaml


aYnilable -

ci Coaming QP
C Bncductivity aps
cli) ifeshylaamd emtortamment ap
uls inckudls mobil CammRXCe a}'s
oHher alp Pchase
Lysed goods mline Such oas
Amam 0 eßau avel apps hat hlP
Date

C8Bookhg toes
a oavelen in mamu iays
amo ichets fmding- thein_LsayHrogh etc.
maps and gealecatian avel dra amc
mo utilitu a dLch as haalth afs
baHCode Scamnets.

ChanacteáifcA
inctttimgs Coa
Lde Chm do mtorms
dalelefmant an aP mobtle, bu Lunles
noie ~hings altan lutih 4he meds amd goa
enobab huetiig
moYe than hulping Many paople hale Shoxt
OtAmtim Sams amd I illmaa uowh
aPp diffCulttp maiaate dham the uA esLd
Veu tast
unable to acco he Sngomau m
Auicau Mauigatm amd 10
Ambiaurty imhove
h de experdemca
ped n hts era mo gn Utacs Lsaiting
atcular4, Leham all they have o
Jaca at loading Symbo m 4h
Scritn. 1hid dufe of Sitaatin ACHO
Dato L
Pagel

am even -9mouabing J88us. ecu


amÎmfataact teatura jor mooilo al.
aCnos Nautous8 mdusltes LHh mamy
aPPicatimstoaing- osomal_amd emsidive
Snomatiom 0X Cradit 7 dekit Cand datatk
Kecurt is am absaluto muudt
cka aff uses mult be Pratectod a a
egellevel. 9 an c he Caiical
SLaauisamemt of asuccoive mmobile aP

Somch oPhions 4 Ye SPmple buc


ffectne fo LL&ens. 1
PetoLefdeS ham 0 do uke he app. the
abilidto Sea1ch ethu he afPP m -he
ntwmet i mfartamt

Rusb No-liffcatian uahush moarh-fiicatton


Cam be toct g1aPhica
a Comainatim of both to demd
the Cmtac hel she may be
Kalevemt amd Ksmali3e Push
inttad m.
motfica
aa hulptul. Thy Shoulel a amd afe
at aticulasus isen to fnteset_of -hm.
Fugol 0S

Usens tsdbaca he bust ulay ooff a


making a hfeceaf
o asla use tsel auoid the app
app.
Luhich udens tll youwwhat thuy Wamt
amd ilta to tha eudbaca jnto Lhat
mut be a addiham 0 detactian
kSy Hutng, a fudbach butom om he ayP
au emakle the clismt do toll yolu hat
hy thina lloulol make it ltovs.
uPdates mctul hove tudback l Can
Soxt ut houl to malal OLGL aa
more Selevemt to Ldes mddemd ufolates
Brolol' Cal un uch a ulaythat ut bLComu
ma ePdemt amd effectte to ule.
onilsot hauig mobtl aP
C Cubtamod don't have to play the
tuatnga
ames
CD Tncoulase usBomerd emagememt.
C) P Jtucuce last
(iv) Hore bemfitial fx uslanerk
The Help Or
Architevture With
do you Mean
by Android?Explain the Android
a).what
EXxample

Ans: Android OS is an oper-source Linux -based operating sysitenm


mobile devices
Ine
being developed by the Open Handset Alliance and Google
number of native appcado p
petatng operating system has a number
o n 9 telephony, messaging, emailin9, contact rmanageo
endar, entertainment multimedia ex perience, location Servic

mapping, social interaction, etc

software stack of components to support


mobile
oevce ta
architecture is a
ndroid of c/c++ libraries
wnic are
epo
soware stack contains a Linux Kernel, collection
r framework services, runtime, and applicauon
through an application

archtecture those are


rollowing are main components ot android

1 Applications
Android Framework

Androld Ruitime

4Piattorm Libraries
5 Linux Kenel

main component in androidl to provide its


in these compornients, the Linux Kernel is the
D a v i k Virtual Machine
(DVM) which is responsible
functions to moblie and
operating system
Tor runing a mobilie applicatict

architecture with different components.


android
1S the pictornial representation of
Following
Application
Home Contacts Alarm Tme
Camera SMS
Calendar Music Clock Email
Gallery Phone

Location Service
NFC Service
Activity Manager Package Manager

View System
Windows Manager Notification Manager oen

ndrol Kuntime

Core Libraries
Dalvik Virtual Machine ygote Androld Debug Bridge

Pattorm ibraties

SGL
Openal Graphics
MediaFramework
Freetype
SSL sQLite Surface Manager

n i Xetnel

Display Driver WHFI Driver Audio Driver Bluetooth Driver


Memory Driver
Camera Driver USB Driver Binder1PC Driver

Applications
of the androld architecture is Applications, The native and third-party applications
The top layer
ke contacts, email, music, gallery, clock, games, etc: Wwhatever we will build those will be installed

on this layer onily,

The application layer runs within the Android run time using the classes and services made

available from the application tranewo.

Application Framework
The Application Framework provides the classes used to create Android applications. It also
the user intertace ano
provides a generic abstraction for hardware accesS
and manages
o n resources lt basically provides the services
s s and
make that class through which we can createparucu
ular
helpful for the Application creation
caon framework includes services like
telephony service, location services, notihicatio
ron c e , view
system, etc which we can use for
fequirerments application development as per oul

Android Runtime
naroid Runtime environment is an
important part of Android rather than an internal
scomponents libraries and the Dalvik virtual machine. The Android part
lilke core and

gne that powers our applications along with the libraries and it forms the basis
run time
Ppication framework
1of te
Daivik Virtual
Machine (DVM) is a
register-based virtual machine
w.tt 15 Specially designed and optimized like Java Virtual Machine
nstances for android to ensure that a device can run
efficientiy. it reles on
threading and low-level memory iu pie
the Linux kermel tor
management
Thecore libraries in android
runtime will enable us
standard JAVA
programming language.
to
implement android applications Using

Platform Libraries
The Platform
Libraries includes various C/C++
SSL libe, Graphics, core libraries and
SQuite, Webkit, Media, Surface Java-based libraries such as
Android development Manger, OpenaL, etc. to provide
Ihe
tor support
following are the
summary details of some core
development android libraries
available for android

Media library for playing and


The Surtace
recording audio and video formats
manager library to provide a
SGLand OpenGL Graphics libraries for 2Ddisplay
and 3D
management
SQLite is for database graphics
support and Freelype for font
Web-Kit for web browser support and SsL for internetsupport
security.
Linux Kernel
Linux Kernel is a bottom
layer and heart of the android
such as
display drivers, camera drivers, architecture. It
manages all the drivers
which Bluetooth drivers, audio
are
rmainly required for the android device
drivers, memory drivers, etc.
during the runtime.
The Linux Kermel will
provide an abstraction layer between the
remalnder of the stack It is device hardware and the
hogeinen, resource etc.
responsible for memory management,
power management, device
xplain th Juatusu el eo th dmoboid UALond
ndoid l.0 -
commesical the
euLom

ncuoid 0, the bat


uptembet 83, Ao08
OOU, 100s nel eased
0n

APL Juel -1
feotunes- alllooin ppltaliom olownloads
ndoid Hake the mdket applbiecaluon
and upolate thouh
Camea duppovt Guaildpplbtoluom
raa mchonizaduon with
calende Hops ynthoni alon
GooqLe cohtacts ,

mpo
Media Ployes mablum9 mamagment,
,

and ploybock medi les.


Notiicalom appeon tlatus
bat
Vaice iale, Youdlube video floyeh
wGond bluttboth duppovt
ndbtoid 4 petit our)
smduoicl 1t update a s
On febu 9, doo the
teleased.he updoie nesoluedl bugs, thamqeolhe
dndboid AP amd addedl o numbet t 4tatne8
APL. lewtl
feastuwtes-
Detal amd Aeuteus Ouailable whem a uA Stavches

oY busi ness on Haps


onger call JimeN plus abiWty
Ju show(hidle the dialpoo
abilty daue otlach ments in mesages
uppovt added Y mo9ee in dyTem ay Outs.
dndtoid 1s (Cop (ake) .
udas
On pd 8, e009, Jh Andpicl 1S updaile
e l eosed, based n u x kernal 86 8
APL. leuel 3
Fealuhes
wth tet
irtual keyboavds
PPotor thid- pavdy Cuslom u 0vds
pved' cuon Qmc use obeti onaxy
Suppovt idgebs in feG-4 and
V i d e o hecording and ployback
3 (-P fomats
And teNLo dppoat fov bluethoth
duto pouvung
poste atwtesin web br0dsse
Copy md wideos and picustes
o n Youtube

to up-load
ALi
utoAotaten epton
moted creem troui on.
One touch -a Ctess a conlacd carolTom tal og
Duemt
dncbroid 6 (Domut)-
On tpt 1S, d009 nduid 6- dubbed Donut -uw
neleasedl, based on nux ktsnel &6: 1.
APL Level
feotuunes
Voice amd texi eiby &eorth on wtb
incudle their conlent
dbilhy ov oluelspers
6e0rch Auli
in
mose
Cammesa amd cam3t CoTde)
alleny
Prlegated
peech mthesi3 mgine
Hull- inguol
ulect uuldiple phots to
lbility oust6
delchon and comesa appbcatoy
Spee d improuement
in
sea2 ching
d o i d A.o (Ecdaiv) LOas
. 0 9Dk
the dndsuoid
Otobey &1, Avo9,
on kemel 6.27
inut
l2aseo based om
AfL
feabwes
xpamded decount ymt
Buuctooth -1 uppost and alet o cal
'bit t tap a (orttacts phole
HS T ommail the peaon
all sawed SMS
and HHS Hessages,
Abiliy to dtach
delete th oldest
oth dhe added abilby to

messages în a tonusatDm
Neuo camea eatvre lash, zom, >cene MOoledh
fetah ed brouáe uL oith bok mastk thoumbnais
Improued oqle Haps 1.9
&uppost for MOvre stem e s and aesalutions
Addihon b ve oallpapeha8.

Andsto'ol 8.01 eclaiv-


Released date Dec 3 0oo)
APL lul 6

MtnoY APL change, ugxes ndamedouk


behauiorsal chonges
vndboid 1 fclaiy
Release date Jon I, 2ol0
AP leuel
Minor am endmenti o he APT and bug xes
dbbid 8:8 fou
HO do, 2oto, the gDK tor mduaid e 00

eLenged, based m lnux Keme 632

Feate
&peec Am.bn nd porfooytam ce 6ptumuaouon
duleraition o hyome's 6 JauaScript Imaine
the BrouOsel applbcoton
Device He oging
ppost o dndboiod cloud o
6uice
US8 ethei nq and -hot pot wnduonalrty
oues a HBale netzsavk
optiomte dis able data access
Opdaded Havket applicatuom
Ouick &uod-ching biluwum ulti ple teybot yd Janguayes
amd thuh dictonaie
uumeic md allbhamum@uc 1aA LDrds
Sppot fov
to expamdable
Sppost tor installinq opelcalims
memor
AclobeLash dupot
UehsLOn2-91
Aeloase date3ept 91, o10
anmd pefommamce
u xes daeuty updaTes
improuememta

Josion & 9 2 -
Reloase data Son 81, 9o1)
ialues that
Hin bug ixes inctuding 3H3 Aotding
e u us
akectpd the
One

Veson 93 Release date Nou 91,o


uooCunty tp dates
dndaid d3 Gingeureod
LOQ heleased,
6,
baec
oto, the dndtoid 93 SDR
om inux Kemel a.6 35
APA Ael 9
featuoe
with intreased
oted usU inte) a ce d eaigm
imbliot and peed
oreem ses amd Aesolutuomi
'duprast oeo losge
enhanced copy pate unetiom.aully
Deus udio letts auth as bss best uenb ate

doonloado om bbuose ema


duppost o mliple camelas om oluice, includin gg
ont o ding tomero,ud ajilable
Enhanced Aupport or nalut eode elwelopment
Audio qraphical and input nhamcemenits for
m e deelopas.
Ast mdhoid alex On Baater 9

Version8.1-

Release dala - Dec. 89 dol o


Smpove mecs ancd bugixes ox the Nes cuus
Vo-yi on 239
Release Date Jan 81, Jol1

9mproutments Ord bug ixesor Neus S.


dbcoid :3.3 Gi
APS lel Io
nqebread
Nesiom 8.3. Releae olato fb 9,2o11
Stutral mpue menda and AP
Versiom &34 xes
Release date-
April di, aoll
Ppt o uicleo b voice call using gboqe iak
opan occewn Ghray 4uppost
uotehed di daau mvnyph onor S2
Hxed A 4ponlamous ebovt
on domgunmgala
SPs
Vension&-35 Release olate uy 8s, 9oll
Smproved meloosk beomamce tos eyuusS41
Fixed a bluetboth bua on damawmaaloxy Puus
Smprnued Guall appll cati on, batley eo en
ixed o d crsh on
Samaunralaa Plus
Vensi om 3 6 Reloase. date Sept 8, Jo
hxed avoice Seoch bug
Vosiom 87 Releae dale - Sept 81, Aol

Oalet &ppostto Doxus S49


Crone
3 ndroid o tony
--
Comb
Relenxe date feb 89, 2o1
AP Jevel1
boed on inux ke mel6 3
Ophtimed tablet suppost th ne holb qraphic JuM
rdoo e
asle Cq
Added dom b07, alon bav
mbled ultlaakinq
Kedesned th keydod, uaking typingaut "dtnd
Od ck ores Comba poaLt
Hosduoe acceles aluon
Hutbele loDAes tabs eblacing bs0Okondous.
ufport or Hdi - ove process os
t emtpt all wses dalo.

ndoid 31 Homeytomb
Reloase dade Hay 1o,doll
APA Leal 1 =

U hein emevtls
Comnedivty fos U3B accessovies
Resiaable Home cveen uodgebs
ppot fo oystíck amd gamepods.
'Bupatoflic audio playbok
+Ban peomon ce u lock
ondroiol 3.8 omy Comb
AP 13
Reloose dote -3uly IS, 8o1)
Versi on 3.0
Smpmuec horduoahe uppot
neneased abiity pcauos tu o (cessles
T
D e dP&ppoit umduom
Vesiom 38 Reloast dale 8ept 20, 2o1
Sug amd unoY A0Cunity, stability
Update groqle boks.
'n BrouwseT.
Smprouerote Ndabe Plash Juppost
Vtrsion 8.0
Kelense date Sept 9, 8ol
improutmemlsfo
e s amd othes munoY
Hoto ola Xbom 1.
sio 28.4 Releose date- Oec 1S, dolf

o Y 39 amd u9 table
Verdion 3 86- Relense date feb I9, ol2
when u
fed dlata eonnedivity dasues coming
Qiplame HOde

4.
Android 4.0 Ice Cveam Samduoich
Release date - Dct 19, 2o11
based on Bnux kemel 3.0:
&thlaut vesion l a l y ppost Adobe
ugtm flash plaes
Hajor Aekinemenils wth ne Roboo font amuly
tbttons nom dhdnid0x ae noo on phDnes
asies to ceate older btth daag And drop dtyfe
Pineh t 2601m uwmctionally in calendlor
lmprouAd emrby Lmidtuom On keyo o0 d.
tO Divect
etler voice ivteraluon
Built ?n phob llos
Vesi On 4.0, 4:0 x ed mino baga)
&nd roid 4 03
Tce Coeam Sanduoich
A PL 15S
Release oate - oec 16,Aol
Veasi0 4.0:3
0uerous bugtx eA and api uadons
Improvement to graphs and dala beseunchonality
Oeuo comer a oPpbtouon nhonCtrg Uideo
oup M aging uppoit
Vesion y Kelcase olaile Nov 87, 8o)la
FiLed
baug peeple appbcatuon
in th
Vesion 9-9 - Roleose date - feb lI, 3o13
ixed blue oth Ouudio
bheamin itons.
and uetooth
bvpresingths wdi
ndoid 4:3 Tell Beon
AP4 18
Release date July 19, 2o18
Bluetooth Du ener9yuprt
Notit oiurpot
K Aesolution Appot
Kestnicted attes HOdeo neo ser preiles

VesiOm 4 3) Release date-Oct 9, 9o13


Wexus 41E
6ugxes and mall tweaku b
&ndroid y.y Kkat

AP 19
Release elate 0ct 31,8613
Releshed lesa ce oth wte leMe yd
Veidied bot
Clock n Jonger how bold hound
Oneless pinding capabily
Oodtut tnrayed bl&sten
Nau 4.4 KHkat oith wearable ectemsions
Keleare olate -Jotne , oly
Vesion .4 W
Bndo1Cl
deD platyomn to
3ntundnelease o the
maot uodtthes
VeYsion y.4
Keloac. odlate Sept 6, ol
U1 bpdates o gooale aps nayi gat on alo omd.

Versi on u.y Lo
Kelease d ote - Oct 81, 9o14

oBne HuAtc plouback


GRS

ndroid so loli pop


APA 8
Vesion S-o-Releae. date 1Oou 4,8o14
Andotd Aundine wth shead o-time compilaton
'Suppot 6 1 bit eru's
Suprost tor prin eufews
Updated mo
Vesiom S-o Keloase. dlate Dec , loly
A t bug tes, încudimq usoluing issues
NotsLO 60&
Releose dade Dec 19, 2ol
Changes hoo aloms Ooke dhe CPO, and houw
aloms compele dlo AesOurte
&ndrotd 6 Asipop
Newion 61 Releae date- Horch 8,
80s
Mpnouement amd bug xes to the bue bieo s07eem.
bhta upost ov ulti ple SiH
Ugh eleinhon uoie talls Conds
ViOn 5.11 Release date Apil 0, 203
NoiOus bu
lotut LO callng p
6 ndvoid 60 Hovsh malloc
A 93
Ve-taLon 60 oct 8, 9olS
ecludeol sudieil asuyle Hanag
Lonleto L h homky toaiols Sihs opP
P tomd oy olte
Applitotin deh bau omdauonled
No Soeem hslotuon dwum4 Jouth
VeuLam 8-01 Reluast dale- Dec 1,4o
Orvcodle t0 amod bro erto ppost
Destipluns ov Us6 eonnedon sptioms.
4 nduoid 4o Nougat
APA
VoHBLom o datedug 39, 8o16
Releass

tpoost le basad omuplhon


calilbratuom
Ability d displa colo
ouuty o Lbo in he Jereem
Aklikt suoteh do the loat aptmusl 0Pp by
doublë tap
Acldled On omergemoy ioaluom pout.
Acloled ths te's A outton to the Du0uies deleen
DydAea Aealit pladro
uitual

Hulli indou uPpot


Reshid le ystent a ttess.
thndroid 81 OreO
AP
16th o the dndroid OsS,
f s the. puinoy Aplenge
VESiom81- Rolease dale Dec $,9ol4
Neus al Weudoska APL
Shoved Hmor AP
Oal paper eolors Af1
utai1lTOnueuosk upd ole
'loost Hesages a noco thite
*

o r t a t e ght and dovk hemes


oviaauon butons ol'M hen not in use
Android Pie
Release. dode -âug Ao
tsthe Maio Aelease
DeL wser inleoce ta the qjuick setlngs MeMu
bat.
CodR has Houeol do the elt notircauom
Kounded comes a t o s the u
NeuD a msitions b Lotthing etiseem app acihe
duppot o display Culeut
Redesigmed velume lide.
Amdbid olashboovd
Call Aeto ding
puomsully usabled.
AP 89
94 i 1s MOOY Aelease. he stable vesi On uoas
eleased On Sept9, 2o19
fevampedu teem esunt nauig auom wth
new
PPspn /eloge ariuaions
Sco ped torage heshictions
dioi d 11 Nougat
AP 9s
Ocd , gol6
S Veaiom 71- Rele ast date
Keanong ed ntblieation uhods
added do poweh
bullon Hemu
Kelad epuon
uelope's atunes fahosted uanagon P1&, keybor d
YLOge.iodlion otc)
and
Honual tovoge Monagev idemties es
PP Jusumatorag
osiom 1 Release date -Dec1,9o16
Ned set oeo
Send GIs aire eHo Om ths dle ault keyboasd
App shovt: tuts
JLom 1-10 Release date April 9ol
uslage alestu

hnd-roid &o oyeo


APT 96
8t s the aio Aelease ndoid bptraung duystou
8t 0s elease d as o duelopt preuieu O
Kdleose dale - Hovch 81, 9 ol7

tta Aclease date - Aug 81, 9olt

Projet 1wble
, the bggest chargt
Pretut- in picrse Aupt
-

Adoptiv îons.
ADeicoluon improue Nends
Syalum d e Adat?ll rameudonk
alti- di solay pot
Gpog e play fole
droid 8 Dreo
AP
34 is the 16 pinoy Aelease o the dndooid D
Vexslom 81- Rele ase dale Dec S 9ol
eus al Nehuooska ART
Jhoved Hemoy AT
Oallpape tolbrS T
urtabil Toneuoovk wpdates
loost Heysages a noo cdhite
dotaie h t and dok bhemes
*Ooviaduon loutow ol when not in use

ndroid 9 Pie
Release dote -Rug oll
t he ajos Aelease
NeLs wtr inilefoce ta the quick sRtng Mem
Clodk hs Hovec ds the J ntitom bat
Rounded eomes atnoss the u
'eud ransiiovs avsLOYtchi'ng betujeem aPPA adivihieg
Sppovt o usplay Cuou
Redesigmed velume liden
mdbuoid olashboo-rd
CalAecovdinq plionsullsabled.
tndroid o
AP 89
HLOOY elease. he 5table vesi Om uas
eleased On
Sept 8,2o19.
Revomped &teem esut nauig auom th
aPpspmclose ariuai on new
Sco ped oraqe neshictons
G-ted occess do nom- A0s7ttable olauCe 1dlemu
Getoy ppo»t lov blomelic QuthemiicaLion tn Gpps

Juppost o old able phones


Y noGcoton buubbles
L &ptem idle dok thome/MOde
Bvdroid 11-
APL3o b
0as t ammoun ted
is 11t aOYAelease and
Croole
Release odlate- Sept 0, 8odd
Chat buubbles
Screem Aetorder
otiicaiuon hikton
NeLD pomisson cobuols
Dne - 4me pomissiom ond
OR
bausun tandalont S
HPLdistin duon
non-landalome SG.

Enleprise dovk pretle privacy pöle dson3


n d d 19-
AP 81
.Release dale Oct , So1
asien o hou ng.
AuifMagt uppost
Solling6ceemshot
Dne haoled mocle
hreo mawcoluom Con 2eom In ony olb@l covlemt

On oluce
to he
nd-id RuriMe (AR) HOdule added
coTe as cOmponemu via aogle Play
upoladale
Bold exl neysCale
PRvau clashbord.
&ndhoid 18
AOL 31
pole amnounted nolnoid 19, on inloio heeabe
d o i d 1 tncauding mprouemeris spet (
tololable phonos toblebs ete
Kelease dlale BA
sts
Oative duppost ov taking srelling bereemsh
Halei alu Y ou
Oidget Ue update wih nes

desigm lamgunge
Plaosm
.doy
Kao heesh to the eppaing duysle
Andoid 13
dndnoid 18L,
Ater the duttessul nelease o
ndroid 1 will be eleased

donguage Customisat1on2 apPa


doge Batly t
m proued stcuoty th blutosth
Butboth Audio Jreain9
mpro
oudio
FC Payments &tcondlom Ust nles
Runtie pomussion o noleatons
3nale ine clock oyoub on elock deeem.

uprot o DA08 eur H 1Ps


Q.8 Explain the following widgets with their properties and methods :-
(a) Text View (b) Edit Text

(c) Button (d) Toggle Button

(e) Checkbox.

Ans. (a). Text View


TextView in Android is one of the basic and important UI elements. This plays a very important
role in the UI experience and depends on how the information is displayed to the user. This
TextView widget in android can be dynamized in various contexts.

TextView Attributes

Following are the important attributes related to TextView control. You can check Android
official documentation for complete list of attributes and related methods which you can use to
change these attributes are run time.

Sr.No. Attribute & Description

1 android:id

This is the ID which uniquely identifies the control.

2 android:capitalize

If set, specifies that this TextView has a textual input method and should automatically
capitalize what the user types.

3 android:cursorVisible

Makes the cursor visible (the default) or invisible. Default is false.

4 android:editable

If set to true, specifies that this TextView has an input method.


5 android:fontFamily

Font family (named by string) for the text.

6 android:gravity

Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than
the view.

7 android:hint

Hint text to display when the text is empty.

8 android:inputType

The type of data being placed in a text field. Phone, Date, Time, Number, Password etc.

9 android:maxHeight

Makes the TextView be at most this many pixels tall.

10 android:maxWidth

Makes the TextView be at most this many pixels wide.

11 android:minHeight

Makes the TextView be at least this many pixels tall.

12 android:minWidth

Makes the TextView be at least this many pixels wide.

13 android:password

Whether the characters of the field are displayed as password dots instead of themselves.
Possible value either "true" or "false".
14 android:phoneNumber

If set, specifies that this TextView has a phone number input method. Possible value either
"true" or "false".

15 android:text

Text to display.

16 android:textAllCaps

Present the text in ALL CAPS. Possible value either "true" or "false".

17 android:textColor

Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

18 android:textColorHighlight

Color of the text selection highlight.

19 android:textColorHint

Color of the hint text. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or
"#aarrggbb".

20 android:textIsSelectable

Indicates that the content of a non-editable text can be selected. Possible value either
"true" or "false".

21 android:textSize

Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example:
15sp).
(b).Edit Text

In Android, EditText is a standard entry widget in android apps. It is an overlay


over TextView that configures itself to be editable. EditText is a subclass of TextView with text
editing operations. We often use EditText in our applications in order to provide an input or
text field, especially in forms.

EditText Attributes

Following are the important attributes related to EditText control. You can check Android
official documentation for complete list of attributes and related methods which you can use to
change these attributes are run time.

Inherited from android.widget.TextView Class −

Sr.No Attribute & Description


1 android:autoText

If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

2 android:drawableBottom

This is the drawable to be drawn below the text.

3 android:drawableRight

This is the drawable to be drawn to the right of the text.

4 android:editable

If set, specifies that this TextView has an input method.

5 android:text

This is the Text to display.

Inherited from android.view.View Class −

Sr.No Attribute & Description

1 android:background

This is a drawable to use as the background.

2 android:contentDescription

This defines text that briefly describes content of the view.

3 android:id

This supplies an identifier name for this view.


4 android:onClick

This is the name of the method in this View's context to invoke when the view is clicked.

5 android:visibility

This controls the initial visibility of the view.

(c). Button

In Android applications, a Button is a user interface that is used to perform some action when
clicked or tapped. It is a very common widget in Android and developers often use it.

A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes

Following are the important attributes related to Button control. You can check Android official
documentation for complete list of attributes and related methods which you can use to
change these attributes are run time.

Inherited from android.widget.TextView Class −

Sr.No Attribute & Description

1 android:autoText

If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

2 android:drawableBottom

This is the drawable to be drawn below the text.

3 android:drawableRight

This is the drawable to be drawn to the right of the text.


4 android:editable

If set, specifies that this TextView has an input method.

5 android:text

This is the Text to display.

Inherited from android.view.View Class –

Attribute Description

1 android:background

This is a drawable to use as the background.

2 android:contentDescription

This defines text that briefly describes content of the view.

3 android:id

This supplies an identifier name for this view.

4 android:onClick

This is the name of the method in this View's context to invoke when the view is
clicked.

5 android:visibility

This controls the initial visibility of the view.

(d). Toggle Button


In Android, ToggleButton is used to display checked and unchecked state of a button.
ToggleButton basically an off/on button with a light indicator which indicate the current state
of toggle button. The most simple example of ToggleButton is doing on/off in sound, Bluetooth,
wifi, hotspot etc.

Programmatically, isChecked() method is used to check the current state of the toggle button.
This method returns a boolean value. If a toggle button is ON, this returns true otherwise it
returns false. Below is the example in which toggle button is used.

ToggleButton Attributes

Following are the important attributes related to ToggleButton control.

Sr.No. Attribute & Description

1 android:disabledAlpha

This is the alpha to apply to the indicator when disabled.

2 android:textOff

This is the text for the button when it is not checked.

3 android:textOn

This is the text for the button when it is checked.

Inherited from android.widget.TextView Class −

Sr.No. Attribute & Description

1 android:autoText

If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight

This is the drawable to be drawn to the right of the text.

4 android:editable

If set, specifies that this TextView has an input method.

5 android:text

This is the Text to display.

Inherited from android.view.View Class −

Sr.No. Attribute & Description

1 android:background

This is a drawable to use as the background.

2 android:contentDescription

This defines text that briefly describes content of the view.

3 android:id

This supplies an identifier name for this view,

4 android:onClick

This is the name of the method in this View's context to invoke when the view is clicked.

5 android:visibility

This controls the initial visibility of the view.


(e). Checkbox

Android CheckBox is a type of two state button either checked or unchecked. There can be a
lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc. Android CheckBox class is the subclass of
CompoundButton class.

CheckBox Attributes

Inherited from android.widget.TextView Class −

Sr.No Attribute & Description

android:autoText
1 If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

android:drawableBottom
2
This is the drawable to be drawn below the text.

android:drawableRight
3
This is the drawable to be drawn to the right of the text.

android:editable
4
If set, specifies that this TextView has an input method.

Inherited from android.view.View Class −

Sr.No Attribute & Description

android:background
1
This is a drawable to use as the background.
android:contentDescription
2
This defines text that briefly describes content of the view.

android:id
3
This supplies an identifier name for this view.

android:onClick
4
This is the name of the method in this View's context to invoke when the view is clicked.

android:visibility
5
This controls the initial visibility of the view.
Why do we need the list-based widgets. Explain
the listView and Spinner with suitable example ?

Need of list-based widgets :-

RadioButtons and CheckButtons are widgets suitable for


selecting options offered by a small set of choices. They are
intuitive and uncomplicated; however they occupy a permanent
space on the GUI(which is not a problem when only a few of
them are shown).
When the set of values to chose from is large, other Android
List-Based Widgets are more appropriate.

ListView :-
Android ListView is a view which groups several items and
display them in vertical scrollable list. The list items are
automatically inserted to the list using an Adapter that pulls
content from a source such as an array or database.

List View
An adapter actually bridges between UI components and the
data source that fill data into UI Component. Adapter holds the
data and send the data to adapter view, the view can takes the
data from adapter view and shows the data on different views
like as spinner, list view, grid view etc.
The ListView and GridView are subclasses
of AdapterView and they can be populated by binding them to
an Adapter, which retrieves data from an external source and
creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful
for retrieving different kinds of data and building views for an
AdapterView ( i.e. ListView or GridView).

ListView Attributes
Following are the important attributes specific to GridView −

Sr.No Attribute & Description

1 android:id
This is the ID which uniquely identifies the layout.

2 android:divider
This is drawable or color to draw between list items.

3 android:dividerHeight
This specifies height of the divider. This could be in
px, dp, sp, in, or mm.

4 android:entries
Specifies the reference to an array resource that will
populate the ListView.
5 android:footerDividersEnabled
When set to false, the ListView will not draw the
divider before each footer view. The default value is
true.

6 android:headerDividersEnabled
When set to false, the ListView will not draw the
divider after each header view. The default value is
true.

ArrayAdapter
You can use this adapter when your data source is an array. By
default, ArrayAdapter creates a view for each array item by
calling toString() on each item and placing the contents in
a TextView. Consider you have an array of strings you want to
display in a ListView, initialize a new ArrayAdapter using a
constructor to specify the layout for each string and the string
array −
ArrayAdapter adapter = new
ArrayAdapter<String>(this,R.layout.ListView,Str
ingArray);
Here are arguments for this constructor −
 First argument this is the application context. Most of the
case, keep it this.
 Second argument will be layout defined in XML file and
having TextView for each string in the array.
 Final argument is an array of strings which will be
populated in the text view.
Once you have array adapter created, then simply
call setAdapter() on your ListView object as follows −
ListView listView = (ListView)
findViewById(R.id.listview);
listView.setAdapter(adapter);
You will define your list view under res/layout directory in an
XML file. For our example we are going to using
activity_main.xml file.

Example

Following is the example which will take you through simple


steps to show how to create your own Android application using
ListView. Follow the following steps to modify the Android
application we created in Hello World Example chapter −

Step Description

1 You will use Android Studio IDE to create an Android


application and name it as ListDisplay under a
package com.example.ListDisplay as explained in
the Hello World Example chapter.

2 Modify the default content


of res/layout/activity_main.xml file to include ListView
content with the self explanatory attributes.

3 No need to change string.xml, Android studio takes care


of default string constants.

4 Create a Text View file res/layout/activity_listview.xml.


This file will have setting to display all the list items. So
you can customize its fonts, padding, color etc. using this
file.

6 Run the application to launch Android emulator and


verify the result of the changes done in the application.
Following is the content of the modified main activity
file src/com.example.ListDisplay/ListDisplay.java. This file
can include each of the fundamental life cycle methods.
package com.example.ListDisplay;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListDisplay extends Activity {


// Array of strings...
String[] mobileArray =
{"Android","IPhone","WindowsMobile","Blackberry
",
"WebOS","Ubuntu","Windows7","Max OS X"};

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ArrayAdapter adapter = new


ArrayAdapter<String>(this,
R.layout.activity_listview,
mobileArray);

ListView listView = (ListView)


findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
Following will be the content
of res/layout/activity_main.xml file −
<LinearLayout
xmlns:android="http://schemas.android.com/apk/r
es/android"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ListActivity" >

<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>
Following will be the content of res/values/strings.xml to
define two new constants-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListDisplay</string>
<string
name="action_settings">Settings</string>
</resources>
Following will be the content
of res/layout/activity_listview.xml file −
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->

<TextView
xmlns:android="http://schemas.android.com/apk/r
es/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>

Spinner :-
Spinner allows you to select an item from a drop down menu
For example. When you are using Gmail application you would
get drop down menu as shown below, you need to select an
item from a drop down menu.
Example
This example demonstrates the category of computers, you
need to select a category from the category.
To experiment with this example, you need to run this on an
actual device on after developing the application according to
the steps below.

Steps Description

1 You will use Android studio to create an Android


application and name it as AndroidSpinnerExample
under a package com.example.spinner.

2 Modify src/AndroidSpinnerExampleActivity.java file to


create a simple list view with items which are showing
as spinner items

3 Modify res/layout/activity_main.xml file to add


respective XML code.

4 No need to define default string constants. Android


studio takes care of default string constants at
string.xml

5 Run the application and choose a running android


device and install the application on it and verify the
results.

Following is the content of the modified main activity


file src/com.example.spinner/AndroidSpinnerExampleActi
vity.java.
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import
android.widget.AdapterView.OnItemSelectedListen
er;

class AndroidSpinnerExampleActivity extends


Activity implements OnItemSelectedListener{
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Spinner element
Spinner spinner = (Spinner)
findViewById(R.id.spinner);

// Spinner click listener


spinner.setOnItemSelectedListener(this);

// Spinner Drop down elements


List<String> categories = new
ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
categories);

// Drop down layout style - list view


with radio button

dataAdapter.setDropDownViewResource(android.R.l
ayout.simple_spinner_dropdown_item);

// attaching data adapter to spinner


spinner.setAdapter(dataAdapter);
}

@Override
public void onItemSelected(AdapterView<?>
parent, View view, int position, long id) {
// On selecting a spinner item
String item =
parent.getItemAtPosition(position).toString();

// Showing selected spinner item


Toast.makeText(parent.getContext(),
"Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?>
arg0) {
// TODO Auto-generated method stub
}
}
Modify the content of res/layout/activity_main.xml to the
following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/r
es/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"/>

<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"/>

</LinearLayout>
Modify the res/values/string.xml to the following
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string
name="app_name">AndroidSpinnerExample</string>
</resources>
This is the default AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/r
es/android"
package="com.example.spinner" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.spinner.AndroidSpinne
rExampleActivity"
android:label="@string/app_name" >

<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>

</activity>

</application>
</manifest>
Date [I][I J[IJ
k=======================-= I I e Pagel

_ _fl:J
- (~tJ'.JL_u.Ji!LL..M-;F~_L....:....~~---#;~ ------LJ:)L_ atsi 11.nw _u;_n t,.1 c

_ _ _JL_U- LJVl-- -___1. ~~>... :!~'---- ~r ~ d- ----/-1.C:.LC~g


i-
uil {-.:~lorry
---" ---~ a,cu h~·v~i~"4 1-rt -t:(- ----- - - --- ---

_ __ µl...:t.__ ---1.:LS-- ~f.LJ..L .-'-'4,.L~- ------'-''4-+ '...,_____,0


~ }/ ' ~ ~ .(~ (. fl' j P-j {)
V

- - - - 1 4 - - - - - -- ---'-' ~ ,4J _ _+z,


.J.--LJ- ----Lr.
1n-'--"v~e. a_Cl-iv i ~
1
et

d RJ.C 9--( t Jed ct£ 1Yi ±en h' ,, n fo d u tJ C 1--t' ob

ect

t-
JJ
II
a

Datu [TI[ nrn


PcjgCJ[ - ] ~
'::f. .fhb t,, f d f" 1ell t;, 001 e tnn,''> ~ ~ ( ✓ -lo :
• s> 1 ci..9J- J~ e d.uJ, rfl
1
l.o!.-W )( ~ +4_ 0t tJ,·v ,' ti
' Y) IS f l Q 'J LI J/i 1 0 Ir ( 1 C, ck
pr\

• _ Y) f ~ plj &J UY -(ll<-ff


- - - » . - - - -~ _ r:;JcJ O r~.of) e - - CgJJ_ __ __ __ ---- -
-~~--
• ,1J- 1o~ t _ _ft_ ~ ~- - - - - - -0 -

- - - - u - - - :-1---,,.,.. ,...., \.¥-,C::!......U-t- ___,, ll gj]_L__ _ _ _ _ _ _ _ _ _ _ _


__ _
---U--<2~~,-~~~~¥p~ll~o~1_ __)atw ± __ __ __ __ __ __ __ __

C 111£P ft
Date [I]mm
Page[ 2-. I CJ

HecoJ v ew

An

Ct.

LJ ~ed
7

Date [I] [I] [IJ


-- -- - Page l ] ft,
~½ p2 "A -0••2 ve --::M \Lf :::tP
1
c21oab =

_ _(y:\ _ _ __,_
Ct"'-'(. v:..i_.
_,_fJ,'__,, L. +:J
_~ - _w-'-f_,_
¼"-' --- -~d~9r...u.ro
..!-!;e__~ c erl lllU
r - - -- ~ 1._ -~ ~v-~P_ ___;~~~~~-~e~
_,µ91-n-!Jg I

od AJ-rv ffJ

• 1-:!ow ::>tJ H/Yle.. ctn UJ e h,f


1,110 , e, t DI'\ c.J/c A L/( 1-e./l.Af

,Cfrp~
0-W!ll (JJt' ,M.M-1 1N t '-{ tkn CPt 6n Ch c~llt eo d)-
-..
' IJ,L_
-1.1...,;...,i1u. _u6!.(._e _ _CfJt/
~ J..L.Ced
J,-- cvlJ -)_ __µlM~,.dcz..,,1:L____
-- '- .>c,. ..c...~
-=-
4 I\...L.IC
-""
:l"--=
cP~ t.<,..;,,'tr....!.. efl-R.
'-=--
--1....... 2?-=I_;
we Lu,Jy_j.Je

cRAJp o(y ~ ±.ent


Ur~," [ I Jl I JI J l
P11w,[ ('~ IC

- - - U - - -- ---'-1',- - -
(_).Jc. .~u r r , lt, ('
...,
'f,;,,. ,. ,
i/1 /
V ),.-
/, ,,... (
'" I
- 1 1 ,r,
/ 1J
I

~ r\ ,, 4~ u r J, 1 i ~ tjl ~ . b1~ .1 f
O> trt ·, rJ) I·
1 ~ ~rJ
vvi d-hod.

- - - l - l~ ~L1-- -l--4-<r1+-----1~ ~ ._________,__--=


! :)~"-4---- ~ - b ~" - ' 'd (.JU I/
<M/u-'-!f1
=1-- . 9'. . . fIU
.L.......,:J_
~ _ _ ../J--I
__ .{ ~ lol),,.1 ,l}Ji ,,·7-
Datu[I JOJ [IJ
PugBf ] ~

-:i..a.,ce +n__ arid ()L,i l~~ _/J _ _m-€fh~) J1 -

- - on ( ~ ~ '"r Jj__ _ JU,._ - ~cho( ,)-h? _ I,') - ,~1.-.) la:1f

-,., ---- - - - - - - -
fa pau
~--=-- ~_,_,_ __._- -~ """" _ _ _
,1,J .Ju f _ _ __
L..____:l:.....:::__:_
/4_R.__f1CL
- - - U - - - --'-"-1<y---

eJ/
-
_-H-----'-£.=6,.,~ ------'...J,c:._,_,_. .___ ~~_ h
_ ±u
tfll?_ - _!,,:J _ A_d;-!.o"l 12cL9f_ ol11.=-
=- - ~ -
- ~ ~ -- ~....r:___a__~'---'- -'-'~ · v; ~- -.---- - - - - - - - - - - - -- - -
Pagel ")

- ~ ~ J _£ ~ (14:LtL jt.:)1.-. PP.Jj _t'J -k _______


.s+ 9tt 11-ch ",i J fux RJ 4.1.f c; _ _________
q

• _fl--l RA 'i el (JJd e S f..lM ~;e,1 ~(] ,J e enc,d O rb v '/J-


---!J1-..-- ~ A-- ---A,....,.'.'.) __ -E:::1-..L..L4-~ - --1--..:.:
fc :.......)...I.~~ I C?(L 021a/i .•~ 1-0<a:1
KT= CoL7 = cf) f\ J( E Lf O i"'i,

0
) ~ t CtvtCJlg I -/-L ~ f ,L,oph. - -~ -f - - - - - -
Q_/_.lrJ)~µ J~ - Jht:4-tLLf_- ~ -
--
Kt :j__ _/ cLalJ:lzj,'e2 _
L-v 111-etTi_ u R..I _
- - ..LJJ r#-.
_ __
~ _ __ 4-Lk_d_u_ __ {,& rjo tf _ _ _ _ /

_M d -------- -- --

- tt.pf - 1! ::: ll~ [l2:.+&.a12 J J') J\ _


(,
_ __ (.a,__,/}'.),_._.__~
fd-d / J.rtrq '- I? JA.t uc, ,
6-14) hy do we necd the vagment in
Andsoid? xplain the
fecycle o ngment Hos Can you adds Hemore 2
Heplace thegment with ment hansaction ?

ns Androidragment is the þart oh aclirity, tt a also known


d& u b - Qtttnty h e e (an be mbre than one r a g ment in

Qn Qctinty fragments Hepruent multiple seern tnaide one


actiity
Andoid fragment fecycte 1 ffetee by a cthity ifeeycle because
im actnty
fragments qre imcloded
own ufe ge methods that is auected by
Cach frag ment had Its
because fag ments are em bedded in actiity
actinty kefe Cycle
actinty
T h e fragment Manager
class ts JHCAonsible to mapke intera etfon
between fragment, okjects
a/ways exist coithin
Weed chragmentA tn Android9 /agmerlts
the Context of a giren Actiri
and Can always alteus that Actinty By dtoTg the irformaton
within the the agmerrér each 4Heen
of inteest ActH
Con imply a cces the objeet Hyomence through the Acti'ity.
Aiteeycte ot fragment, he ufegck of android fragmert tike
the atity jeeycle. Thewe are 12
1ife-
cycte methods or ragment.

fragment ia Added

OnAtach)

onCueate()
OnCHeatrieu)

aT Acti ty Cteated(

onStart)
onResumec)

UsU NaYgateragment Is Atire)


6ackworeor The fragmerrt i
fragment ta a dded to the
OnPause C) batk
emoreol/ 6tack them Hemored |ueplaCed.
Heplace
0n Stop)

onoestey Vituu() he tragmet Hetsmå


to the layout faom
onppestroY) the back Atask.
onDe tach t)

hagment is Destroy t

Wndojdfragment ifecycle ftethods 9


onAtach ( AcHrty);- Jt 4Called ornly once hen it i atached
with actiHy
.onteate CGundle): Jt -

ia used to mitialize the


fragment
1). ontueqte Yíeus kayoutanfla tor, Tttu G+0 up, 3undle). - teatey gnd
and
Heturns Uitu hiugrchy

)onActirity Cueated C nd te)Jt14 inro/ed aften the Combletie


tion
of onbeate ) method.
u onYTeuStg te Res tored (Bundt) Jt proidu tntoBmqtion o the
fragment that al the sare
Atatt o ragmert Yitu
hivqrchy has loeen uestored.
U OnStart) : -) malkes he fragment tl utattire rtaible
U). onRes um eC): - makes the ragmentt intexative
U)- OnPauseC) : 3 Called uhen fragment t no
longe, tnteractir.
1x)on$top(U,9 1 (alled uhen fragment mo longv Hisible

X0TOutroyYituwu(): Qllows the fagment to elean ub tuby r(eg.


Xi) On Destroy() allows the fragment to ean op 0f foagment
State
Xm Oetoth c) Jt is Called tmmedrately pOr to the
?ragment mo

(onge being Q8Aoiated with its acttity

vagment 7ranaattjons At Muntime a4 mentManagr Can


add, Hemore, Heplace
puorm othu and
a ctons uith fragmenta tn Huhonse touser
tntua ceion. Sach Aet
Tagment ehange thet you Commit is Called
the traniqction
Qnd you Can 4peeit uhat t do tnaide the ansaction Using
the APt pronded by the Miag ment 7 ansactHon clas8ou Can gou
multfple Qcttons tnto a
Yingle trgnAattio 1or examble, q
-

t9msaton Cam add or


Heplae multple ments Thia 92ouping
Can be segulor uhenyou hare
multple diblinq frag ments
diaplayed on the ame AHe en such as with Aput iews
You Can get an tnatanee
o, hagment Transaction aom the
ragment Managen b Calting being11anaactiont), a4 Ahown in the
follosin example
Jara bagmentManaguu fragment Managu
hagment ranaacti'on fragment ansqction
fragmentManag.
begin Transaction ();
Add, Remore, Replaee
aqme nt 7Add U:>
0 add a
fragment to q
hagmentManagex, Call add () on the
tansacton. This method Heeeiru he iD of the Containe
for the
ragment, Q4 Nell q4 the clas name
o the
gmernt you toiah
to add. The added tragment s moYed tu the RESOM&D Atate.
9t istongly Me tommended that the Contamen ts a fragmen t -

ContainexYeu that s part o the neu hinarchy


Kemore ():5 (o Hemore aTagment om the h ost, Ca
emore (), bassin9 im aa9ment tnstance that wad
Hetriered om thergment mqmageuthrough
Hndhag mentRu
4 ) or
findfragment By Tag() S the gments rie
breioua)y Qdded to a (ontainer the Het is Hemore d
,
oom the
Containe at the point. he Hemoved
ragment ia moreq
to the DESTRoYED tate
ReblaceC): 2 Usc plate ) to
Mplaee an exjating iragment
(n (ontaineu
a
urth an instanee Q 7eu
vagment elass that you proriede. Cqlting eplace () i2 tgui'-
Yalent to alling Hemore() Cw1th a fragrment tna Con ta i n
Qnd Qd
ding a neus fragment to that same (orta/n.
he ollouwing Cocdenippet shouws how you Can pla(e one ragment
&utth Qnothe

Jara:fragmentManago gmentf(anagu =
tragment7ansq eton tr anaachon =
fragm entManaguu. begi
fsansacton AttRe cord eniny Alloned77ansaction ();
o ansaction . (tut);
Heplatt CR:idfr@gment -(ontarm, EXampletrag
tansachon. Commit (); ment clasw , n
l);
Jn this xample, Q neuu
Instanu o
theragment 1f 9ny that Cuenty Xamplefragment Hepla ces
tn the
lay out (ontaimou
identified by Rid fagment Cuntainv
By delault,
-

the ch ang a
made in a
ragment1rqm4a tti on Qe not added to
back 3tac/e.
sare thase changs, you (an lall
addTo Beck Stac/e C) on the
hagment77ansactron.
Location-Based Services
Mobile phones use several related methods, alone and in combination, to
determine where they are:

Cell ID

Whether you’re actually talking on the phone or not, as long as it’s powered
up, your mobile phone carries on a constant conversation with nearby cell
towers. It has to do this to be able to respond when someone calls you, so
every few seconds it “pings” the cell tower it was using last to tell it that it’s
still in range and to note network parameters such as the current time, the
current signal strength (uplink and downlink), and so on.

If you happen to be moving, your phone may initiate a handover to another


cell tower, all in the background and without you having to intervene. Each cell
tower worldwide has a unique identifier called, appropriately enough, its Cell
ID, and each tower knows its latitude and longitude, so it’s easy enough for a
mobile phone to know approximately where you are located by noting the
current Cell ID’s geo- graphic location. Cell network sizes vary depending on
the expected traffic in an area, but in the United States their radius ranges
from a half mile (cities) to five miles or more (wide-open spaces).

Triangulation

Most of the time your mobile phone is in range of more than one cell tower. In
2G and later mobile technologies, the cell tower has the ability to tell what
direction your signal is coming from. If there are two or three towers that can
see your phone, together they can triangulate on your phone’s location. With
some operators, your phone then has the ability to query the network to find
out where it’s been located. This sounds a little backward, but it can be very
accurate, and it doesn’t depend on any extra hardware on the mobile phone.

GPS

The satellite-based Global Positioning System is ubiquitous these days, found


in car navigation units, handheld navigators, and mobile phones. The good
news is that, using GPS, your mobile phone can determine its location very
accurately, including its altitude if that’s important for some particular
application. There are several downsides to GPS, but it is gaining popularity
nonetheless. The downsides are:
Increased cost

GPS radios and processors are fairly inexpensive, but still, an increase of even
$10 in the bill-of-materials cost of a mobile phone is considerable.

Reduced battery life

There have been great strides in reducing the power required by GPS radios
and processors, but they still suck battery power. Most phones that include
GPS also have a feature that lets the user turn it on and off. If your application
depends on GPS accuracy, it’s good to remember that your application might
have to check to see whether the GPS device is turned on, and notify the user
if it isn’t.

Unreliable availability

Nothing “always works,” but GPS in particular depends on your mobile device
being able to see the satellites currently overhead. If you’re in the basement of
a high-rise building, surrounded by steel-reinforced concrete, you probably
aren’t going to be able to use GPS.

It’s reasonable to expect that all Android phones will include one or all of these
location finding methods. Most recent Android phones, in particular, can use
them all. So now we’ll proceed to techniques for using the location capabilities.

The Google Maps Activity


Android allows us to integrate google maps in our application. You can show
any location on the map , or can show different routes on the map etc. You can
also customize the map according to your choices.

One of the applications that comes with Android is the Google Maps
application itself. If it’s appropriate, you can start Google Maps from your
application the same way you start any other Activity:

1. Create an Intent (new Intent(String action, Uri uri)) that says you need to
display a map. The parameters are:
• An action, for which you must specify ACTION_VIEW.
• A Uri, for which you should specify one of the following URI
schemes, substituting your data:
—geo:latitude, longitude
— geo: latitude , longitude ?z= zoom — geo:0,0?q
my_street_address
— geo:0,0?q business_near_city
2. Call startActivity(Intent intent), using the intent you just created.

Sr.No Method & description

addCircle(CircleOptions options)
1
This method add a circle to the map

addPolygon(PolygonOptions options)
2
This method add a polygon to the map

addTileOverlay(TileOverlayOptions options)
3
This method add tile overlay to the map

animateCamera(CameraUpdate update)
4
This method Moves the map according to the update with an animation

clear()
5
This method removes everything from the map.

getMyLocation()
6
This method returns the currently displayed user location.

moveCamera(CameraUpdate update)
7
This method repositions the camera according to the instructions defined in
the update

setTrafficEnabled(boolean enabled)
8
This method Toggles the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyCallback callback)
9
This method Takes a snapshot of the map

stopAnimation()
10
This method stops the camera animation if there is one in progress

An example that creates a map is:

Intent intent = new Intent(ACTION_VIEW, "geo:37.422006,-122.084095");


startActivity(intent);

The maps activity file is the main activity for the app, and contains the code to
manage and display the map. By default, the file that defines the activity is
named MapsActivity.java or if you set Kotlin as the language for your
app, MapsActivity.kt.
The main elements of the maps activity:

• The SupportMapFragment object manages the life cycle of the map and
is the parent element of the app's UI.
• The GoogleMap object provides access to the map data and view. This is
the main class of the Maps SDK for Android. The Map Objects guide
describes the SupportMapFragment and GoogleMap objects in more
detail.
• The moveCamera function centers the map at the LatLng coordinates for
Sydney Australia. The first settings to configure when adding a map are
usually the map location and camera settings; such as viewing angle,
map orientation, and zoom level. See the Camera and View guide for
details.
• The addMarker function adds a marker to the coordinates for Sydney.
See the Markers guide for details.

The maps activity file contains the following code:


import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends AppCompatActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is
ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the
camera. In this case,
* we just add a marker near Sydney, Australia.
*
* If Google Play services is not installed on the device, the user will be
prompted to install
* it inside the SupportMapFragment. This method will only be triggered
once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker in Sydney and move the camera


LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

Module Gradle file


The Module build.gradle file includes the following maps dependency, which is
required by the Maps SDK for Android.

dependencies {
implementation 'com.google.android.gms:play-services-maps:18.0.2'
// ...
}

XML layout file


The activity_maps.xml file is the XML layout file that defines the structure of
the app's UI. The file is located in the res/layout directory. The
activity_maps.xml file declares a fragment that includes the following
elements:

• tools: context sets the default activity of the fragment to Maps Activity,
which is defined in the maps activity file.
• android: name sets the class name of the fragment to
SupportMapFragment, which is the fragment type used in the maps
activity file.
The XML layout file contains the following code:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />

Deploy and run the app


When you run the app successfully, it will display a map that is centered on
Sydney Australia with a marker on the city as seen in the following screenshot.
To deploy and run the app:
1. In Android Studio, click the Run menu option (or the play button icon) to
run your app.
2. When prompted to choose a device, choose one of the following
options:
• Select the Android device that's connected to your computer.
• Alternatively, select the Launch emulator radio button and choose
the virtual device that you set up.
3. Click OK. Android Studio will start Gradle to build your app, and then
display the results on your device or emulator. It can take several
minutes before the app launches.
How can you play audio and video
in Android ?
Playing Audio and Video
Android provides a standard means to play audio or video:
the MediaPlayer class. For audio content, you can also play
back raw data, which is useful in sophisticated applications
where you generate the audio dynamically.
A MediaPlayer goes through several states during its life
cycle:
Idle:- The MediaPlayer is instantiated.
Initialized:- The media source is set.
Preparing:- The MediaPlayer is preparing the media source
for playback.
Prepared:- The MediaPlayer is prepared for playback.
Started:- Playback is in progress.
Paused:- Playback has been paused.
Playback complete:- Playback of source is done (the playback
can be started again).
Stopped:- The MediaPlayer is no longer prepared to play the
source.
End:- The MediaPlayer is no more, and all associated
resources are released.
Audio Playback
Audio can be played through two methods, MediaPlayer and
AudioTrack. MediaPlayer is the standard, simple way to do
playback. Its data must be in a file or be stream-based.
AudioTrack, in contrast, provides direct access to raw audio
in memory.
MediaPlayer audio playback
When you first start using the MediaPlayer, you should
determine whether a file placed within the application’s
resources is to be used. If so, MediaPlayer has a convenient
static method that will set up the data source and prepare
the player:
MediaPlayer mediaplayer = MediaPlayer.create(this,
R.raw.example);
If you are not using an application resource, such as
referencing an audio file residing on the filesystem (SD card
and the like) or on a website (e.g., http://SomeServer/Some
AudioFile.mp3), you’ll have to manually set up and call your
data source. You can take the data from a URI through a call
to:
setDataSource(context, uri)
The context in the first argument is a means for the
MediaPlayer to access the resources of the application itself,
and thus be able to resolve the URI. Either the application or
activities context will do.
MediaPlayer mediaplayer = new MediaPlayer();
// Uri mediaReference = "http://someUriToaMediaFile.mp3";
// mediaplayer.setDataSource(this, mediaReference);
// use absolute path
mediaplayer.setDataSource("/sdcard/somefile.mp3");
// prepare mediaplayer mediaplayer.prepare();
Once the MediaPlayer is prepared, you can play it:
mediaplayer.start();
During play, the player can be paused or stopped. When in
the paused state, it may be unpaused simply by calling start()
again. Once the MediaPlayer is stopped, you can’t start it
again without resetting it through the reset() method,
reinitializing it with the data source as shown earlier, and
issuing prepare(). However, look at the following:
mediaplayer.pause(); // pausing
mediaplayer.start(); // going from pause to play
mediaplayer.stop(); // stopping ...
// to be able to play again reset must be called
mediaplayer.reset();
// now the media player must be reinitialized to play again
While the MediaPlayer is playing, you can track its current
position in the file through getCurrentPosition(). This returns
the amount of time played through in the file, in millisecond
units: mediaplayer.getCurrentPosition();
Once the MediaPlayer is no longer needed, make sure to
release it so that the resources are cleaned up and made
available for the system:
mediaplayer.release();
AudioTrack audio playback
AudioTrack provides a much more direct method of playing
audio. The following example shows the parameters required
to set up an AudioTrack:
File mediafile = new File(mediaFilePath);
short[] audio = new short[(int) (mediafile.length()/2)];
// read in file and fill up audio[]
AudioTrack audiotrack = new AudioTrack(
// stream type
AudioManager.STREAM_MUSIC,
// frequency
11025,
// channel config—mono, stereo, etc.
AudioFormat.CHANNEL_CONFIGURATION_MONO,
// audio encoding
AudioFormat.ENCODING_PCM_16BIT,
// length
audio.length,
// mode
AudioTrack.MODE_STREAM
);

Video Playback
Video playback, unlike audio playback, can use only the
MediaPlayer. There is no video equivalent to AudioTrack.
Video uses the MediaPlayer similarly to audio files, but you
must additionally specify a view (called a surface) on which
the video can be displayed. Android offers a convenient
control that includes its own surface: the VideoView view. An
example of its use follows. It includes the addition of an
optional controller that lets the user control the playback
through a simple interface that includes buttons to start,
stop, and pause the playback, as well as a seek bar to skip
forward or back within the video’s playback progress:
// create the view (in this case it is already included in the
layout resource)
VideoView videoview = (VideoView)
findViewById(R.id.videoview);
videoview.setKeepScreenOn(true);
// used if streaming
if (videouri != null) videoview.setVideoURI(videouri);
// absolute path if it is a file
else videoview.setVideoPath(videopath);
// let's add a media control so we can control the playback
mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(videoview);
videoview.setMediaController(mediacontroller);
if (videoview.canSeekForward())
videoview.seekTo(videoview.getDuration()/2);
// start the playback
videoview.start();
Page No. .

Roll No. (in figures). Code of Paper:.

Asignmtnt f_Mobile A Derlopmet


Subittd to Ma: Sacbun Lallan
Subitted by: Ravna
Rll No- 39

glue19 hat ane ditteneniAensans a


ovaiable
v a a b in
hdnoid How heseans Can bt used 1

A Android Sensas ae vintua! daicy hat


rovde data inq hom.a set a a i a l
Ansons ace.leo hetne,9moAcobe, maquntomchy
baro mefeu hwdity rswre, Lig
oxlty and heat rate AhJons.

Sesons available_in Adnoid:


1. ybe Acelero meko-

Type- Hard a t
escupion-Mcasune Jh aceednation o
in l 2 that is ahplied to dance o
al ntce hysial axcsxy1) in dina
fhekora havit
ComoCes- Motron dcection Cabuke, HL c)
2 pe- anbitnt Jeperatunc
Sype- Hardusane
Desciphou Mcanes Jhe ambians
menatunr in C).
Signature of the Candidate
Page No.

Roll No. (n figures) . Code of Paper:.

Comhmoh Oae: Monitovng ain tomperutune

3 ypC- nraity
lype-Sottuoane o Hordioar
Dsiphion Mcasuncs J toner 6 naity in
m2 a t i sahped to a deice
On all
al n t t hyial aru 341Z)
ommoh Cse Motio Dcecion (4hake, lH cte)

ype ny
1pclardiwant
Décph0n Mtasun Jhs deice a t d
otahon inrad/4 arowd cach o
onte y al onyx, 4,z
omnon yu Kotahion dctrcti (apin, twrn,ch)

Yp Mardsarr
Disouphisn : Meaurey h ambiend Ligt doel
iurinatim) is P
Comon u ontaolling Sences Bighkncs
6ype- Untay Aceelerationm
Ype Sant on Ha-duwane
Dueiphou Mcaswt acc acceleratim force in
4 hat i applicd to a donu n all
phyd)eal aris xgz) Crclui
rghaity
ac eliathon
Usu: Monifoun aog a
yt
x-aris. J
Signature of the Candidate
Page No.
Roll No. (in figures). Code of Paper:

7 ype Magnehc icld


pt Hmd uoat
Destiptio- Mcsne he ambint geokmetic
allTnce phygieak óxs y2)
in uE
CaCan a Compas

81ye: Oicntah on
14pe Satdan
Dueipho-Mess nes odeghee sF wtati
S a duice arou
all nec ydi cal arts (yz)
As e APf l e l 3, you Can ablain
in clihah matnix and rotation matM
a a duice by uI 9haity Sency
Oaanehc
Ccnjunho oif t RotahnMatiaC) hod.
O ' Deteinr dcmce sho

p-Harrduant
TDesovbhm- Measwr ambent ai prusmc
Pa bay
se MonfoUn ain Cisure Chores

l lo e - Hardioane
Broximi
Deserpthio Mcasunt x i
pxi mity , an
objcet CMnlahi viuJcen
Signature of the Candidate
Page No.

Roll No. (in figures). Code of Paper:,

device. Tht eleriee seser tpicaly use o


deterine whetley handst iabeiheld
upto pevom-la
oe Phonepasitio dlaning a Call

12 ype- Rotation Verten


14p ottwane o Harduoare
Desoupho Mcants ILe ouenatio h deic
by poielng Tnte demends 6 die y
rotahonveto
Dse: otion clcttcion &Rotahon Vectos
dctt chon

13 pe-epenahunt.
1ype Hard ioane.
Desoi bhi0H- Mcauhr he ttnpeatune sdice
iC) The serson inplementati0 varu
acnos deice & y Awans a aeplaceA
oi ypeAmbient Tepunatwne ese
in AfT e 4
Csu:Mowtoing tenperatune
Sen san ad in Andhip APbt
Androi d - powe oleics hae built-in
Jat misnt hofh , ountah 0
Cwnohhental Codiion.
hse sson t Capable troidin
Coifh i g do0uon ad a cuurnady
and ant
kuliyou antto

Signature of the Candidate


Page No..

Roll No. (in figures). Code of Paper: .

mouto - Luee oli engoa deict mov tnt


en po)o On you an to monutos
changy anneica ehmonment hea4
duid.
an e gane mighsbrack ntadig ho
olnce main Anso to iecopler
us U 9utwiu & motio,Auk aj hl,
phake Aoaho Likewse 4
LotaLen abplitai mk we a doncy
fepoknt sehson and umidity sensan
D Callat á nehot Jow-point ona
tnavel appat Mat us[h Jeoagenc
hepe a Copaw beeni
At e u s , udrod
ovides a Cohvenient systt Called
Calld
e Seue Mana Th Ca b atttMtd via
g Syote Senice
Contt i e anguncn Contrt.S¬NSoOR-
SERVICC
Wi he SouoMonngen you he Can gck a
speeityic syon a i gttDefaubESsarl)
muhod

A Copas)k Jenson nay sOcHmg be netwnd


attes
snan a l i t s assocjafcd data, yDu
ge Ses List()

Signature of the Candidate


Page No.
Roll No. (in figures). Code of Paper: .

Senson Mlanag e
(Suyon aManat Contontget SystoSenvice (ConkedSCNseR
SCRVICE
Il gcktis The defanCf a
Ceelezomctey
Scso
accelmhg get Defrull Sensoy (Senso:1yrE-
ACCELEOMETER);
Igetia h ALs attclo mutcs
i s KSenje7 lisl:g e t SensoyisSen
TYE Ac CELC ROME TË R_

yougot
achall nabl fen andstart gebbin theis
dsa by ntgisnig skney agaiut t a
ssou.
Sense bvenfLiskaenn Sensontent Listenc(O
Ovevnidt
bubic void mACCura eyChanged (Sensere otndo,
altunacy
O v i de
public void drwacy_Charsederyo ensoh,
m

Intaltunaty) t)x
bubcvoid on Séyan Ched (Seantvent tved)1

e g i s i s a Liseae
negiten istegey (Listeney, dehuo», Senso
.

Man Cy.SCNsoR DCLay_UT );

Signature of the Candidate


CLIENT-SERVER APPLICATION
Developing client-server applications for the mobile device is no more difficult
than developing for personal computers. In fact, the java.net package works
nicely on Android devices. The example application we will build sends a text
string to a server and receives the text string back with an added confirmation. As
you probably assume, you can build both the client side and the server side on
the same Eclipse platform. However, you will probably want to run the server-side
application on another machine with another IP address on the same local area
network. If you have written any client-server applications, you are likely familiar
with IP addresses and port numbers; this application uses port 8888, an arbitrary
choice. You can use just about any port number you want; just stay away from the

numbers zero through 1023. Because port numbers are 16-bit values, there are
65,536 choices. However, they are broken into the groups shown here:
0 to 1023
1024 to 49151
49152 to 65536
Well-known port numbers Registered ports Dynamic or private ports Because you
are likely to be doing this project on a local area network using unroutable IP
addresses, the port choice isn’t critical. For convenience sake, the server-side
source code for this experiment is listed here:
import java.io.*;
import java.net.*;
import java.util.*;
public class SimpleJavaServer {
public static final int PORT=8888;
public static void main(String args[]){
new SimpleJavaServer().doIt();
}
public void doIt(){
String received="";
try{ ServerSocket ss = new ServerSocket( PORT );
while( true ){ Socket sock = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
sock.getInputStream() ) ); received=in.readLine();
System.out.println(received);
OutputStreamWriter out = new OutputStreamWriter( sock.getOutputStream() );
BufferedWriter bw=new BufferedWriter(out);
bw.write(received +" received by server \n"); bw.flush(); }
}
catch( Exception e ){ e.printStackTrace();
}}}
On the client side, there are some preliminary steps we need to take before
getting into code. First, we have to be sure the device ’s networking capability is
available to the

application, so we need to add a permission line in the manifest file. The


complete file is listed next. Look for the line that starts with <uses-permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sheusi.SimpleAndroidClient"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".SimpleAndroidClientActivity"
android:label="@string/app_name"> <intent-filter> <action
android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </activity>
</application> </manifest>
The user interface will simply be two EditText widgets: one for the text going out
to the server, and the other to display the message that comes back. There’s also
a Button widget between the two EditText widgets to start the transmission to
the server. The server’s IP address is hard-coded in this example, as is the port
number. That certainly restricts the utility of the application, but after all it is just
an experiment. You could modify that application to accept a target IP address
and port number from the user through an additional EditText or two if you so
desire. If you stay with the hard-coded values, you must obtain the IP of the
server-side machine. That is simple enough using the ipconfig console command
on a Windows machine or the ifconfig command on a Linux machine. There are
plenty of other ways to find a machine’s IP address. Following is the listing for
the Java file:
package com.sheusi.SimpleAndroidClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
import java.net.*;
import java.io.*;
import android.util.*;
public class SimpleAndroidClientActivity extends Activity {
/** Called when the activity is first created. */
EditText etsend=null;
EditText etreceive=null;
Button b1=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etsend=(EditText)findViewById(R.id.sendString);
etreceive=(EditText)findViewById(R.id.receiveString);
b1=(Button)findViewById(R.id.connect);
b1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Socket s=null;
String response="";
try{
InetSocketAddress sa=new InetSocketAddress("192.168.1.231",8888);
s=new Socket();
s.connect(sa,2000);
OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream());
osw.write(etsend.getText().toString()+"\n"); osw.flush();
InputStreamReader isr =new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
response=br.readLine();
etreceive.append(response+"\n"); s.close();
}
catch(IOException ioe){
Log.e("Code Error",ioe.getMessage());
etreceive.setText("Couldn’t connect with server");
} } }); } }
You will notice that we use the java.net and java.io packages to do most of the
work. In fact, the code in the listener for the Button object is almost a mirror
image of what is in the server-side code. The connect( ) method used here takes
two parameters. One is the InetSocketAddress variable, and the other is a
timeout value. The number 2000 represents 2000 milliseconds, or 2 seconds.
After 2 seconds, the application will give up trying to reach the server and print an
error message in the
second EditText field. Otherwise, the application would hang trying to connect to
a nonexistent server. Don’t forget to change the IP address in the previous listing
to the IP address on your server machine, and be sure to start the server
application before you try the client-side application in the emulator. screen shot
of the application as it would appear if the server is found and has responded to
the client.
Example
Client
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android =
"http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
tools:context = ".MainActivity">
<EditText
android:id = "@+id/etIP"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "IP-Address"
android:inputType = "text" />
<EditText
android:id = "@+id/etPort"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/etIP"
android:hint = "Port No"
android:inputType = "number" />
<Button
android:id = "@+id/btnConnect"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/etPort"
android:layout_gravity = "center"
android:layout_marginTop = "16dp"
android:text = "Connect To Server" />
<TextView
android:id = "@+id/tvMessages"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/etMessage"
android:layout_below = "@+id/btnConnect"
android:inputType = "textMultiLine"
android:textAppearance =
"@style/Base.TextAppearance.AppCompat.Medium" />
<EditText
android:id = "@+id/etMessage"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/btnSend"
android:hint = "Enter Message"
android:inputType = "text" />
<Button
android:id = "@+id/btnSend"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentBottom = "true"
android:text = "SEND" />
</RelativeLayout>

Step 3 − Add the following code to res/layout/MainActivity.java.


package com.client.myapplication.client;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
Thread Thread1 = null;
EditText etIP, etPort;
TextView tvMessages;
EditText etMessage;
Button btnSend;
String SERVER_IP;
int SERVER_PORT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etIP = findViewById(R.id.etIP);
etPort = findViewById(R.id.etPort);
tvMessages = findViewById(R.id.tvMessages);
etMessage = findViewById(R.id.etMessage);
btnSend = findViewById(R.id.btnSend);
Button btnConnect = findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvMessages.setText("");
SERVER_IP = etIP.getText().toString().trim();
SERVER_PORT =
Integer.parseInt(etPort.getText().toString().trim());
Thread1 = new Thread(new Thread1());
Thread1.start();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
new Thread(new Thread3(message)).start();
}
}
});
}
private PrintWriter output;
private BufferedReader input;
class Thread1 implements Runnable {
@Override
public void run() {
Socket socket;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.setText("Connected\n");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message ! = null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("server: " + message +
"\n");
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Thread3 implements Runnable {
private String message;
Thread3(String message) {
this.message = message;
}
@Override
public void run() {
output.write(message);
output.flush();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("client: " + message + "\n");
etMessage.setText("");
}
});
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android =
"http://schemas.android.com/apk/res/android"
package = "com.client.myapplication.client">
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name =
"android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity
android:name =
"com.client.myapplication.clienlt.MainActivity"
android:label = "Client">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name =
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Q. Write a short note on :

(A) Near field communication

(B) Native libraries and headers

(C) Shadows and Gradients

Ans : (A) Near field communication:

Near Field Communication (NFC) is a set of short-range wireless


technologies, typically requiring a distance of 4cm or less to initiate a connection.
NFC allows you to share small payloads of data between an NFC tag and an
Android-powered device, or between two Android-powered devices.
Tags can range in complexity. Simple tags offer just read and write semantics,
sometimes with one-time-programmable areas to make the card read-only. More
complex tags offer math operations, and have cryptographic hardware to
authenticate access to a sector. The most sophisticated tags contain operating
environments, allowing complex interactions with code executing on the tag. The
data stored in the tag can also be written in a variety of formats, but many of the
Android framework APIs are based around a NFC Forum standard called NDEF
(NFC Data Exchange Format).

Android-powered devices with NFC simultaneously support three main modes of


operation:
1. Reader/writer mode, allowing the NFC device to read and/or write passive
NFC tags and stickers.
2. P2P mode, allowing the NFC device to exchange data with other NFC
peers; this operation mode is used by Android Beam.
3. Card emulation mode, allowing the NFC device itself to act as an NFC
card. The emulated NFC card can then be accessed by an external NFC
reader, such as an NFC point-of-sale terminal.
NFC Basics
This document describes how Android handles discovered NFC tags and how it
notifies applications of data that is relevant to the application. It also goes over
how to work with the NDEF data in your applications and gives an overview of the
framework APIs that support the basic NFC feature set of Android.

Advanced NFC
This document goes over the APIs that enable use of the various tag
technologies that Android supports. When you are not working with NDEF
data, or when you are working with NDEF data that Android cannot fully
understand, you have to manually read or write to the tag in raw bytes using
your own protocol stack. In these cases, Android provides support to detect
certain tag technologies and to open communication with the tag using your
own protocol stack.

Host-based Card Emulation


This document describes how Android devices can perform as NFC cards
without using a secure element, allowing any Android application to emulate a
card and talk directly to the NFC reader.

How to activate NFC functionality

If your Android smartphone is NFC disabled, you need to activate it to use


NFC. To activate NFC, do the following activities:

1. Go to Settings of your Android device.


2. Select the Connected Devices option.
3. Now, choose Connection preferences.
4. Look at the options NFC and Android Beam.
5. Turn both of these options ON.

Where can I use NFC for, and how do I do it?

o Send a phone number.


o Send a picture.
o Send a document.
o Send directions.
o Launch an app on someone else's phone.
o Make a payment.
o Sharing apps.

(B) Native libraries and headers:

The Android NDK provides a set of native headers and shared library files that
has gradually increased with successive releases of new Android API levels. This
page explains these headers and files, and maps them to specific Android API
levels.

Overview

There are two basic steps to enable your app to use the libraries that the NDK
provides:
1. Include in your code the headers associated with the libraries you wish to
use.
2. Tell the build system that your native module needs to link against the
libraries at load time. For example, to link
against /system/lib/libfoo.so, add the following line to
your Android.mk file:

LOCAL_LDLIBS := -lfoo

To list multiple libraries, use a space as a delimiter. For more information


about using the LOCAL_LDLIBS variable, see Android.mk.
For all API levels, the build system automatically links the standard C libraries, the
standard C++ libraries, real-time extensions, and pthread; you do not need to
include them when defining your LOCAL_LDLIBS variable. For more information
about the C and C++ libraries, see Android API level 3.
The NDK often provides new headers and libraries for new Android releases.
These files reside under $NDK/platforms/android-
<level>/<abi>/usr/include. When the NDK does not have a specific new
group of headers and libraries for an Android API level, it means that an app
targeting that level should use the most recently released NDK assets. For
example, there was no new release of NDK headers or libraries for Android API
levels 6 and 7. Therefore, when developing an app targeting Android API level 7,
you should use the headers and libraries located under android-5/.
(C) Shadows and Gradients:

Shadows :

Robolectric works by creating a runtime environment that includes the real


Android framework code. This means when your tests or code under test
calls into the Android framework you get a more realistic experience as for
the most part the same code is executed as would be on a real device.
There are limitations however:

1. Native code - Android native code cannot execute on your


development machine.
2. Out of process calls - There are no Android system services running
on your development machine.
3. Inadequate testing APIs - Android includes next to no APIs suitable
for testing

Shadows classes :
Shadow classes always need a public no-arg constructor so that the
Robolectric framework can instantiate them. They are associated to the
class that they Shadow with an @Implements annotation on the class
declaration.
Shadow classes should mimic the production classes’ inheritance
hierarchy. For example, if you are implementing a Shadow
for ViewGroup, ShadowViewGroup, then your Shadow class should
extend ViewGroup’s superclass’s Shadow, ShadowView

Methods

Shadow objects implement methods that have the same signature as the
Android class. Robolectric will invoke the method on a Shadow object when
a method with the same signature on the Android object is invoked.

Suppose an application defined the following line of code:


...

this.imageView.setImageResource(R.drawable.pivotallabs_log
o);
...

Gradients :

The user interface (UI) of modern apps is improving all the time.
Designers are experimenting with various styles and color combinations to
see which ones work best with the Android App. GradientDrawable is a
key component of Android that is commonly used these days.

What actually is a gradient drawable?

A GradientDrawable is drawable with a color gradient that can be used for


buttons, backgrounds, and so on. Let’s begin with a simple example of
creating a button in Android with an aqua colored background:
This can be achieved in the following way:

 XML

<Button
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:text="Geeks for Geeks"
android:background="#00FFFF"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
Create a new file gfg color drawable.xml in the drawable package and
enter the following code:

 XML
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="45"
android:startColor="#D98880"
android:centerColor="#F4D03F"
android:endColor="#48C9B0"/>
</shape>

We’ve used the <gradient /> tag and added three colour codes: startColor,
centerColor, and endColor.
Roll No.(infigures Code of Paper

Mobil A putahon Developmunt


Amqumeut

Evplam all dedabai opiaton h SLie

Audkciol OS hay th o w wplene tatiow o pxteim


CAUD Cade , ad , Updatc, Delltc) epUations, So
CRUD
Avwoid ovcles a 3et G mes avaulbl
andneid . databa Qud avudioid.cletabae.6qt

packaes

&SLH Databan
Obycct
pdatc Delte

* wakt- a t a dotabuc e &implu


t andkool by um SSLtTOpenlelpes
Aas. ALLOpenltdpa awbytiact clus
Nth wo abtaet mthods ouerte 88Litcdataba
oldVmon
db) ovd owUpaslu ($&LitoDatabau db, ivt
int new Veisirn aud May me dateuba
hultul unetiau.

Sign. Of the candidate.


Page No.
Roll No.(m figures) Code of Paper

d
fuluedt SQtuDtubayc nt Dadrhme)acttnve
1
tctimu
Callcd c c tRoy heut ttthe applicathn Coulltu

Hwi be dalld vohenener Mut


setsutableDakahae )
act Readalole Dadabag [) ex
uwim available i u p gttOpeuta pe
QLOpemllelpa calls maeattl)
cm so
itaetiatt
ethod o t l CaAakn dactabm and
9LHtDaekabae obgcek

oldVuran, t wwVunen
epade SQLH Databast db t
Culy talld oenira e a updatto
iKVt m o Mtoupdatu a
*o eRLment naluw ot yaluue
vaRiable pawmd m a &uclos ogwsiAUct
vidleu
mUpgtad mod w Cam wite qLLeRNe
putem

updat
lo pesie-m wmet, a d , claloke und
epatowt h e e au two ways

Ruaol eleletu
ww mhult fwetowa tu cel
p date doeta Thase operatiows eloctd
e pdatu
sQLtcBatabaçe clona
wwwties pAovlded

candidate.
Page No. 2. Sign. Of the
Roll No.in figures) Code of Paper

Puv uues

etthen Aauu ,ett.


ciatabaies ik Mysi, Sq
ttus ca uR will haue
s t aua pwcol the qu stA
Jaw uuy tamg 8 , 8tsmCeleehioA1gi
e SxecsL(&t Sq, Obiit[ omdAgs)
ethod o pateinn Opuahons

west To pestecm wat epelatvw wy aRaucteuao


dall innatfunchn
quuy, we hae o
available SSLHDatabau v

uublic Jovg iwkat t wm taliehJawe t i


NuuLlotmntack, CoudevtVtervalueA

Pollewn eXamplu Sauw Guuery te t

9y INSERT NTO "+ IAcmilable AJAME


sti
+ VALUES (o,?,2)
LitDatabaw db getwutable Datuhae ( );
dbexec SL (quoty, uo Atyl) (Htm.Mae
Hem deveto ) ;
db teel)
Sign. Of the candidate.
PageNo.3.
Aol No.in figures) UR Code of Paper a e t r e

to o
aw
e ut t Cpaatron. Movwevt, wtBk paumeteEa
qceies huchm, a au atuintd tei
&Cus e fuue & oplatiom

Upelatt t has tow para H% wo oli


la to iwwat huwehon a t
able Naw and CovtetValuns. Autte uo
wwwclauw [8tain) and vwhuARas(stay)
ubue ut updste Stai tableNawe ,Covetent ValuLA
CovrtntValuies, gtsin whecla
&tm oniAa)
Updot function wTl Retum YUmmbe ot oes
afctcd &uces O thew

Delut a&mula to updatt tomd Delett huneti


v a lable in'SgLHtDatabam tlas
belel uneki takis ttieu patanetn._

uubl nt delte (stay table NJame & i


Ouellae 8tiy lJ xotuece Hags)

Sign. Of the candidate.


Page No.
Page No.

Roll No. (in figures). Code of Paper:

Hen 6lanaAp whece tlase Cptional

ull oleletu oull


u m b u

table elelet fuwcho l l m nu


atd Aows whnllam peRd

h 0.

Pad &eluet) s8LitDatabaw Cla eide qua


wetuod to cadl data 1aO table.
qM ) muthod CueRloadad rih dtltient
Dalamdtts.t etuRm Cuse object so
Wae j 4ult get wiw quutd datu it
povides daut funetina vow eadiy data .

putblie Cuwse quuy |Stiuy talde,St8y ) coluum


st selutiin , 81Mng)Aeluthan Angs,attuy

publieCume g 1 table, Stiy [I olumw Stsie


din, tuin ácluetionh St 50uphyM

pudlic Cuo guu( beoesu distiwet,Jtai kable, Stsil\


toluuwws dt lerho , teinel) uetionAags
oupy tig awi Stay duhy

5
Signature of the Candidate

You might also like