Testing and Securing Android Studio Applications - X

Testing and Securing Android Studio Applications - X
TestingandSecuringAndroidStudio
Applications
TableofContents
TestingandSecuringAndroidStudioApplications
Credits
AbouttheAuthors
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.IntroductiontoSoftwareSecurity
Softwaresecurityterms
Threats,vulnerabilities,andrisks
Threat
Vulnerability
Risk
Securecode-designprinciples
Testingthebasics
Summary
2.SecurityinAndroidApplications
Themobileenvironment
AnoverviewofAndroidsecurity
Permissions
Interapplicationcommunication
Intents
Contentproviders
Summary
3.MonitoringYourApplication
DebuggingandDDMS
Threads
Methodprofiling
Heap
AllocationTracker
NetworkStatistics
FileExplorer
EmulatorControl
SystemInformation
Summary
4.MitigatingVulnerabilities
Inputvalidation
SQLinjection
Permissions
Handlingauser’sdataandcredentials
Interapplicationcommunication
SecuringIntents
Securingthecontentproviders
Summary
5.PreservingDataPrivacy
Dataprivacy
Sharedpreferences
Filesintheinternalstorage
Filesintheexternalstorage
Thedatabasestorage
Encryption
Theencryptionmethods
Generatingakey
Usingencryptiontostoredata
Summary
6.SecuringCommunications
HTTPS
SSLandTLS
Serverandclientcertificates
Keytoolintheterminal
AndroidStudio
CodeexamplesusingHTTPS
Summary
7.AuthenticationMethods
Multifactorauthentication
Theknowledgefactor
Thepossessionfactor
Theinherencefactor
Loginimplementations
AccountManager
Summary
8.TestingYourApplication
TestinginAndroid
TestingtheUI
TheuiautomatorAPI
TheUiDeviceclass
TheUiSelectorclass
TheUiObjectclass
TheUiCollectionclass
TheUiScrollableclass
Theuiautomatorviewertool
TheUItestproject
RunningUItestcases
Summary
9.UnitandFunctionalTests
Testingactivities
Thetestcaseclasses
Instrumentation
Thetestcasemethods
TheAssertclassandmethod
TheViewAssertsclass
TheMoreAssertsclass
UItestingandTouchUtils
Themockobjectclasses
Creatinganactivitytest
Creatingaunittest
Theunittestsetup
Theclocktest
Thelayouttest
TheactivityIntenttest
Creatingafunctionaltest
Thefunctionaltestsetup
TheUItest
TheactivityIntenttest
Thestatemanagementtest
Gettingtheresults
Summary
10.SupportingTools
Toolsforunittesting
Spoon
Mockito
AndroidMock
FESTAndroid
Robolectric
Toolsforfunctionaltesting
Robotium
Espresso
Appium
Calabash
MonkeyTalk
Bot-bot
Monkey
Wireshark
Othertools
Genymotion
Summary
11.FurtherConsiderations
Whattotest
Networkaccess
Mediaavailability
Changeinorientation
Serviceandcontentprovidertesting
Developeroptions
Gettinghelp
Summary
Index
TestingandSecuringAndroidStudio
Applications
TestingandSecuringAndroidStudio
Applications
Copyright©2014PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:August2014
Productionreference:1190814
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78398-880-8
www.packtpub.com
CoverimagebyRavajiBabu(<[email protected]>)
Credits
Authors
BelénCruzZapata
AntonioHernándezNiñirola
Reviewers
NicoKüchler
AnandMohan
RaviShanker
KevinSmith
AbhinavaSrivastava
CommissioningEditor
AmarabhaBanerjee
AcquisitionEditor
RebeccaYoué
ContentDevelopmentEditor
ParitaKhedekar
TechnicalEditor
MrunmayeePatil
CopyEditors
RoshniBanerjee
AdithiShetty
ProjectCoordinators
NehaThakur
AmeySawant
Proofreader
AmeeshaGreen
Indexers
MariammalChettiyar
RekhaNair
TejalSoni
PriyaSubramani
Graphics
RonakDhruv
ProductionCoordinator
ConidonMiranda
CoverWork
ConidonMiranda
AbouttheAuthors
BelénCruzZapatareceivedherengineeringdegreeinComputerSciencefromthe
UniversityofMurciainSpain,withspecializationinsoftwaretechnologiesandintelligent
andknowledgetechnologies.ShehasearnedanMScdegreeinComputerScienceandis
nowworkingonherPhDdegreeinSoftwareEngineeringResearchGroupfromthe
UniversityofMurcia.
BelénisbasedinSpain;however,duetothefieldofherPhD,sheisnowcollaborating
withUniversitéMohammedV-SoussiinRabat.Herresearchisfocusedonmobile
technologiesingeneralandalsoappliestomedicine.
Belénhasworkedasamobiledeveloperforseveralplatforms,suchasAndroid,iOS,and
theWeb.SheistheauthorofthebookonAndroidStudio:AndroidStudioApplication
Development,PacktPublishing.
Tofollowherprojects,shemaintainsablogathttp://www.belencruz.comandyoucan
[email protected]_cz.
IwouldliketothankPacktPublishingforofferingmetheopportunitytowritethisbook.I
wouldparticularlyliketothankParitaKhedekar,RebeccaYoué,andAmeySawantfor
theirvaluablehelp.
IwouldalsoliketothankAntonio,theco-authorofthisbook,formakingeverythingso
easy;mynewfriendsofadventure,especiallyPaloma,Camilla,andAdrián,fortheselast
months;myfriendsfromwaybackforvisitingme;andfinally,myfamilyforsupporting
me.
AntonioHernándezNiñirolahasanengineeringdegreeinComputerScienceandisa
mobileapplicationdeveloper.HewasbornandraisedinMurciainthesoutheastregionof
SpainandiscurrentlylivinginRabat,Morocco.Hehasdevelopedseveralwebsitesand
mobileapplications.
AftercompletinghisdegreeinComputerScience,hepursuedaMaster’sdegreein
TeacherTrainingforInformaticsandTechnology.Antoniopushedhisstudiesfurtherand
isnowadoctoralcandidateundertheSoftwareEngineeringResearchGroupofthefaculty
ofComputerScienceattheUniversityofMurcia,andisactuallyaresearcherforthe
UniversitéMohammedV-SoussiinRabat.
Youcanvisithiswebsiteathttp://www.ninirola.estofindoutmoreabouthimandhis
projects.
IwouldliketobeginbythankingRebeccaYoué,ParitaKhedekar,andAmeySawantfor
theirvaluableinput.ThankyoutoeveryoneatPacktPublishingwhomakewritingabook
suchanenjoyableexperience.
ThankyouBelén,theotherhalfofthisbook,formakingeverythingmuchbetter.Iwould
finallyliketothankmyfamilyfortheirsupport,mynewfriendsinMorocco,myold
friendsinSpain,andeveryonewhohelpedmebewhoIamtoday.
AbouttheReviewers
NicoKüchlerlivesinBerlin,Germany.Hedidanapprenticeshipasamathematicaltechnicalsoftwaredeveloper.Hehasworkedforthegambleindustryandasanonline
shopprovider.HehasbeenworkingatDeutschePostE-POSTDevelopmentGmbHfor2
yearswithinthescopeofAndroidappdevelopment.
Hehasbeenmaintainingaprojectthatprovidesaquickstartwithtest-drivenAndroidapp
developmentathttps://github.com/nenick/android-gradle-template.
AnandMohanisageekandastart-upenthusiast.HegraduatedfromtheIndianInstitute
ofInformationTechnology,Allahabad,in2008.HehasworkedwithOracleIndiaPvt.Ltd.
for4years.In2012,Anandstartedhisownventure,TripTern,alongwithhisfriends,
whichisacompanythatalgorithmicallyplansoutthemostoptimizedtravelitineraryfor
travelersbyutilizingBigDataandmachine-learningalgorithms.AtTripTern,Anandhas
developedandimplementedofflineAndroidapplicationssothattravelerscanmodifytheir
itineraryonthegowithoutrelyingonanydataplan.
Apartfromworkingonhisstart-up,Anandalsolikestofollowthelatesttrendsin
technologyandbestsecuritypractices.
RaviShankerhasalwaysbeenfascinatedwithtechnology.He’sbeenapassionate
practitionerandanavidfollowerofthedigitalrevolution.HelivesinSydney,Australia.
Helovestraveling,presenting,reading,andlisteningtomusic.Whennottinkeringwith
thetechnology,healsowieldsasetofbrushesandpaletteofcolorstoputtherightsideof
hisbraintowork.
Ravihashonedhisskillsoveradecadeindevelopment,consulting,andproductand
projectmanagementforstart-upstolargecorporationsinairline,transportation,telecom,
media,andfinancialservices.HehasworkedintheUSA,UK,Australia,Japan,andmost
ofAsia-Pacific.Hehasalsorunacoupleofstart-upsofhisowninthepast.
Raviisoftenseenblogging,answeringoraskingquestionsonStackExchange,postingor
upvoting,andtweetingonthelatestdevelopmentsindigitalspace.Hehasmade
presentationsatmeetingsandinterestgroupsandhasconductedtrainingclasseson
varioustechnologies.He’salwaysexcitedattheprospectofnewandinnovative
developmentsinimprovingthequalityoflife.
AbhinavaSrivastavahascompletedhisBachelorofTechnologydegreeinComputer
ScienceEngineeringfromIndiain2008andhasalsoreceivedaDiplomainWirelessand
MobileComputingfromACTS,C-DAC,Indiain2009.
HestartedhiscareerasaSoftwareEngineeratPersistentSystemsbeforemovingto
Singapore,andiscurrentlyworkingwithMasterCard,Singapore.
Abhinavaisacoretechnologistbyheartandlovestoplaywithopensourcetechnologies.
Hemaintainshisownblogathttp://abhinavasblog.blogspot.in/andkeepsjottinghis
thoughtsfromtimetotime.
Iwouldliketothankmyfamilymembersfortheircontinuoussupport,especiallymyelder
brother,AbhishekSrivastava,whohasbeenamentorandaninspiration.Lastbutnotleast,
IwouldliketoextendmygratitudetoPacktPublishingforgivingmetheopportunityto
beapartofsuchawonderfulexperience.
www.PacktPub.com
Supportfiles,eBooks,discountoffers,and
more
Youmightwanttovisitwww.PacktPub.comforsupportfilesanddownloadsrelatedto
yourbook.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand
ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas
aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith
usat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup
forarangeoffreenewsletters,andreceiveexclusivediscountsandoffersonPacktbooks
andeBooks.
http://PacktLib.PacktPub.com
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital
booklibrary.Here,youcanaccess,readandsearchacrossPackt’sentirelibraryofbooks.
Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,printandbookmarkcontent
Ondemandandaccessibleviawebbrowser
FreeaccessforPacktaccountholders
IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccess
PacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsfor
immediateaccess.
Preface
Mobileapplicationshavebecomeverypopularinthelastfewyearsthankstoahuge
incrementintheuseofmobiledevices.Fromadeveloper’spointofview,Androidhas
becomeanimportantsourceofincomethankstothedifferentapprepositories,suchas
GooglePlayandAmazonAppstore.
Withanincreaseinthenumberofapplicationsavailable,usershavebecomemore
demandingaboutthefeaturesoftheapplicationstheyaregoingtouse.Asolidtestingof
theapplicationanditssecurityaspectsarethekeyfactorsinthepursuitofsuccessforan
application.Bugsandsecurityissuesareobviouslynotfeaturesthathelpyourapplication
dowellintheincreasinglymoreexigentmarketofAndroid.
Inthisbook,youaregoingtolearnhowtoturnyourAndroidapplicationintoasolidly
debuggedandsecureapplication.Toachievethis,youwilllearnhowtouseAndroid
Studioanditsmostimportantfeatures:testingandsecurity.
Whatthisbookcovers
Chapter1,IntroductiontoSoftwareSecurity,introducestheprinciplesofsoftware
security.
Chapter2,SecurityinAndroidApplications,describesthedistinctivefeaturesfoundin
mobileenvironmentsandtheAndroidsystem.
Chapter3,MonitoringYourApplication,presentsthedebuggingenvironment,oneofthe
mostimportantfeaturesofanIDE.
Chapter4,MitigatingVulnerabilities,describesthemeasuresthatshouldbetakento
preventattacks.
Chapter5,PreservingDataPrivacy,presentsthemechanismsofferedbyAndroidto
preservetheprivacyofuserdata.
Chapter6,SecuringCommunications,explainsthemechanismsofferedbyAndroidto
securecommunicationsbetweenanAndroidapplicationandanexternalserver.
Chapter7,AuthenticationMethods,presentsdifferenttypesofauthenticationmethods
usedinAndroidmobiledevices.
Chapter8,TestingYourApplication,introduceswaystotestanapplicationusingAndroid
Studio.
Chapter9,UnitandFunctionalTests,coversunitandfunctionalteststhatallow
developerstoquicklyverifythestateandbehaviorofanactivityonitsown.
Chapter10,SupportingTools,presentsasetofexternaltoolsdifferentfromAndroid
StudiotohelpdeveloperstestanAndroidapplication.
Chapter11,FurtherConsiderations,providessomefurtherconsiderationsthatareuseful
fordevelopers.
Whatyouneedforthisbook
Forthisbook,youneedacomputerwithaWindows,MacOS,orLinuxsystem.Youwill
alsoneedtohaveJavaandtheAndroidStudioIDEinstalledonyoursystem.
Whothisbookisfor
ThisbookisaguidefordeveloperswithsomeAndroidknowledge,butwhodonotknow
howtotesttheirapplicationsusingAndroidStudio.Thisbookissuitablefordevelopers
whohaveknowledgeaboutsoftwaresecuritybutnotaboutsecurityinmobile
applications,andalsofordeveloperswhodonothaveanyknowledgeaboutsoftware
security.It’sassumedthatyouarefamiliarwithAndroidanditisalsorecommendedtobe
familiarwiththeAndroidStudioIDE.
Conventions
Inthisbook,youwillfindanumberoftextstylesthatwillhelpyoudistinguishbetween
differentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanation
oftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,
pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Tosend
anorderedbroadcast,youcancallthesendOrderedBroadcastmethod.”
Ablockofcodeissetasfollows:
Instrumentation.ActivityMonitormonitor=
getInstrumentation().addMonitor(SecondActivity.class.getName(),null,
false);
Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevant
linesoritemsaresetinbold:
@Override
protectedvoidsetUp()throwsException{
super.setUp();
Intentintent=newIntent(getInstrumentation().getTargetContext(),
MainActivity.class);
startActivity(intent,null,null);
mActivity=getActivity();
Anycommand-lineinputoroutputiswrittenasfollows:
adbshellmonkey–pcom.packt.package–v100
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,in
menusordialogboxesforexample,appearinthetextlikethis:“Themultiplicationis
madewhentheButton1buttonisclicked.”
Note
Warningsorimportantnotesappearinaboxlikethis.
Tip
Tipsandtricksappearlikethis.
Readerfeedback
Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthis
book—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforusto
developtitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,and
mentionthebooktitlethroughthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingor
contributingtoabook,seeourauthorguideonwww.packtpub.com/authors.
Customersupport
NowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelp
youtogetthemostfromyourpurchase.
Downloadingtheexamplecode
YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfrom
youraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcan
visithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlyto
you.
Errata
Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdo
happen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthe
code—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansave
otherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.If
youfindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/support,
selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetails
ofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandthe
erratawillbeuploadedtoourwebsite,oraddedtoanylistofexistingerrata,underthe
Erratasectionofthattitle.
Piracy
PiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.At
Packt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucome
acrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswith
thelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpirated
material.
Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluable
content.
Questions
Youcancontactusat<[email protected]>ifyouarehavingaproblemwithany
aspectofthebook,andwewilldoourbesttoaddressit.
Chapter1.IntroductiontoSoftware
Security
YouwanttolearnhowtoimproveyourAndroidapplicationssothatthey’resecureand
robust.Youwouldliketolearnaboutmobilesoftwaresecurityanditsmostimportant
threatsandvulnerabilities.Youwantyouruserstobesatisfiedwhileensuringthattheir
dataissecureandthattheapplicationhasnobugs.Canyoudothiseasily?Whatdoyou
needtodoinordertoachievethis?
Thischapterwillteachyouthebasicsofsoftwaresecurity.We’llbeginbyteachingyou
thedifferentsecuritytermsthatwewilluseinthisbook.You’llseethemostimportant
threatsandvulnerabilitiesthatmayaffectyourapplication.You’llthenlearnaboutsecure
codedesignprinciples,aswellashowtotestourapplicationforsecurityissues.
Inthischapter,wewillcoverthefollowingtopics:
Softwaresecurityterms
Threats,vulnerabilities,andrisks
Securecodedesignprinciples
Securitytesting
Softwaresecurityterms
Inrecentyears,theInternethasexperiencedahugeincreaseinelectroniccommerce(ecommerce).Thisincreaseinmonetizationofinformationinthecloudmeansthat
attackerscannowberewardedfinancially,socially,andevenpoliticallyforasuccessful
attack.Thereisalowriskinattemptingtheseattacks,sincethereisasmallchanceof
gettingcapturedandtherefore,ofprosecution.Withamoremotivatedenemy,companies
andenterpriseshavetoimprovetheirsecuritymeasurestofacethesenewthreats.They
mustidentifythethreatsanddefendthevulnerabilitiesthatmayaffectthedatathathasa
bigimpactontheirbusiness.
Inordertounderstandthecontentofthisbookcompletely,youwillfirstneedto
understandsomebasicconceptsaboutsoftwaresecurity:
Accesscontrol:Thisensuresselectiveaccesstoresourcesbyusersthatareentitledto
it.
Asymmetriccryptography:Thisisalsoknownasthepublickeycryptographyand
usesalgorithmsthatemployapairofkeys—onepublicandoneprivate.Apublickey
isusedtoencryptthedatawhileaprivatekeyisusedtodecryptdata.
Authentication:Thisisaprocessthroughwhichwecanconfirmtheidentityofa
user.
Authorization:Thisisaprocessthroughwhichwegivesomeonepermissiontodo
orhavesomething.
Availability:Thismeansthatthesystemanddataareavailabletoauthorizedusers
whentheymaymakeuseofit.
Bruteforce:Thisisaverybasicandnonoptimalcryptanalysistechniquethattries
everypossibilitytocrackakeyorapassword.
Cipher:Thisisacryptographicalgorithmthatmaybeusedforencryptionand
decryption.
Codeinjection:Thisisanattackwherethecodeisinsertedintoapplicationqueries.
ThiskindofattackiscommonlyusedtoalterdatabasesviaSQLinjections.
Confidentiality:Thisspecifiesthatthedataisonlyavailableforuserswhohave
permissiontoaccessit.
Crack:Thisistheprocessthroughwhichanattackerattemptstogainaccesstoa
machine,network,orsoftware.
Decryption:Thisistheprocessthroughwhichanencryptedmessageistransformed
intoitsoriginalstate.
Denial-of-service(DoS):Thisisatypeofattackthatmakesanonlineresource
unavailableforafixedamountoftime.
Distributeddenial-of-service(DDoS):ThistypeofattackissimilartotheDoS
attack,butitisperpetratedfromseveralmachinesandisgenerallymoreeffective
thanaDoSattack.
Dictionaryattack:Thisisabasiccryptanalysistechniquethatusesallthewordsina
dictionarywhentryingtocrackakeyorpassword.
Encryption:Thisisaprocessthroughwhichaplainpieceofdataistransformedinto
anencryptedstate,withtheobjectiveofconcealingthisinformationinorderto
preventaccessfromunwantedsources.
Hashfunction:Thisisatypeofalgorithmthatmapsdataofdifferentsizesintodata
ofafixedsize.
Hijackattack:Thisisaformofattackinwhichanalreadyestablished
communicationisseizedandactsasoneoftheoriginalparticipants.
HypertextTransferProtocolSecure(HTTPS):Thisisanapplicationlevelprotocol
basedonHTTPthatallowsasecuretransferofsensitiveinformationintheformof
hypertext.
Integrity:Thismeansthattheinformationisaccurateandisnotchanged
accidentallyordeliberately.
MD5:Thisisaverycommonlyusedhashfunction.
Man-in-the-middleattack:Thisisatypeofattackwheretheattackerassumesa
positioninthemiddleofacommunication,interceptsandreadsthemessagesofa
communication,andletsthevictimsbelievethattheyaredirectlyconnectedtoeach
other.
Password:Thisisastringofcharactersusedforauthentication.
Phishing:Thisisanattackattemptthatappearstobefromareliablesourceand
trickstheuserintoenteringtheirauthenticationcredentialsinadifferentdomainor
application.
Risk:Thisisthelikelihoodofanattackhappeningandsucceeding.
SHA1:Thisisacommonlyusedhashfunction.
Sniffingattack:Thisisanattackthatanalysesthepacketsexchangedinanetworkin
ordertoextractusefulinformationfromthem.
Spoofingattack:Thisisanattackwhereanunauthorizedentitygainsaccesstoa
systemwiththecredentialsofanauthorizeduser.
Symmetriccryptography:Thisisatypeofcryptographythatusesthesamekeyfor
encryptionanddecryption,andtherefore,everyentitysharesthesamekey.
Threat:Thisisacircumstancethatcouldbreachsecurityandcauseharmtothe
system.
Vulnerability:Thisisaweaknessthatallowsforathreattooccur.
Threats,vulnerabilities,andrisks
Therearethreekeytermsthatyouneedtounderstand.Theyweredefinedintheprevious
section,butwewilltalkalittlebitmoreaboutthemsincetheyarecommonlymixedup.
Thesetermsarethreat,risk,andvulnerabilityandtheyarediscussedinthefollowing
sections.
Threat
Athreatisanythingthatmayexploitvulnerabilityinordertoaccess,modify,ordestroy
information.Athreatisthesourceandtypeofanattackandiswhatwetrytodefend
against.Threatassessmentsareusedtodeterminethebestwaytodefendagainsta
determinedclassofthreat.
Whenweconsideracommunicationbetweentwoauthorizedentities,asource(S)anda
destination(D),threatscanbecategorizedintothefollowingfoursegments:
Interception:Thishappenswhenanattackingentityhasanaccesstoa
communicationbetweentwoauthorizedentities.Theentitiesdonotrealizethat
interceptionishappeningandkeeponwiththeircommunicationnormally.
Interruption:Thisreferstowhentheattackingentityinterceptsthecommunication.
Thesourceentitymaynotrealizethisishappening,whilethedestinationentityhas
noknowledgeofthecommunicationattempt.
Modification:Thishappenswhentheattackingentitychangestheinformationsent
betweenthetwoauthorizedentities.Thedestinationentitydoesnotrealizethatthe
informationhasbeentamperedwithbytheattackingentity.
Fabrication:Thishappenswhentheattackingentityactslikethesourceentity.The
destinationentityacknowledgesthecommunicationasifitwasproducedbythe
sourceentity.
Vulnerability
Vulnerabilityisaweaknessoraflawinthesecuritysystemofourapplicationthatmaybe
usedbyadeterminedthreattoaccess,modify,ordestroyinformation.Vulnerability
testingismandatoryandshouldbeperformedrepeatedlytoensurethesecurityofour
application.
Whenahumanorasystemtriestoexploitvulnerability,itisconsideredtobeanattack.
Someofthemostcommonkindsofvulnerabilitiesthatcanbeexploitedtodamageour
systemareasfollows:
Improperauthentication:Thishappenswhenanentityclaimsthatithasbeen
authenticatedandthesoftwaredoesnotcheckwhetherthisistrueorfalse.This
vulnerabilityaffectsoursystemofaccesscontrol,sinceanattackercanevadethe
authenticationprocess.Averycommonexampleofexploitingthisvulnerabilityis
modifyingacookiewhichhasafieldthatdetermineswhethertheuserisloggedin.
Settingloggedintotruecancheatthesystemintobelievingthattheentityisalready
loggedinandisthereforegrantedaccesswhenitshouldnotbegranted.
Bufferoverflow:Thishappenswhenthesoftwarehasaccesstoadeterminedamount
ofmemorybuttriestoreadabufferoutofthelimits.Forexample,ifthesoftwarehas
abufferofsizeNbuttriestoreadthepositionN+2,itwillreadinformationthatmay
beusedbyanotherprocess.Thisgrantsaccessandevenmodifiestheinformationthat
belongstoapartofthememorywherethesoftwareshouldnothaveaccess.
Cross-sitescripting(XSS):Thisisakindofvulnerabilitythatallowsathird-partyto
injectcodeinoursoftware.Itisespeciallycommoninwebsites,butitalsoappliesto
certainmobileapplications.ThemostcommonlyusedexamplesofXSSarethe
accesstocookiesfromadifferentsiteandtheinjectionofJavaScriptintoadifferent
site.
Inputvalidation:Whenreadinginformationprovidedbytheuser,itisalwaysa
goodideatovalidatethedata.Notvalidatingthedatamayresultinanattacker
introducingcertainunexpectedvaluesthatcancauseanissueinthesystem.
SQLinjection:Thisisakindofinputvalidationvulnerability.Itisverycommonto
useasearchfeatureinalmostanyapplication.Thestringthattheuserintroducesin
thesearchfieldisthenintroducedinaSQLsentence.Ifthereisnoanalysisandfilter
ofthestringprovidedbytheuser,anattackercouldwriteaSQLquerythatwouldbe
executed.Ifthisiscombinedwithabadaccesscontrol,theattackercouldevendelete
thewholedatabase.
Risk
Ariskisthepotentialforanattackhappeningandbeingsuccessful.Themoresensitivethe
information,thehighertheriskofattack,asitcancauseahigherlevelofdamagetoour
system.Risksaretheresultofathreatexploitingvulnerabilityandaccessing,modifying,
ordestroyingapieceofinformationthatwewanttobeprotected.Riskassessmentsare
performedtoidentifythemostcriticaldangersandtoevaluatethepotentialdamage.This
potentialdamageiscalculatedthroughastatebetweenthecostofabreachhappening,
whichdependsonhowsensitivetheinformationis,andtheprobabilityofthatevent,
whichdependsonthethreatsandvulnerabilitiesthatmayaffecttheapplication.
Asyoucansee,thereisaveryimportantrelationshipbetweenthesethreeterms;
especiallywhentryingtocorrectlyidentifytheriskthattheinformationstoredsuffers.
Assessingthreatsanddetectingvulnerabilitiesiscrucialtotheprotectionofthe
informationinourapplication.
Securecode-designprinciples
Inordertoreducethenumberofvulnerabilitiesofyourapplication,agoodsecuritydesign
ismandatory.Therearemanystandardsandguidelinesthatrecommenddifferent
processestoproducesecureapplications.Inthissection,wearegoingtoidentifythemost
importantprinciplesthatyoushouldfollowwhendesigningyourapplication:
Securedefaults:Securityisoftheutmostimportanceforanaverageuser.When
designingyourapplication,youshouldmakesurethatthemostdemandinguseris
goingtobesatisfiedand,therefore,yourapplicationshouldofferthebestsecurity
methodsavailable.However,therearesomeuserswhomaypreferaccessibilityover
securityandmaywanttoreducethelevelofsecurity.Forexample,youmaywantto
addpasswordagingtoyourauthenticationsystem.Thismeansthateveryestablished
periodoftime,theusersshouldchangetheirpasswordtoanewone.Thismeansan
additionallevelofsecuritybutcanbeannoyingforcertainusers.Addinganoptionin
thepreferencestoturnoffthisfeaturecanbeagoodidea.However,alwaysmake
suretosetthedefaulttothemoresecuresetting,andlettheuserdecidewhetherthey
wanttoincreasetheriskofbreachingtheirinformation.
Leastprivileges:Privilegesaresometimesconcededinexcessinordertospeedup
theprocessofdevelopment.Thisprinciplestatesthatyoushouldalwaysconcedethe
leastprivilegesaspossibleinordertominimizesecurityrisks.
Clarity:Nevertrustobscuritytoensurethesecurityofyourapplication.Concealing
theinformationonhowyoursecuritysystemworksisagoodidea,butitshouldnot
begrantedasenoughbyitself;thesecuritymustcomefromgoodcryptographic
techniquesandagoodsecuritydesign.
Smallsurfacearea:Ifyouknowyoumayhavevulnerabilityinadeterminedsection
ofyourcode,youcantrytominimizetheriskofathreatexploitingitbyminimizing
theoveralluseofthissection.Forexample,ifyouthinkthatcertainfunctionality
maybeexploited,youcanrestrictthisfunctionalitytoauthenticatedusers.
Strongdefense:Whendefendingagainstacertainattack,theremaybedifferent
methodstouse.Onecontrolcansurelybeenoughbutsensitiveinformationdemands
extraordinarymeasures.Also,usingmorethanonemethodofprecautionismostof
thetimesconvenient.
Failingsecurely:Whendevelopingourapplication,weaimforthehighest
robustness.However,applicationsfailsometimesandweneedtoadaptourcodeto
makesuretheapplicationfailssecurely.WhenprogrammingforAndroid,wecan
addressthisissuebycontrollingeveryexception,forexample,throughthecorrect
usageoftryandcatch.
Nottrustingthethird-partycompanies:Therearemanyservicesavailablethat
havebeendevelopedbythethird-partycompanieswithdifferentprivacyandsecurity
policies.Itisimportanttoknowthatwhileusingoneoftheseservices,youtrustthe
companiesonhowtheyuseyourinformation.Theprincipleofnottrustingthethirdpartycompaniesrecommendsthatyoushouldonlytrustanexternalservicewiththe
minimalamountofinformationpossibleandalwaysimpliesacertainleveloftrust
withthem.
Simplicity:Alwaystrytokeepyoursecuritycodesimple.Althoughitis
recommendedtousecodepatterns,whentalkingaboutsecurity,thesafestandmore
robustwayisitssimplicity.
Addressvulnerabilities:Whenyoudetectvulnerability,itisimportanttoaddress
thisissuecorrectly.Youneedtounderstandboththevulnerabilityandthethreatand
thenactaccordingly.
Testingthebasics
AsstatedbyBorisBeizer,authorofthebookSoftwareTestingTechniques,Dreamtech
Press:
“Bugslurkincornersandcongregateatboundaries.”
Securitytestingcanbedefinedasaprocessthroughwhichwefindvulnerabilitiesorflaws
inoursecuritysystem.Althoughwemaydoexhaustivesecuritytesting,itdoesnotimply
thatnoflawsexist.Inthissection,wewillfocusonthetaxonomyofteststhatcanbe
performedinanycircumstance.
Testscanbecategorizedintotwobiggroups:white-boxtestsorstructuraltestsandblackboxtestsorfunctionaltests.Structuraltesting,morecommonlyknownasthewhite-box
testing,isatestingmethodthatevaluatestheinternalbehaviorofacomponent.Itis
focusedontheanalysisofthebehaviorofeachprocedureindifferentmomentsof
execution.Thewhite-boxtestevaluateshowthesoftwareproducesaresult.Functional
testing,specificationtesting,orblack-boxtesting,aremethodsoftestingthatfocusonthe
functionalityofthecomponentratherthanitsstructure.Whenusingthiskindoftest,the
testerisawarethatacertaininputshouldgenerateaparticularoutput.Thistestevaluates
whatthesoftwareproduces.
Thetwotestcategories,white-boxtestandblack-boxtest,areshowninthefollowing
diagrams:
Therearevariouswhite-boxtechniques.However,themostcommonlyusedarecontrol
flowtesting,dataflowtesting,basispathtesting,andstatementcoverageandtheyare
explainedasfollows:
Controlflowtesting:Thisevaluatestheflowgraphofthesoftwaretoindicate
whetherthesetoftestscoverseverypossibletestcase.
Dataflowtesting:Thisrequiresanevaluationofhowtheprogramvariablesare
used.
Basispathtesting:Thisensuresthateverypossiblepathinacodehasbeenincluded
inthetestcases.
Statementcoverage:Thisconsistsoftheevaluationofthecodeandthedevelopment
ofindividualteststhatwillworkoneveryindividuallineofcode.
Theblack-boxtestingdesignalsoincludesdifferenttechniques.Themostfrequentlyused
techniquesareequivalencepartitioning,boundaryvalueanalysis,cause-effectgraphing,
statetransitiontesting,allpairstesting,andsyntaxtesting,andtheyareexplainedas
follows:
Equivalencepartitioning:Thisdividestestcasesindifferentpartitionsthatpresent
similarcharacteristics.Thistechniquecanhelpinreducingthenumberoftestscases.
Boundaryvalueanalysis:Thisisperformedinordertoanalyzethebehaviorofa
componentwhentheinputisneartheextremevalidvalues.
Cause-effectgraphing:Thisgraphicallyillustratestherelationshipbetween
circumstancesoreventsthatcauseadeterminedeffectonthesystem.
Statetransitiontesting:Thisisperformedthroughanumberofinputsthatmakethe
systemexecutevalidorinvalidstatetransitions.
Allpairstesting:Thisisacombinatorialmethodthattestseverypossible
combinationofparameters.Whenthenumberofparametersandthepossiblevalues
foreachparameterarebig,thistesttechniquecanbecombinedwiththeequivalent
partitioningtechniquetoreducethenumberoftestcases.
Syntaxtesting:Thisanalysesthespecificationsofacomponenttoevaluateits
behaviorwithahugenumberofdifferentinputs.Thisprocessisusuallyautomatized
duetothelargenumberofinputsrequired.
Whentestinganapplication,therearedifferentlevelsoftestingthatdependonthesizeof
thepartofthesysteminvolved.Therearefivecommonlyknownlevelsoftests:unit,
integration,validation,system,andacceptance.
Unittests:Thesetestsfocusoneachindividualcomponent.Thesetestsareusually
performedbythesamedevelopmentteamandconsistofaseriesofteststhatevaluate
thebehaviorofasinglecomponentcheckingforthecorrectnessofthedataandits
integrity.
Integrationtests:Thesetestsareperformedbythedevelopmentteam.Thesetests
assessthecommunicationbetweendifferentcomponents.
Validationtests:Thesetestsareperformedbythefullydevelopedsoftwareinorder
toevaluatethefulfilmentoffunctionalandperformancerequirements.Theycanalso
beusedtoassesshoweasyitistomaintainortoseehowthesoftwaremanages
errors.
Systemtests:Thesetestsinvolvethewholesystem.Oncethesoftwareisvalidated,it
isintegratedinthesystem.
Acceptancetests:Thesetestsareperformedintherealenvironmentwherethe
softwareisused.Theuserperformsthesetestsandacceptsthefinalproduct.
Thehighertheleveloftesting,unittestingbeingthelowestandacceptancetestingthe
highest,themorelikelyitistouseblack-boxtests.Unittestsevaluatecomponentsthatare
smallandthereforeeasytoanalyzeinbehavior.However,thehigherthelevel,thebigger
thesystem,andthereforethemoredifficultandmoreresource-consumingitistoapply
white-boxtestingcategory.Thisdoesnotmeanthatyoushouldnotapplytheblack-box
testingcategorywhileperformingunittests,aseachonecomplementstheother.
Summary
Inthischapter,learnedthebasicandmostcommonlyusedterminologieswhilediscussing
softwaresecurity.Youknowthedifferencebetweenthreat,vulnerability,andrisk,and
understandhoweachoneisrelatedtotheother.Youalsolearnedaboutthedifferentkinds
ofthreatsandvulnerabilitiesthatcanaffectasystem.Younowknowhowtoproperly
approachcodingyoursecuritysystemthankstothesecurecodeprinciples.Finally,you
learnedaboutthedifferentmethodsoftestingthatyoushouldconsiderinordertomake
yourapplicationrobust.Properlyunderstandingthesedefinitionsallowsyoutodesign
bettersecuritysystemsforyoursoftware.
Soasadeveloper,youhavetoaddressthesecurityofyourapplication,butwhatdoes
Androiddoforyou?Androidhasseveralbuilt-insecuritymeasuresthatreducethe
frequencyandthepotentialdamagethatapplicationsecurityissuesmaycause.Inthenext
chapter,youwilllearnaboutthesefeaturesandunderstandhowtheywork.
Chapter2.SecurityinAndroid
Applications
Youunderstandthesecurityconceptsinsoftwareandnowyouwanttodiscoverhowthose
threatsandvulnerabilitiesareappliedtoamobileenvironment.Youwanttobeawareof
thespecialsecurityfeaturesintheAndroidoperatingsystem.Youarealreadyfamiliar
withAndroid,butyouneedtoknowthecomponentsthatarecriticalforitssecurity.
Thischapterwillshowyouthechallengesthatexistinthemobileenvironment.Youwill
learnabouttheAndroidsecurityarchitectureandaboutwhatapplicationsandboxing
means.ThischapterwillshowyouthemainfeaturesinAndroidthatwillallowyou
protectyourlocation:permissionsandinterprocesscommunication.
Wewillbecoveringthefollowingtopicsinthischapter:
Vulnerabilitiesinthemobileenvironment
Androidsecurityoverview
Permissions
Interapplicationcommunication
Themobileenvironment
Androidisanoperatingsystem(OS)createdforintelligentmobiledeviceswitha
touchscreen,suchassmartphonesortablets.Knowingthefeaturesofadeviceisimportant
toidentifythevulnerabilitiesthatcanpotentiallycompromisetheintegrity,confidentiality,
oravailabilityofyourapplication(app).
Asmartphoneisaconnecteddeviceandsomalicioussoftwarecaninfectitinseveral
ways.Thesmartphonecancommunicatewithdifferentdevicesbyawirelessorwired
connection.Forexample,itcanconnecttoacomputerbyacableoritcanconnectto
anothermobiledevicebyawirelessBluetoothnetwork.Thesecommunicationsallowthe
usertotransferdata,files,orsoftware,whichisapossiblepathtoinfectthesmartphone
withmalware.
AsmartphoneisalsoaconnecteddeviceinthesensethatitcanconnecttotheInternetby
cellularnetworkslike3GoraccesspointsviaWi-Fi.Internetisthereforeanotherpathof
potentialthreatstothesecurityofsmartphones.
Smartphonesalsohaveinternalvulnerabilities,forexample,maliciousappsthatare
installedbytheuserthemselves.Thesemaliciousappscancollectthesmartphone’sdata
withouttheuser’sknowledge.Sensitivedatamightbeexposedbecauseofimplementation
errorsorbecauseoferrorsthatoccurwhilesendingdatatothewrongreceiver.
Communicationbetweentheappsinstalledinthesmartphonecanbecomeawaytoattack
them.
Thefollowingfigurerepresentsthetypesofexistingvulnerabilitiesinsmartphones.The
connectiontothenetworkisoneoftheexternalvulnerabilities,sincenetworkconnections
aresusceptibletosniffingorspoofingattacks.Theconnectionstoexternaldevicesalso
involvepotentialvulnerabilitiesasmentionedearlier.Regardinginternalvulnerabilities,
implementationerrorscancausefailuresandattackerscantakeadvantageofthem.
Finally,userunawarenessisalsoavulnerabilitythataffectstheinternalsofthe
smartphone.Forexample,installingappsfromuntrustedsourcesorsettinganimprudent
configurationforWi-FiorBluetoothservicesisarisk.
Asadeveloper,youcannotcontroltherisksassociatedwithexternaldevicesorthe
network,noteventhoserelatedtouserunawareness.Therefore,yourresponsibilityisto
createrobustappswithoutimplementationerrorsthatcancausesecuritybreaches.
AnoverviewofAndroidsecurity
Androidprovidesasecurearchitecturetoprotectthesystemanditsapplications.Android
architectureisstructuredlikeasoftwarestackinwhicheachcomponentofalayeraccepts
thatthelayerfollowingitissecure.Thefollowingfigureshowsasimplifiedversionofthe
Androidsecurityarchitecture:
AndroidOSisamultiuser,Linux-basedplatforminwhicheachapphasadifferentuser.
EachapphasitsownuserID(UID)intheLinuxkernelthatisunique.TheUIDis
assignedbythesystemandisunknowntotheapp.BecauseoftheuniqueUID,Android
appsruninseparateprocesseswithdifferentpermissions.Thismechanismisknownas
applicationsandboxing.TheAndroidApplicationSandboxisolateseachapplication’s
dataandcodeexecutiontoimproveitssecurityandpreventmalware.Thismeansthat
undernormalcircumstances,youcannothaveaccesstootherapplication’sdataandother
applicationsdonothaveaccesstoyourapplication’sdata.AstheApplicationSandboxis
implementedintheLinuxkernel,thesecurityprovidedbythismechanismisextendedto
allthelayersabovethekernel(suchaslibraries,Androidruntime,applicationframework,
andapplicationruntime).Forexample,ifamemorycorruptionerrorisgenerated,this
errorwillonlyhaveconsequencesfortheapplicationinwhichtheerrorwasproduced.
ApplicationsandboxingisoneofthemainsecurityfeaturesofAndroid,butwecanalso
findthefollowingfeaturesinthesecuritymodel:
Application-definedpermissions:Ifapplicationsareisolatedfromeachother,how
cantheyshareinformationwhenrequired?Applicationscandefinepermissionsto
allowotherapplicationstocontrolitsdata.Therearealsomanypredefinedsystembasedpermissionscovermanysituationsandthatwillreducethenecessityof
creatingpermissions,especiallyforyourapplication.
Interprocesscommunication:Undernormalcircumstances,everycomponentofan
applicationrunsinthesameprocess.However,therearetimeswhendevelopers
decidetoruncertaincomponentsindifferentprocesses.Androidprovidesan
interprocesscommunicationmethodthatissecureandrobust.
Supportforsecurenetworking:Networktransactionsareespeciallyriskyon
mobiledevicesthatcommonlyuseunsecuredWi-Finetworksinpublicspaces.
Androidsupportsthemostcommonlyusedprotocolstosecureconnectionsunder
theseextremeconditions.
Supportforcryptography:Androidprovidesaframeworkthatdeveloperscanuse
withtestedandrobustimplementationsofcommonlyusedcryptographicmethods.
Encryptedfilesystem:Androidprovidesafullfilesystemencryption.Thismeans
thattheinformationstoredonanAndroiddeviceisencryptedandistherefore
protectedatanytimeagainstexternalentities.Thisoptionisnotactivebydefaultand
requiresausernameandapassword.
Applicationsigning:Theinstallationpackageofeveryappmustbesignedwitha
certificate,whichcanbeaself-signedcertificate.Anattackercanpreservetheir
anonymity,sinceit’snotnecessaryforatrustedthird-partytosignthecertificate.
Certificatesaremainlyusedtodistinguishdevelopersandallowthesystemto
managepermissions.Topreventanattackerfrommodifyingyourapplication,you
shouldkeepyourcertificatesafe.Furthermore,applicationupdatesmustbesigned
withthissamecertificate.
Permissions
Withapplicationsandboxing,appscannotaccesspartsofthesystemwithoutpermission,
butevenwithit,Androidallowsdatasharingwithotherappsoraccesstosomesystem
services.Anappneedstorequestpermissiontoaccessdevicedataortoaccesssystem
services.PermissionsareasecurityfeatureofAndroidsystem,butmisusedpermissions
makeyourapplicationvulnerable.
Thepermissionneedsofanapparedeclaredinitsmanifestfile.Thismanifestfileis
bundledintotheapp’sAndroidapplicationpackage(APK),whichincludesitscompiled
codealongwithotherresources.Thepermissionsrequestedinthemanifestfile(manifest
permissions)willbeshowntotheuserwheninstallingtheapp.Theusershouldreview
thesepermissionsandacceptthemtocompletetheinstallationprocess.Iftheuseragrees
tothem,theprotectedresourcesareavailabletotheapp.
Tip
Donotrequestpermissionsthatyourappdoesnotneed.Reducingthenumberof
permissionsmakesyourapplessvulnerable.
PermissionscontrolhowanappinteractswiththesystembyusinganAndroid
applicationprogramminginterface(API).SomeoftheprotectedAPIsthatneed
permissionincludethefollowing:
Bluetooth
Camera
LocationGPS
Networkanddataconnections
NFC
SMSandMMS
Telephony
Forexample,torequestpermissiontousethecamera,youhavetoaddthefollowingline
codeinourmanifestfile:
<uses-permissionandroid:name="android.permission.CAMERA"/>
ThefollowingcodeisusedtorequestpermissiontoaccesstheInternet:
<uses-permissionandroid:name="android.permission.INTERNET"/>
ThefollowingcodeisusedtorequestpermissiontosendaSMS:
<uses-permissionandroid:name="android.permission.SEND_SMS"/>
Interapplicationcommunication
AppsinAndroidcannotaccesseachother’sdatadirectlybecauseofapplication
sandboxing,butAndroid’ssystemprovidessomeothermechanismsfortheapplicationsto
communicatewitheachother.Intentsandcontentprovidersaremechanismsthatwecan
useontheJavaAPIlayer.Intentsandcontentprovidersshouldbeusedcarefullyto
preventattacksfrommalwareapplications.Thisisthereasonwhyitisimportantto
understandtheircharacteristics.
Intents
Intentsareanasynchronousinterprocesscommunicationmechanism.Intentisamessage
thatincludesthereceiverandoptionalargumentstopassthedata.ThereceiverofIntent
canbedeclaredexplicitlysothattheIntentissenttoaparticularcomponent,oritcanbe
declaredimplicitlysothattheIntentissenttoanycomponentthatcanhandleit.Intents
areusedforintra-applicationcommunication(inthesameapplication),orfor
interapplicationcommunication(indifferentapplications).Thefollowingcomponentscan
receiveIntents:
Activities:Anactivityrepresentsascreenintheapp.Intentscanstartactivities,and
theseactivitiescanreturndatatotheinvokingcomponent.Tostartanactivityusing
Intent,youcancallthestartActivitymethodorthestartActivityForResult
methodtoreceivearesultfromtheactivity.
Services:Aserviceperformslong-runningbackgroundtaskswithoutinteractingwith
theuser.TostartaserviceusingIntent,youcancallthestartServicemethodorthe
bindServicemethodtobindothercomponentstoit.
Broadcastreceivers:Intentscanbesenttomultiplereceiversthroughbroadcast
receivers.WhenareceiverisstartedbecauseofIntent,itrunsinthebackgroundand
oftendeliversthemessagetoanactivityoraservice.Somesystemeventsgenerate
broadcastmessagestonotifyyou,forexample,whenthedevicestartschargingor
whenthedevice’sbatterylevelislow.TosendabroadcastmessageusingIntent,you
cancallthesendBroadcastmethod.Tosendanorderedbroadcast,youcancallthe
sendOrderedBroadcastmethod.Tosendastickybroadcast,youcancallthe
sendStickyBroadcastmethod.Therearethreetypesofbroadcastmessages:
Normalbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoallthe
receiversatthesametime.Soonafter,themessageisnolongeravailable.
Orderedbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoone
receiveratatimedependingonitsprioritylevel.Anyreceivercanstopthe
propagationofthemessagetotherestofthereceivers.Soonafter,themessage
isnolongeravailable.
Stickybroadcast:Inthistypeofbroadcast,themessageissentbutitdoesnot
disappear.Anexampleofastickybroadcastisthebatterylevel.Anappcanfind
outwhichwasthelastbatterylevelbroadcastbecauseitremainsaccessible.
ApplicationcommunicationbyIntentsallowsthereceiverandoptionalargumentstoreuse
eachother’sfeatures.Forexample,ifyouwanttoshowawebpageinyourapp,youcan
createIntenttostartanyactivitythatisabletohandleit.Youdonotneedtoimplementthe
functionalitytodisplayawebpageinourapp.Thefollowingcodeshowsyouhowto
createIntenttodisplaywebpagecontent:
Intenti=newIntent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.packtpub.com"));
startActivity(i);
Tip
Downloadingtheexamplecode
YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfrom
youraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcan
visithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlyto
you.
TheprecedingcodeisanexampleofanimplicitIntentinwhichageneralactionis
indicated:Intent.ACTION_VIEW.TheAndroidsystemsearchesforalltheappsthatmatch
theIntent.IfthereismorethanoneapplicationthatmatchestheIntentandtheuserhasnot
setadefaultone,adialogisdisplayedsothattheusercanchoosewhichoneofthemto
use.
IntentsthataresupportedbyacomponentaredeclaredinthemanifestfileusingtheIntent
filters.Thebroadcastreceiverscanbealsobedeclaredatruntime.Intentfilterdeclaresthe
typesofIntentsthatacomponentcanrespondto.WhenacomponentincludesanIntent
filter,thecomponentisexportedsoitcanreceiveIntentsfromothercomponents.Intent
filtercanconstrictbytheactionoftheIntent,bythetypeofdata,orbythecategoryofthe
Intent.Forexample,ifyouwantyourapptobehaveasabrowser,youhavetocreatean
activitywiththefollowingIntentfiltersinyourmanifestfile:
<activity…>
<intent-filter>
<actionandroid:name="android.intent.action.VIEW"/>
<dataandroid:scheme="http"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<categoryandroid:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
Thefollowingexampleshowsyouhowtoregisterareceivertorunwhenthedevicestarts
charging:
<receiver…>
<intent-filter>
<actionandroid:name="android.intent.action.ACTION_POWER_CONNECTED"/>
</intent-filter>
</receiver>
Note
IfyouwanttolearnmoreaboutIntents,youmightwanttocheckouttheofficial
documentation:http://developer.android.com/guide/components/intents-filters.html.
Contentproviders
Contentprovidersareamechanismthatallowssharingbetweenapplicationsandservesas
persistentinternaldatastoragefacility.Thedatastoredthroughacontentprovideris
structuredandtheinterfaceisdesignedtobeusedwithaStructuralQueryLanguage
(SQL)backend.AlthoughitiscommontouseaSQLdatabasebehindcontentproviders,
filestorageorRESTcallscanalsobeused.Ifyouarenotfamiliarwithcontentproviders,
youmightwanttocheckouttheofficialdocumentationsinceitisabroadtopic:
http://developer.android.com/guide/topics/providers/content-providers.html.Ourinterest
incontentprovidersisrelatedtotheirsecurityandpermissions.Contentprovidersarethe
perfectscenarioforSQLinjectionattacks.
Toaccessthedataofcontentproviders,therearecontentresolversthatyoucanusein
yourapp.Theprovider’sdataisidentifiedbyacontentURI.Toaccessthecontent
provider,youshouldusethegetContentResolver().query()method,whichreceivesthe
followingparameters:
ContentURI:ThisistheURIthatidentifiesthedata(theFROMclauseinSQL)
Projection:Thisspecifiesthecolumnstoretrieveforeachrow(theSELECTclausein
SQL)
Selection:Thisisthecriteriatoselecttherows(theWHEREclauseinSQL)
Selectionarguments:Thiscomplementsthecriteriatoselecttherows
Sortorder:Thisisthesortorderfortherows(theORDERBYclauseinSQL)
TherearesomecontentprovidersofferedbytheAndroidsystemitself,suchasthe
calendarproviderandthecontactsprovider.Toaccessthesystemcontentproviders,you
needtorequestthepermissioninyourmanifestfile.Forexample,tobeabletoreadthe
contacts,youmustaddthefollowingpermissiontoyourapp:
<uses-permissionandroid:name="android.permission.READ_CONTACTS"/>
Toacquirethewritingaccesspermissions,youmustaddthefollowinglineofcodeinyour
manifest:
<uses-permissionandroid:name="android.permission.WRITE_CONTACTS"/>
Anyothercontentprovider,notonlythoseofthesystem,canindicatetherequired
permissionsthatotherappsmustrequestsothattheycanaccesstheprovider’sdata.
Summary
Inthischapter,youlearnedaboutthevulnerabilitiesassociatedwithmobiledevices—both
externalandinternal.YounowunderstandtheAndroidarchitectureandthefeatures
providedbythesystemtokeepitsafe.YounowknowwhichcomponentsoftheJavaAPI
layerarevulnerabletoattacks,soyoucanlearnhowtomitigatetheminthenextchapters
ofthisbook.
Inthenextchapter,wewillstartusingAndroidStudioIDE.Asthefirststeptocreate
secureAndroidapplications,youwilllearnhowtomonitorAndroidapplicationsinthe
debuggingenvironmentinordertodetectincorrectbehaviors.
Chapter3.MonitoringYourApplication
Youarenowawareoftheimportanceoflearninghowtomonitortheactivityofyour
Androidapplicationandarealsofamiliarwiththebasicconsoleorlogsthatyouuseto
debugyourapplication.However,thereismoretolearnaboutthedebuggingtool
availableinAndroidStudio.AndroidStudioincludestheDalvikDebugMonitorServer
(DDMS)debuggingtool.Doyouwanttousethisdebuggingtoolwhileprogrammingin
AndroidStudio?
Thischapterpresentsthedebuggingenvironment,oneofthemostimportantfeaturesofan
IDE.MonitoringyourAndroidapplicationallowsyoutodetecttheincorrectbehaviors
andsecurityvulnerabilities.Inthischapter,youwilllearnabouttheinformationavailable
intheadvanceddebuggingtoolincludedinAndroidStudio:DDMS.
Thetopicsthatwillbecoveredinthischapterareasfollows:
DebuggingandDDMS
Threadandmethodprofiling
Heapusageandmemoryallocation
Networkstatistics
Fileexplorer
Emulatorcontrolandsysteminformation
DebuggingandDDMS
InAndroidStudio,youcanusedifferentmechanismstodebugyourapplication.Oneof
themisthedebugger.Thedebuggermanagesthebreakpoints,controlstheexecutionof
thecode,anddisplaysinformationaboutthevariables.Todebuganapplication,navigate
toRun|Debug‘MyApplication’orclickonthebugiconpresentinthetoolbar.
AnothermechanismistheConsole.TheConsoledisplaystheeventsthataretakingplace
whiletheapplicationisbeinglaunched.Actionssuchasuploadingtheapplication
package,installingtheapplicationinthedevice,orlaunchingtheapplicationaredisplayed
intheConsole.
LogCatisanotherusefultooltodebugyourapplication.ItisanAndroidloggingsystem
thatdisplaysallthelogmessagesgeneratedbythesystemintherunningdevice.Log
messageshaveseverallevelsofsignificance:verbose,debug,information,warning,and
error.
Finally,youalsohaveDDMS,anexcellentdebuggingtoolavailableintheSDKthatis
availabledirectlyinAndroidStudio.Thistoolisthemaintopicofthischapter.
ToopentheDDMStoolinAndroidStudio,navigatetoTools|Android|Monitor
(DDMSincluded).Alternatively,youcanclickontheAndroidiconpresentinthetoolbar,
whichwillopenawindowwiththeDDMSperspective.
Oncetheperspectiveisopen,asshowninthefollowingscreenshot,youcanseethelistof
connecteddevicestotheleft-handsideofthescreen,alongwithalistoftheprocesses
runningoneachdevice.Ontheright-handsideofthescreen,youcanseethedetailed
informationoftheprocess.Thisinformationisdividedintoseventabs:Threads,Heap,
AllocationTracker,NetworkStatistics,FileExplorer,EmulatorControl,andSystem
Information.LogCatandConsoleareaccessibleatthebottomofthewindow.
Threads
TheThreadstabdisplaysthelistofthreadsthatareapartoftheselectedprocess.
Applicationshaveonemainthread,alsocalledastheUIthread,whichdispatchesthe
eventstotheuserinterface(UI)widgets.Toperformlongoperations,itisnecessaryto
createnewthreadssothatthemainthreadisnotblocked.Ifthemainthreadgetsblocked,
thewholeUIwillalsogetblocked.
Toillustratetheworkingofthistool,runthefollowingexample.InAndroidStudio,create
anewbasicprojectwithamainlayoutandamainactivity.Addabuttontothemain
layoutnamed,forexample,StartNewThread.Createanewmethodtobeexecutedwhen
thebuttonisclickedandaddthefollowingcodeinthemethod:
publicvoidstartNewThread(Viewv){
newThread(newRunnable(){
publicvoidrun(){
Thread.currentThread().setName("MyexampleThread");
try{
Thread.sleep(30000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}).start();
}
Theprecedingmethodcreatesanewthreadintheapplication,althoughitdoesnothing
andcontainsonlyasleepinstruction.Youcansetthethreadanametorecognizeiteasily.
RuntheapplicationandopentheDDMSperspective.
SelectyourapplicationprocessfromtheDevicessectionandclickontheUpdateThreads
iconpresentonthetoolbaroftheDevicessectionandthethreadswillbeloadedinthe
contentofthetab.TheStatuscolumnindicatesthethreadstate,utimeindicatesthetotal
timespentbythethreadexecutingusercode,stimeindicatesthetotaltimespentbythe
threadexecutingsystemcode,andNameindicatesthenameofthethread.Youcan
identifythemainthreadintheresultlistwiththeIDnumber1,asshowninthefollowing
screenshot:
ClickontheStartNewThreadbuttonofyourapplicationandnoticethatanewthread
appearsinthelistascanbeobservedinthefollowingscreenshot,MyexampleThread:
Thethreadisactiveforaperiodof30seconds.EverytimeyouclickontheStartNew
Threadbutton,anewthreadiscreated.
Thistoolisespeciallyusefulwhilecreatingthreadsinourapplicationapartfromthemain
thread.Thankstothistool,wecaneasilycheckwhetherourthreadsarebeingexecutedat
acertainpointoftheexecutionorwhethertheyareperformingasexpectedinmemory
usage.
Methodprofiling
Themethodprofilingtoolisusedtomeasuretheperformanceofthemethodsofa
selectedprocess.Withthistool,youcanaccessthenumberofcallsofamethodandthe
CPUtimespentontheirexecution.Therearetwotypesofvaluesavailable,theexclusive
timeandtheinclusivetime:
Exclusivetime:Thisreferstothetimespentintheexecutionofthemethoditself.
Inclusivetime:Thisreferstothetotaltimespentintheexecutionofthemethod,
whichincludesboththetimespentbythemethodaswellasthetimespentbyany
othermethodcalledinsidethemethod.
Toillustratetheworkingofthistool,wearegoingtorunthefollowingexample.Createa
newbasicprojectwithamainlayoutandamainactivityinAndroidStudio.Youcanalso
reusetheprojectcreatedintheprevioussection.Addabuttontothemainlayout,for
example,StartMethodHierarchy.Createanewmethodthatistobeexecutedwhenthe
buttonisclickedandaddthefollowingcodeinthemethod:
publicvoidstartMethodHierarchy(Viewv){
secondMethod();
}
Addthesecondandthethirdmethodinyouractivity,shownasfollows:
privatevoidsecondMethod(){
thirdMethod();
}
privatevoidthirdMethod(){
try{
Thread.sleep(30000);
}catch(InterruptedExceptione){e.printStackTrace();}
}
Asseeninthepreviouscode,youcreateahierarchyofmethodcallsthatyouwillbeable
toobserveinthemethodprofiling.Totakealookatyourmethodprofilingdata,select
yourapplicationprocessinthedevicessectionandclickontheStartMethodProfiling
iconpresentonthetoolbaroftheDevicessection.ClickontheStartMethodHierarchy
buttonofyourapplicationandwaitforaperiodofatleast30secondssothatthethird
methodfinishesitsexecution.Oncethethirdmethodfinishesitsexecution,youcanstop
themethodprofilingbyclickingontheStopMethodProfilingicon.
Whenyoustopthemethodprofiling,anewtabwiththeresultanttracewillappearwithin
theDDMSperspective.Thetopofthisnewtabrepresentsthemethodcallsinatimegraph
whereeachrowbelongstoeachthreadoftheapplication.Thebottomofthetrace
representsthesummaryofthetimespentonamethodinatable.
Tosearchforyourapplicationpackageandmainactivity,clickontheNamelabeltoorder
themethodsbytheirname,forexample,
com/example/myapplication/app/MainActivity.Thethreemethods
(startMethodHierarchy,secondMethod,andthirdMethod)shouldappearinthelistasis
showninthefollowingscreenshot:
OnexpandingthedetailedinformationofthesecondMethod,youcanseethattheparentis
thestartMethodHierarchymethodandthatthethirdMethodmethodisitschild.This
informationispresentedinthefollowingscreenshot:
Also,examinetheexclusiveandinclusiverealtimes.Theprecedingscreenshotreveals
thattheinclusiverealtimeforthirdMethodwas30001,138ms,becauseofthesleep
clauseof30seconds.ThetimespentintheexecutionofthesecondMethoditselfis0,053
ms(exclusiverealtime),butsincetheinclusivetimeincludesthetimespentbythe
childrenmethods,itsinclusiverealtimewas30001,191ms.
Methodprofilingcanbeusedtodetectmethodsthatarespendingmoretimethan
anticipatedintheirexecution.Withthisinformation,youcanlearnwhichmethodsare
causingproblemsandneedtobeoptimized.Youcanalsolearnwhichmethodsaremore
time-consumingsothatyoucanavoidunnecessarycallstothem.
Heap
TheHeaptabstoresallnewobjectscreatedintheapplication.Thegarbagecollector
(GC)deletestheobjectsthatarenotreferredanymore,releasingunusedmemory.The
Heaptabdisplaystheheapusageforaselectedprocess.
Toillustratetheworkingofthistool,runthefollowingexample.Createanewbasic
projectwithamainlayoutandamainactivityinAndroidStudio.Addabuttontothemain
layout,forexample,StartMemoryConsumption.Createanewmethodtobeexecuted
whenthebuttonisclickedandaddthefollowingcodetothemethod:
publicvoidmemoryConsumption(Viewv){
list=newArrayList<Button>();
for(inti=0;i<=1000;i++){
list.add(newButton(this));
}
}
Finally,addthedeclarationofthelistasaglobalvariableintheactivity.Thisway,youare
preventingtheGCtoreleasethememorythatstoresthelistafterthemethodfinishesits
execution.Thedeclarationofthelistasaglobalvariableintheactivityisshownas
follows:
privateList<Button>list;
Inthismethod,youarecreatingalargenumberofnewobjects,forexample,alist
containing1000buttons.Usingthismethod,youaregoingtoexaminehowthecreationof
thelistisreflectedintheheap.RuntheapplicationandopentheDDMSperspective.
SelecttheapplicationprocessintheDevicestabandclickontheUpdateHeapicon
presentonthetoolbartoenableit.TheheapinformationisshownafteraGCexecution.
SelecttheHeaptabandclickontheCauseGCbutton,andyou’llseetheheapusage.
Thefirsttableofthetabdisplaysasummary:thetotalsize,theallocatedspace,thefree
space,andthenumberofallocatedobjects.Thestatisticstablepresentsthedetailsofthe
objectsthatareallocatedontheheapbyitstype:numberofobjects,totalsizeofthe
objects,sizeofthesmallestandlargestobjects,mediansize,andaveragesize.Wecan
selecteachtypeindividually.Thisactionwillloadthebottombargraphwiththenumber
ofobjectsofthattypeorderedbyitssizeinbytes.Wecanthenclickonthegraphusing
therightbuttonofthemousetochangeitsproperties:title,colors,font,labels,andsoon.
WecanalsosaveitasaPNGimage.
Observethenumberofdataobjectsallocatedontheheapasshowninthefollowing
screenshot:
ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMS
perspective,causemoreGCexecutionsandnotehowthenumberofobjectsincreases
whilethemethodisbeingexecuted.Thefollowingscreenshotshowstheheapinformation
whenthemethodhasalreadyfinisheditsexecution.Theallocateddataobjectshavegrown
from24.822to60.821.
Finally,youcanalsotrytochangethedeclarationofthelistsothatitbecomesalocal
variableinthememoryConsumptionmethod.Repeatthepreviousprocessandnotethatthe
newdataobjectsarereleasedbytheGConcetheexecutionofthemethodisfinished.
AllocationTracker
TheAllocationTrackertabdisplaysthememoryallocationsoftheselectedprocess.The
allocationtracker,unliketheheaptool,showsthespecificobjectsbeingallocatedalong
withthethread,themethod,andthelinecodethatallocatedthem.
Youcanagainrunthepreviousexamplecreatedfortheheapmonitortoshowtheresults
oftheallocationtracker.SelecttheapplicationprocessandintheAllocationTrackertab
andclickontheStartTrackingbuttontostarttrackingthememoryinformation.Now,
clickontheGetAllocationsbutton.Thiswillgetthelistofallocatedobjects,which
includesafilteronthetopofthetabthatyoucanusetofiltertheobjectsallocatedinyour
ownclasses.
ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMS
perspective,againclickontheGetAllocationsbuttonandobservethenewobjectsthat
arelistedintheresults.TheobjectsarethebuttonscreatedinthememoryConsumption
method.
Theresultstablepresentstheallocationsize,thethread,theobjectorclass,andthe
methodinwhicheachobjectwasallocated.ClickonanyoftheButtonobjectstosee
moreinformationasshownthefollowingscreenshot.
YoucannoticethattheButtonobjectisallocatedinthemainactivityinthe
memoryConsumptionmethod,andthelineofcodethatallocateditisthelinenumber26.
Wheneveryouneedtoexaminetheobjectsallocatedintheheap,youcanusethe
allocationtracker.Youcananalyzetheinteractionsinyourapplicationandimprovethe
memoryusage.
ThefollowingscreenshotshowsthedetailsoftheButtonobjects:
NetworkStatistics
TheNetworkStatisticstabdisplaysthenetworkresourcesusedbyourapplication.Let’s
createasimpleexampletotestthistool.Createanewprojectandaddthefollowing
permissionsinyourmanifestfile:
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
Inthemainlayout,addabuttonnamed,forexample,StartNetworkConnection.Create
anewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcode:
publicvoidstartNetworkConnection(Viewv){
newThread(newRunnable(){
publicvoidrun(){
try{
//Smallimage
TrafficStats.setThreadStatsTag(0x0001);
downloadURL("http://goo.gl/iGoYng");
TrafficStats.clearThreadStatsTag();
Thread.sleep(5000);
//Mediumimage
TrafficStats.setThreadStatsTag(0x0002);
downloadURL("http://goo.gl/eQHDRh");
TrafficStats.clearThreadStatsTag();
Thread.sleep(5000);
//Largeimage
TrafficStats.setThreadStatsTag(0x0003);
downloadURL("http://goo.gl/tUDnRv");
TrafficStats.clearThreadStatsTag();
}catch(IOExceptione){
e.printStackTrace();
}catch(InterruptedExceptionie){ie.printStackTrace();}
}
}).start();
}
Usingtheprecedingexample,youaredownloadingthreeimagesofdifferentsizes:small,
medium,andlarge.Consideringthatconnectingtothenetworkisalongoperation,we
needtoexecutethecodeinanewthread.UsinganAsyncTaskclassisabettersolution,
butinsteadtheThreadclassisusedtokeepthecodecleaner.Afterdownloadinganimage
andbeforedownloadingthenextone,youwillhavetowaitforaperiodof5secondsso
thattheresultsdisplayedlaterarenotconfusing.Finally,toclearlyseparatethedifferent
downloads,weestablishadifferenttagforeachdownloadusingthesetThreadStatsTag
andclearThreadStatsTagmethodsoftheTrafficStatsclass.TheTrafficStatsclass
providesnetworktrafficstatisticssuchasthenumberofbytesorpackagesreceivedand
transmitted.
Todownloadanimage,youhavetoaddthefollowingmethodinyouractivity:
privateBitmapdownloadURL(Stringimage)throwsIOException{
InputStreamis=null;
try{
URLurl=newURL(image);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
intresponse=conn.getResponseCode();
is=conn.getInputStream();
//ConverttheInputStreamintoabitmap
returnBitmapFactory.decodeStream(is);}finally{
if(is!=null){
is.close();
}
}
}
Inordertohavesimplecode,thepreviousmethoddoesnotexecuteanyadditionalactions
ontheimages.Theimagesareonlydownloaded.
RuntheapplicationandopentheDDMSperspective.Togetthenetworkstatisticsofyour
application,clickontheStartbuttonintheNetworktab.Then,clickontheStart
NetworkConnectionbuttonoftheapplicationtostartdownloadingtheimages.Thedata
transferswillappearinthegraphaspacketsaresentorreceived.Thefollowingscreenshot
showstheresultsofthenetworkstatistics:
Inthepreviousscreenshot,thedownloadofthethreeimagescanbeeasilyidentified.The
columnsRXbytesandRXpacketsrepresentthetotalnumberofbytesandpackets
received.ThecolumnsTXbytesandTXpacketsrepresentthetotalnumberofbytesand
packetstransmitted.Wecanusethenetworkstatisticstooltooptimizethenetwork
requestsinourapplicationandcontrolthepacketsthatarebeingtransferredatacertain
pointoftheexecution.
FileExplorer
TheFileExplorertabexposesthewholefilesystemofthedevice.Wecanexaminethe
size,date,orpermissionsforeachelement.Navigateto/data/app/yourpackagetosearch
foryourapplication.apkpackagefile.Tocheckthepathinwhichyourfilesaresaved
whentheyarecreatedoninternalstorage,youcanusethegetFilesDir()methodinyour
activity.Thefilesrelatedtoyourapplicationareusuallylocatedat
/data/data/yourpackage.Let’sperformanexample.
Createanewprojectandinthemainlayoutaddabuttonnamed,forexample,CreateNew
File.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthe
followingcode:
publicvoidcreateNewFile(Viewv){
Stringstring="Helloworld!";
FileOutputStreamoutputStream;
try{
outputStream=openFileOutput("MyFile",MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
}catch(Exceptione){e.printStackTrace();}
}
Usingthepreviouscode,youarecreatinganewtextfileontheinternalstorageofour
application.RuntheapplicationandopentheFileExplorertaboftheDDMSperspective.
Navigateto/data/data/yourpackage/files,whichisempty.ClickontheCreateNew
Filebuttonofyourapplicationandcheckthatthenewfilehasbeencreatedat
/data/data/yourpackage/files,asshowninthefollowingscreenshot:
EmulatorControl
TheEmulatorControltabmakesitpossibletochangestatesoractivitiesinthevirtual
device.Withthisemulator,youcantestyourapplicationinenvironmentsandsituations
thatwouldotherwisebeimpossibleortime-consumingtoachieve.Thisallowsyouto
checkwhetheritisbehavingasexpectedunderthefollowingspecialconditions:
TelephonyStatus:Youcanchoosethevoiceanddatastatus,changingitsspeedand
latency
TelephonyActions:Youcansimulateanincomingcalls,MMS,orSMS
LocationControls:Youcanchangethegeolocationofthedevice
SystemInformation
IntheSystemInformationtab,youcanaccessFrameRenderTime,CPUload,and
Memoryusageofthedeviceintheformofgraphs.Youcanselectyourapplication
individuallyandcompareitwiththerestofapplicationsthatarerunningonthedevice.
Ifyouclickonthegraphwiththerightbuttonofthemouse,youwillseeapopupwiththe
graphpropertiessuchascolors,font,andtitle.Thegraphcanbecustomizedhereandcan
alsobesavedasaPNGimage.
Summary
Aftergoingthroughthischapter,youknowhowtodebuganapplication.Youcreated
severalexamplesinthischaptersoyouknowhowtointerpretthedataprovidedbythe
DDMSineachofthetabsavailable.Younowunderstandbetterhowthreads,method
calls,memoryallocation,andnetworkusageworkinAndroidapplications.
Inthenextchapter,youwillapplyallthatyouhavelearnedfromthisandtheprevious
chapter.YouwilllearnhowtoidentifyandmitigatethevulnerabilitiesinAndroid
applications,andyouwillbeabletocreatesecureapplicationsbyfollowingthe
recommendationsincludedinthenextchapter.
Chapter4.MitigatingVulnerabilities
InChapter1,IntroductiontoSoftwareSecurity,wealreadydiscussedthemostimportant
vulnerabilitiesthatcanbeexploitedinordertocompromiseyourapplication.Now,you
needtolearnwhatmeasuresyoucantakeinordertoaddressthesevulnerabilitiesand
makeyourapplicationmoresecure.Whateasystepscanbetakeninordertoachievethis?
Thischapterwillshowyouhowtomitigatevulnerabilities.Removingoratleasttreating
vulnerabilitieswillsignificantlyreducetherisksofyoursystem.We’llbeginbylearning
howtovalidateinputfields.We’llalsolearnhowtoavoidcodeinjection,especiallythe
mostcommonone:SQLinjection.We’llthenseerecommendedpracticeswhenhandling
usercredentialsandwewilllearnhowtomakeourcomponentsmoresecureinorderto
avoidvulnerabilitiesintheinterapplicationcommunications.
Thetopicsthatwillbecoveredinthischapterareasfollows:
Inputvalidation
Permissions
Handlingusers’dataandcredentials
Interapplicationcommunication
Inputvalidation
AccordingtotheAndroiddevelopmentguidelines,thelackofsufficientinputvalidation
measuresisoneofthemostcommonsecurityproblemsinAndroidapplications.Thereare
severalproblemsthatcanbederivedfrominsufficientinputvalidationsuchasbuffer
overflows,nullpointers,off-by-oneerrors,inconsistenciesinthedatabase,andevencode
injectionproblems.
Now,wewillseesometipsthatwillhelpustomitigatethisvulnerability.
WecanusetheinputTypeattributeinordertolimitthepossiblecharacterstheusercan
setinafield.Forexample,ifwehaveanEditTextfieldwherewewantatelephone
number,wecandefinetheEditTextasfollowsinyourlayoutfile:
<EditText
android:id="@+id/EditTextTelephone"
android:hint="@string/telephone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone">
</EditText>
Althoughthisshouldnotbeconsideredasecurityfeature,itcanhelptomitigatethis
vulnerability.However,inordertoensurethatthefieldiscorrect,additionalmeasures
shouldbetaken.
Forexample,ifwehaveEditTextforane-mail,wecancheckifitscontentmatchesthe
formatofane-mailsimplybyusingthePatternclassfromthejava.util.regexpackage
andthePatternclassfromthejava.utilpackage:
publicvoidisEmail(EditTextet){
if(et.getText()==null)returnfalse;
elsereturnPatterns.EMAIL_ADDRESS.matcher
(et.getText().toString()).matches();
}
Therearemorepatternsavailableinthisclassthatwecanuse:
DOMAIN_NAME:Thispatternisusedtocheckthedomainnames
EMAIL_ADDRESS:Thispatternisusedtocheckthee-mailaddresses
IP_ADDRESS:ThispatternisusedtochecktheIPaddresses
PHONE:Thispatternisintendedtocheckthesubstringsthataresimilartophone
numbersintextandshouldnotbeusedtovalidateaphonenumber
TOP_LEVEL_DOMAIN:ThispatternisusedtochecktheInternetAssignedNumbers
Authority(IANA)top-leveldomains
WEB_URL:ThispatternisusedtocheckmostpartsofthewebURLs
Ifweneedtovalidateaninputthatisnotinthislist,wecanuseourownregular
expressions.Thereareplentyofoptionstodothevalidation,butusingthePatternclass
fromthejava.util.regexpackageisrecommended.Tolearnmoreaboutregular
expressions,whichwillallowyoutodefineyourownpatterns,youcanchecktheofficial
documentationathttp://developer.android.com/reference/java/util/regex/Pattern.html.
SQLinjection
Oneofthemostcommonandharmfulattacksisaparticularkindofcodeinjectionwhere
unauthorizedSQLqueriescanaccessorevenalterourdatabase.Toillustratethissituation,
let’sconsiderthefollowingexamplewhereyouhavethefollowingcodetocheckthe
usernameandpasswordthatwasjustenteredbytheuser:
//Wehavetheusername/passwordintwoEditTexts
Stringusername=usernameEditText.getText().toString();
Stringpassword=passwordEditText.getText().toString();
//Weformourquery
Stringquery=
"SELECT*FROMusersWHEREusername='"+username+"'AND
password='"+password+"'";
SQLiteDatabasedb=this.getWritableDatabase();
//ThemethodrawQueryperformsthequery
Cursorc=db.rawQuery(query,null);
//Incyouhaveacursortotheuseriftherewasamatchinthequery
if(c.getCount!=0)returntrue;//Ifthereisoneresult,grantaccess
Sowhat’stheproblemwiththeprecedingcode?Anattackercansimplywriteausername
andenterthefollowingstringinEditTextforpassword:
''OR'1'='1'
Thiswillgranttheuseraccesstotheusernamesincethestringquerywillappearas
follows:
"SELECT*FROMusersWHEREusername='admin'ANDpassword=''OR'1'=
'1'"
Thebestdefenseagainstthisvulnerabilityistouseparameterizedqueries.Themost
importantmethodsthatwewillbeusingareasfollows:
query(Uriuri,String[]projection,Stringselection,String[]
selectionArgs,StringsortOrder)
insert(Uriuri,ContentValues)
update(Uriuri,ContentValuesvalues,Stringselection,String[]
selectionArgs)
delete(Uriuri,Stringselection,String[]selectionArgs)
NotethatiftheselectionArgsparametercontainsanymeaningfulSQLcharacters,those
charactersaresanitizedandcanthereforemeannoharmtotheintegrityofthedatabase.In
ordertoexecutethecodeusedinthepreviousexamplesafely,wecanusethemethod
showninthefollowingcode:
//Wehavetheusername/passwordintwoEditTexts
Stringusername=usernameEditText.getText().toString();
Stringpassword=passwordEditText.getText().toString();
//WesettheURIofthetable;
StringtableName="USERS";
//Wesettheprojection
String[]projection=newString[]{"username","password"}
//WesettheWHEREclauseorselection
Stringselection="username=?ANDpassword=?";
//Finallywesettheselectionarguments
String[]selectionArgs=newString[]{username,password};
//Nowwegetthedatabase
SQLiteDatabasedb=this.getWritableDatabase();
//ThemethodrawQueryperformsthequery
Cursorc=db.query(tableName,projection,selection,selectionArgs,null);
//Incyouhaveacursortotheuseriftherewasamatchinthequery
if(c.getCount!=0)returntrue;//Ifthereisoneresult,grantaccess
Permissions
TheAndroidsandboxingsystemalienatesapplicationsfromeachother.Thismeansthat
theapplicationsmustexplicitlyshareresourcesthroughtheuseofpermissions.Inorderto
accesstheadditionalcapabilities,weneedtodeclarethepermissionsthatwerequirein
ourmanifest,andthesepermissionsmustbeacceptedbytheuserafterinstallation.
Ifourapplicationdoesnothaveaccesstomanypermissions,itreducesthevulnerabilities
thatmayaffectourapplication.Whendevelopingtheapplication,weshouldalwaystryto
requestasfewpermissionsaspossible.Forexample,trytostoredatalocallyinsteadof
askingforapermissionforexternalstorage.Ifitisnotpossible,wecanobviouslyrequest
permissionsbutweshouldaddressthevulnerabilitiesthatthesepermissionscanleadto.
Ifthesystem-definedpermissionsarenotenough,wecancreateourownpermissionto
use,whichwillbedefinedandwillrequireotherentitiestoaskforpermissionwhen
required.Whencreatingapermission,wehavetoconsiderthedifferentprotectionlevels
available:
normal:Thisisthelowestpossiblepermissionlevelandissetbydefault
dangerous:Thispermissionlevelcanbegrantedbytheuserduringinstallation
signature:Thispermissionlevelisgrantedbythesystemifarequestingappis
signedwiththesamecertificateastheappthatdeclaredthepermission
signatureOrSystem:Thispermissionlevelisgrantedbythesystemifarequesting
appisintheAndroidsystemimageorissignedwiththesamecertificateastheapp
thatdeclaredthepermission
Alwaystrytousethesignaturepermissionssincetheyaretransparenttotheuserand
grantaccessonlytoapplicationssignedbythesamedeveloper.Ifweneedtousethe
dangerouspermissionlevel,wehavetounderstandthatthispermissionisgrantedbythe
userand,therefore,needstobewellexplainedwhendefined.Userscandecidenotto
installtheapplicationiftheydonotunderstandthepermissionthattheyhavetograntorif
theyperceiveitasapossibleharm.
Wewillseesomeexamplesofcreatingpermissionsinthefollowingsections.
Handlingauser’sdataandcredentials
Thebestwaytohandleauser’sdataandcredentialsistominimizetheuseofthis
information.Weshouldhaveaccesstotheuserdata,storeuserdata,ortransmituserdata
onlywhenitiscompletelynecessary.
Inthecaseswherehandlinguser’sdataandcredentialsisnecessary,therearesome
considerationsthatweshouldhaveasdevelopers:
Considerusinghashornonreversibleformsofdataifthelogicofyourapplication
allowsit.
Donotexposeuser’sdatatootherapplicationsonthedevice.Trytomakethe
interprocesscommunicationasstrictaspossible.Programmingwithmoreflexible
interprocesscommunicationpermissionscanbemorecomfortable,butitcanalsobe
ahugevulnerabilityinyoursystem.
MinimizetheuseofAPIsthataccesssensitiveinformation,especiallywhenthe
informationispersonaldata.DifferentAPIshavedifferentprivacypoliciesandcan
evenbemalicioussometimes.
Makesureyouunderstandwhateachandeverypieceofdatathatwehavetosupply
toathird-partycomponentisfor.Whenyoudon’tunderstandwhyathird-party
componentorAPIrequirescertaindata,itisbetternotprovideit.
Limitthenumberoftimesusersareaskedforcredentialsasmuchaspossible.Asking
forcredentialsanumberoftimescanmaketheuserlessawareofpossiblephishing
attacks.
LogsareasharedresourceinAndroid,andthereforeyoushouldbecarefulabout
whichinformationyouwriteontotheselogs.
Avoidtransmittingunnecessaryinformationwheneveritispossible.Whentreating
sensitiveinformation,evaluatewhetheritisnecessarytotransmitthatinformationon
theserver.Iftheoperationcanbeperformedlocally,youshouldperformitlocally.
Whenusingausernameandpasswordauthenticationsystem,besurenottostorethis
informationonthedevice.Ifitisstrictlynecessarytodoso,usecryptography
methodsandneverstoreitasplaindata.
YoucanavoidsomeoftheseproblemsusingtheAndroidclassAccountManager.Theclass
AccountManagerprovidesaccesstotheuser’sonlineaccountsthataresetinthedevice.
Google,Facebook,andWhatsApphavetheirownauthenticatorsthatareusedtomanage
theauthenticationofyourapplication.Thisalsohasanaddedvalue,thatis,toavoidthe
processofregistration,whichsometimescandriveawaylazyusers.Youwilllearnmore
aboutthisauthenticationmethodinChapter7,AuthenticationMethods.
Interapplicationcommunication
AsweseeninChapter2,SecurityinAndroidApplications,therearewaystocommunicate
betweenAndroidappsastheycannotsharedataduetoApplicationsandboxing.This
communicationraisessecuritychallengesthatshouldnotbeoverlooked.
SecuringIntents
WhenusingIntents,therearetwokindsofvulnerabilities:unauthorizedIntentreceiptand
Intentspoofing.AnunauthorizedIntentreceipthappenswhileusinganimplicitIntent.As
theIntentisbroadcasted,thereisnoguaranteethattheintendedrecipientwillreceiveit.A
maliciousapplicationcandeclareanimplicitIntentbydeclaringallthepossibleactionsin
theintentfilter.ThiskindofinterceptioncanleadtoDoSandphishingattacks.
Thebestwaytoprotectagainstthiskindofvulnerabilityistobeverycautiouswith
implicitIntents.
Note
Ifyouaresharingsomeprivateinformation,avoidusingimplicitIntents.
Whenpossible,andespeciallywhilesharingprivateinformation,yourapplicationshould
considerusingexplicitIntents.Youcanmaketherecipientexplicitbysettingthe
destinationclassusingthemethodsetClassName(Contextctxt,StringclassName)
asfollows:
Intenti=newIntent();
i.setClassName("com.example.myapplication",
"com.example.myapplication.MyActivity");
YoucanalsousethesetPackage(stringpackageName)methodtolimittheaccesstoa
singlepackage:
Intenti=newIntent();
i.setPackage("com.example.myapplication");
AnapplicationwithanexportedcomponentthatdoesnotexpectIntentsfromamalicious
applicationisvulnerabletoIntentspoofingattacks.Asadeveloper,youshouldlimityour
component’sexposurebysettingdifferentpermissionlevelrequirementsinthemanifest.
Thedefaultvaluesofcertainpropertiescanbemisleadingandmaychangefromone
versiontoanother.Itisagoodideatoindicatethenatureofyouractivityexplicitly.For
example,let’smakeouractivityPrivateActivityprivate:
<activity
android:name=".PrivateActivity"
android:exported="false">
</activity>
Ifwewanttomakeouractivityaccessibletoexternalapplications,wecanexplicitly
indicatewhichapplicationshavetheselectiveaccess.Inthiscase,we’llmake
SelectiveActivityaccessibletootherapplicationsthroughourownpermission.Then,
wecanusethispermissiontoindicateselectiveaccesstoSelectiveActivityusingthe
Intentfilter,asshowninthefollowingcode:
<permission
android:description="Packtpermission"
android:name="packt.permission"
android:protectionLevel="signature"/>
<activity
android:name=".SelectiveActivity"
android:exported="true"
android:permission="packt.permission">
<intent-filter>
<actionandroid:name="packt.action.NAME_ACTION"/>
</intent-filter>
</activity>
Note
Intentfiltersarenotasecurityfeature.Theyperforminputvalidationinyourreceiverin
ordertoverifythedatareceived.
Securingthecontentproviders
InChapter2,SecurityinAndroidApplicationswehavelearnedaboutthecontentprovider
mechanismthatallowsapplicationstosharerawdata.Oneexternalcomponentcanusean
authoritynameasahandletoperformSQLqueriestobothreadand/orwritecontent.We
shouldbecarefulanduseacontentprovideronlywhenitiscompletelynecessaryandtake
thefollowingprecautions:
Useseparatereadandwriteprovider-levelpermissions.Wecanspecifyeachofthem
withtheattributeandroid:readPermissionandandroid:writePermission.Wecan
alsouseboththeattributesbyusingandroid:permission.
Usepath-permissiontospecifyeachURIthatyouwanttocontrol.Inthisway,you
canallowpermissionforasingleordifferentURIsinyourprovider.
ThismechanismisalsovulnerabletoSQLinjections.Inordertoeasilyavoidthis
vulnerability,Androidsupportsparameterizedqueries.Thecontentprovidermethods
supportparameterization.Themethodsthatareusedinparameterizedqueriestoacontent
providerarethesameastoanyotherSQLdatabase,andwehavealreadyseentheminthis
chapter.
Summary
Inthischapter,youlearnedhowtomitigatethemostimportantvulnerabilitiesthatcan
affectourAndroidapplication.Youknowhowtouseregularexpressionsinorderto
validateaninput.YouhavealsolearnedaboutSQLinjectionsandhowparameterized
queriescanhelpovercomethisvulnerability.Weknowhowtohandleuserandcritical
information.Finally,welearnedhowtouseIntentsandcontentprovidersinthemost
securewaypossible.
Inthenextchapter,youwilllearnhowtopreservetheprivacyofourdata.Youwilllearn
howtohandlethedatawhenstoredlocally,thedifferentpossibilities,andwaystosecure
them.Youwillalsolearnaboutcryptographyandhowtoencryptlocaldata.
Chapter5.PreservingDataPrivacy
Mostapplicationsneedtosavesomekindofdata.Youwanttolearnhowtousethe
storageoptionsprovidedbytheAndroidsystem,howcanyouprotectyourdata
application,whatsecuritymeasuresshouldbetakenineachtypeofstorage,andhowcan
youuseencryptioninAndroidtopreservetheprivacyofyourdata.
ThischapterpresentsthemechanismsofferedbyAndroidtopreserveuserdataprivacy.
Youwilllearntohandledatawhenit’sstoredonthedevice,whataretherisksinvolved
withthestorage,thedifferentstorageoptions,andhowtosecurethestorage.Youwillalso
learnaboutcryptographyandhowtoencryptlocaldata.
Thetopicsthatwillbecoveredinthischapterare:
Dataprivacy
Encryption
Usingencryptiontostoredata
Dataprivacy
Dataprivacyisanimportantconcernforapplicationsbecausealotofinformationis
storedandmanagedintheapplications:contacts,e-mails,bankaccounts,messages,
agenda,socialnetworks,andsoon.Someofthisinformationcanalsobeconsideredas
sensitivedata.Sensitivedatacanbeanyofthefollowingtypesofinformation:
Informationthatallowsyoutoidentifyadeviceortheuserofthatdevicesuchasthe
phonenumberortheInternationalMobileStationEquipmentIdentity(IMEI)
numberofthatdevice
InformationfromtheresourcesofthedevicesuchastheGPSlocationofthatdevice
Informationcreatedandmanagedbytheapplications
Users’personaldatasuchasphotosormessages
Asadeveloper,yourresponsibilityistoprotecttheprivacyoftheinformationthatis
storedbyyourapplication.Therearedifferentmechanismstostoreyourapplicationdata
inAndroid,andeachstoragemechanismismeanttokeepaspecifickindofinformation.
ThestoragemechanismsprovidedbyAndroidaresharedpreferences,internaland
externalstorage,anddatabasestorage.
Sharedpreferences
Sharedpreferencesareusedtosavethecollectionofkey-valuepairsoftheprimitivedata
typessuchasboolean,float,int,long,andstring.Thesekey-valuespairsaresavedin
yourapplicationdataintheformofanXMLfile,whichisstoredonthedeviceat
/data/data/yourpackage/shared_prefs/.Ifyouonlyneedonesharedpreferencefile,
youcangetthedefaultonebyusingthegetPreferences()method.Ifyouneedtocreate
morethanonesharedpreferencefile,youcanspecifyitsnamebyusingthe
getSharedPreferences()method.Boththesemethodsarereceivedasparametersinthe
operatingmode.Theoperatingmodeisstaticfinalint,whichcanhavethefollowing
values:
MODE_PRIVATE:Thesharedpreferencesinthismodeareprivateandonlyyour
applicationcanworkwiththem
MODE_WORLD_READABLE:Thesharedpreferencesinthismodecanbereadbyother
applications
MODE_WORLD_WRITEABLE:Thesharedpreferencesinthismodecanbeeditedbyother
applications
Toillustratethesethreemodes,createanewapplicationprojectandintheonCreate
methodofthemainactivity,addthefollowingtocodetocreatethreesharedpreference
files:
SharedPreferencessharedPref=
getSharedPreferences("com.example.MyPrefsFile",MODE_PRIVATE);
SharedPreferences.Editoreditor=sharedPref.edit();
editor.putBoolean("KeyA",true);
editor.commit();
SharedPreferencessharedPref2=
getSharedPreferences("com.example.MyReadablePrefsFile",
MODE_WORLD_READABLE);
SharedPreferences.Editoreditor2=sharedPref2.edit();
editor2.putBoolean("KeyB",true);
editor2.commit();
SharedPreferencessharedPref3=
getSharedPreferences("com.example.MyWriteablePrefsFile",
MODE_WORLD_WRITEABLE);
SharedPreferences.Editoreditor3=sharedPref3.edit();
editor3.putBoolean("KeyC",true);
editor3.commit();
TheprivatesharedpreferencefileisnamedMyPrefsFile,thereadablesharedpreference
fileisnamedMyReadablePrefsFile,andthewriteablesharedpreferencefileisnamed
MyWriteablePrefsFile.Ineachfile,wesaveaBooleanvalue.Executetheapplication
andopentheDDMSperspective.OpentheFileExplorertabandnavigatetoyour
applicationfilesunder/data/data/yourpackage/.You’llseethatanewshared_prefs
folderhasbeencreatedandinsidethisfolderthethreepreferencefileshavealsobeen
created,asshowninthefollowingscreenshot:
Observethesystempermissionsofthethreepreferencefiles.TheMyReadablePrefsFile
fileallowsanyuserofthesystemtoreaditandtheMyWriteablePrefsFilefileallowsany
userofthesystemtowriteit.Creatingasharedpreferencefileusinganyofthesetwo
modesisverydangerousastheprivacyofthedatastoredinthemisnotpreserved.There
arebettermechanismsthansharedpreferencestodistributedatabetweenapplicationssuch
asthecontentproviders.
Note
Alwayscreateyoursharedpreferencesusingtheprivatemodetoreducesecurityholes.
Themodeflagofthesharedpreferencesdeterminesonlythesystempermissionofthefile.
TheXMLfileisnotencrypted.YoucancheckthisbydownloadingtheMyPrefsFilefile
fromtheDDMSperspective.Openthefileusinganytexteditorandnoticethatthesaved
dataisnotencryptedandcanberead.Thecontentofthedownloadedsharedpreference
fileisasshowninthefollowingcode:
<?xmlversion='1.0'encoding='utf-8'standalone='yes'?>
<map>
<booleanname="KeyA"value="true"/>
</map>
Theactualuser,anyapplicationwiththerootsystempermission,oranyattackerthatgains
accesstothedeviceisabletoreadthisfile.
Note
Donotsavesensitivedataonsharedpreferencesastheyarestoredinanunencryptedfile.
Filesintheinternalstorage
Internalstorageallowsyoutosaveanytypeoffileinyourapplication’sdatadirectory,
whichisstoredonthedeviceat/data/data/yourpackage/files/.Tocreateafile,you
canusetheopenFileOutput()methodinwhichyoucanspecifythemodeflagasa
parameter.Themodeflagcanhavethefollowingvalues:
MODE_PRIVATE:Thefileisprivateinthismodeflagandonlyyourapplicationcan
workwithit.
MODE_APPEND:Inthismodeflag,ifthefilealreadyexists,dataiswrittentotheendof
theexistingfile.Ifthefiledoesnotexist,thesystempermissionsforthefilearelike
thepermissionsforMODE_PRIVATE.
MODE_WORLD_READABLE:Thefileinthismodeflagcanbereadbyotherapplications.
MODE_WORLD_WRITEABLE:Thefileinthismodeflagcanbeeditedbyother
applications.
Justlikethesharedpreferences,creatingafileusingtheMODE_WORLD_READABLEor
MODE_WORLD_WRITEABLEflagisverydangerousastheprivacyofthefilecontentisnot
preserved.Infact,boththeflagsweredeprecatedinAndroidAPILevel17.
Note
DonotusetheflagsMODE_WORLD_READABLEorMODE_WORLD_WRITEABLEtocreateyourfiles.
Thecreatedfilesarenotencrypted,thereforeyoucanencryptthefilecontenttopreserve
itsprivacy.
Filesintheexternalstorage
Externalstoragereferstoaworld-readablepartofstorageinanAndroiddevice.Wetend
tothinkaboutexternalstorageasanSDcard,butactually,externalstoragecanalsobea
non-removablestorage.Externalstoragemaynotalwaysbeavailable,forexample,ifthe
SDcardisremovedincasethestoragewasprovidedbyanSDcard,orifthestoragehas
beenmountedtoaPC.Forthisreason,youmustalwayscheckexternalstoragestate
beforeusingit,usingthefollowingcode:
StringexStorageState=Environment.getExternalStorageState();
Intheexternalstorage,therearetwotypesoffiles:publicandprivate.Thesetwoterms
shouldnotbeconfusedwiththefilepermissions.Thepublicandprivatefilesinexternal
storagearediscussedindetailasfollows:
Publicfiles:Thesefilesintheexternalstoragearefilesthatcanbesharedwithother
applications,suchaspictures,music,orringtones.Tofetchthepathofthedirectories
inwhichthesetypesoffilesshouldbestored,youcanusethe
Environment.getExternalStoragePublicDirectory()method.Youindicatethe
typeofthepubliccontentyouwanttoworkwithasaparameter.Someexamplesfor
thistypeflagareDIRECTORY_PICTURES,DIRECTORY_ALARMS,DIRECTORY_DOCUMENTS,
DIRECTORY_MUSIC,andDIRECTORY_RINGTONES.
Privatefiles:Thesefilesontheexternalstoragearefilesthatbelongtoyour
applicationandhence,theyhavenoutilityoutsideyourapplication.Thesefilesare
removedwhenyourapplicationisuninstalled.Rememberthatalthoughthesetypes
offilesbelongtoyourapplication,theirpermissionsarestillworldreadable.Toget
thepathofyourprivatedirectory,youcanusethecontext.getExternalFilesDir()
method.
Note
Donotsavesensitiveinformationonexternalstoragebecausefilesinitareglobally
readableandwriteable.
Thedatabasestorage
SQLitedatabasesallowyoutostoreyourdatainaprivatedatabase.Thedatabaseisa.db
file,whichiscreatedintheinternalstoragedirectoryofyourapplication.Thespecific
pathforthisfileis/data/data/yourpackage/databases/.Databasesareprivatebutnot
encryptedandthus,theuseroranyattackerthatgainsaccesstothedevicecanreadthe
databasecontent.
Note
Sensitivedatashouldbeencryptedandverysensitivedatashouldnotbesavedonthe
device.
Encryption
Encryptionistheprocessofencodingdataintoaformthatcannotbeunderstoodby
unauthorizedusers.Sensitivedatastoredinthedeviceshouldbeencryptedtopreserveits
security.Youcanencodedatatosaveitassharedpreferences,asfilesintheinternal
storage,indatabases,oreveninexternalstorage.Butyoushouldrememberthatsensitive
datamustnotbestoredonexternalstorage.Therearetwotypesofencryptionmethods:
Symmetric:Insymmetricencryption,thekeysforencodinganddecodingarethe
same.Someexamplesofwell-knownsymmetricalgorithmsareDES,TripleDES,
AES,Serpent,Twofish,andBlowfish.
Asymmetricorpublic-key:Inasymmetricorpublic-keyencryption,thekeyfor
encodingisdifferentfromthekeyfordecoding.Theencryptionkeycanbepublic
andhence,anyonecanencodedatausingthepublickey.Butonlytheownerofthe
privatekeyisabletodecodeit.Someexamplesofwell-knownasymmetric
algorithmsareRSA,Diffie-Hellman,ElGamal,andDSA.
Usingasymmetricalgorithmisenoughtoencryptourdatasincenobodyelseneedsthe
publicencryptionkey.Thefollowingfigureexplainshowsymmetricencryptionworks:
Let’sseeanexampleofhowtoencryptsomeinformation.Theclassthatprovides
implementationsforencryptionanddecryptionistheCipherclassfromthejavax.crypto
package.Tousethisclass,youneedtocreateaninstanceindicatingtheencryption
algorithmandoptionallythemodeorthepadding.Youcanseebothexamplesinthe
followingcodesnippets:
Cipherc=Cipher.getInstance("AES");
Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");
ThenextstepistoinitializetheinstanceusingtheinitmethodoftheCipherclass.This
methodreceivestheoperation—encryptordecrypt—andthekeytousefortheencryption,
asshowninthefollowingcodesnippets:
c.init(Cipher.ENCRYPT_MODE,key);
c.init(Cipher.DECRYPT_MODE,key);
Toperformtheoperation,usethedoFinalmethod,asshowninthefollowingcode
snippet:
byte[]finalBytes=c.doFinal(initialBytes);
Bothmethods—initanddoFinal—admitmoreparametersthatcanbeconsultedinthe
Androidreferenceathttp://developer.android.com/reference/javax/crypto/Cipher.html.
Theencryptionmethods
Thefollowingcodeshowsthecompletemethodtoencryptatextusingtheencryption
methodsdiscussedintheprecedingsection:
publicbyte[]encrypt(Stringtext,Keykey)
throwsNoSuchPaddingException,NoSuchAlgorithmException,
InvalidKeyException,BadPaddingException,IllegalBlockSizeException
{
Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE,key);
byte[]encodedBytes=c.doFinal(text.getBytes());
returnencodedBytes;
}
Thefollowingcodeshowsthecompletemethodtodecryptatextusingthedecryption
methodsdiscussedintheprecedingsection:
publicStringdecrypt(byte[]text,Keykey)
throwsNoSuchPaddingException,NoSuchAlgorithmException,
InvalidKeyException,BadPaddingException,IllegalBlockSizeException
{
Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE,key);
byte[]decodedBytes=c.doFinal(text);
returnnewString(decodedBytes);
}
Generatingakey
Togenerateakeyinordertoencryptordecryptyourdata,youcanjustwritedownyour
ownkeyasaStringdatatype.Forexample,youcanusethefollowinglineofcodebut
withadifferentkey:
privatefinalStringkey="12345678901234567890123456789012";
ToobtainaKeyobjectsothatitcanbepassedasaparametertoyourencryptionand
decryptionmethods,youcanusetheSecretKeySpecclass.Thesimplestconstructorof
thisclassreceivesthekeybytesandalgorithmname,asshowninthefollowinglineof
code:
SecretKeySpecsks=newSecretKeySpec(key.getBytes(),"AES");
Althoughwritingyourownkeyissimple,keepingitvisibleinyourcodeisnotsecure.
Anyattackerthatgainsaccesstoyourcodecangetthekey.Therightwaytogenerate
yourkeyisbyusingtheSecureRandomandKeyGeneratorclasses.Theobjectiveisto
obfuscatethekey.
TheSecureRandomclass,asspecifiedintheAndroidreference,generates
cryptographicallysecurepseudorandomnumbers.Usingthedefaultconstructoris
recommendedsothataninstanceofthestrongestproviderisreturned.Settingaseedmay
alsobeinsecurebecauseitmayreplacethestrongdefaultseed.TheKeyGeneratorclass
generatessymmetriccryptographickeys.Youshouldremembertosavethegeneratedkeys
sothatyoucanusethemlater,evenwhentheapplicationisclosedandrestarted.
Note
YoushouldinvoketheSecureRandomclassusingthedefaultconstructorandwithout
settinganyseed.
Thefollowingcodeshowsthecompletemethodtogenerateakeyforbothencryptionand
decryption:
publicSecretKeySpecgenerateKey()throwsNoSuchAlgorithmException
{
SecureRandomsecureRandom=newSecureRandom();
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("AES");
keyGenerator.init(256,secureRandom);
SecretKeySpecsks=newSecretKeySpec(key.getEncoded(),"AES");
returnsks;
}
Usingencryptiontostoredata
Usingallthemethodsdiscussedintheearliersections,youcannowencryptany
informationinyourapplication,asshowninthefollowingcode:
StringmyData="Mysecretinformation";
SecretKeySpecsks=generateKey();
byte[]encoded=encrypt(myData,sks);
Stringdecoded=decrypt(encoded,sks);
Log.d("MAIN-Encoded:",
Base64.encodeToString(encoded,Base64.DEFAULT));
Log.d("MAIN-Decoded:",decoded);
TheresultsgeneratedinLogCatareshowninthefollowingscreenshot:
Thepreviousexamplecanbeadaptedtoencryptthecontentofafileontheinternal
storageofyourapplication,asshowninthefollowingcode:
StringmyData="Mysecretinformationinmyinternalfile";
SecretKeySpecsks=generateKey();
byte[]encoded=encrypt(myData,sks);
FileOutputStreamfos=
openFileOutput("MyEncryptedFile.txt",Context.MODE_PRIVATE);
fos.write(encoded);
fos.close();
Onexecutingthecodeinyourmainactivity,theMyEncryptedFile.txtfilewillbecreated
intheinternalstorage,asseeninthefollowingscreenshot.Downloadthefileandopenit
inanytexteditor.Noticethatthecontentisnotunderstandablebecauseitisencoded.
Itismandatoryforyoutostorethepersistentdataencryptedretainingthekeythathas
beenusedforencoding.Thekeycannotbesavedintheinternalstorageasitisconsidered
tobesensitivedata.InAndroid4.3,theKeyStorefacilitywasprovidedbutKeyStoreonly
storespublicorprivatekeys.SymmetrickeyscannotbestoredinKeyStore.Toprovide
additionalprotection,thekeyshouldnotbedirectlyaccessibletotheapplication.
Note
Thekeyusedtoencryptyourdatashouldbekeptinasafeplace.Ifyoulosethekey,the
datacannotbedecoded.
Thebestsolutiontokeepyourkeysafeistosendittoyourserversothatthekeyisnever
allocatedinthedeviceitself.Theuseroranyattackerthatgainsphysicalaccesstothe
devicecannotobtainthekey.InChapter6,SecuringCommunications,youwilllearnhow
toprotectyourexternalcommunications.
Analternativesolutionistogeneratethekeyfromapasswordthattheuserhasto
introducewhenstartinghis/herapplication.Thekeyisthereforenotstoredinthedevice
andisrememberedbytheuser.Thissolutionisverysecurebutitrequirestheuserto
introduceapasswordeverytimetheapplicationisstarted,affectingtheusabilityofyour
application.InChapter7,AuthenticationMethods,youwilllearnmoreaboutthe
authenticationmethods.Togenerateakeyfromapassword,youcanusethePBKDF2
algorithmimplementedintheSecretKeyFactoryclass,asshowninthefollowingcode
snippet:
SecretKeyFactoryskf=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
ThekeyisgeneratedcreatingaPBEKeySpecobject,whichreceivesthepassword,abyte
arrayassalt,theiterationcountofthealgorithm,andthederivedkeylength.Themethod
togenerateakeyofthistypeisasshowninthefollowingcode:
privatestaticbyte[]salt="3r4ghe69".getBytes();
publicSecretKeySpecgeneratePassKey(Stringpassword)
throwsNoSuchAlgorithmException,InvalidKeySpecException{
KeySpeckeySpec=
newPBEKeySpec(password.toCharArray(),salt,500,256);
SecretKeyFactoryskf=
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKeykey=skf.generateSecret(keySpec);
SecretKeySpecsks=newSecretKeySpec(key.getEncoded(),"AES");
returnsks;
}
Thesaltbytearraycanalsobestoredintheinternalstorage.
Summary
Inthischapter,youlearnedmoreaboutthedifferenttypesofstorageforourdata
applicationinAndroid.Youalsolearnedaboutthecharacteristicsandrisksofeachtypeof
storage.Youalsoknowhowtoencrypttheuserdataandmanagethelocalstorage.You
havecreatedthenecessarymethodstoencryptyoursensitivedataanduseitinyour
application.
Inthenextchapter,youwilllearnhowtopreservetheprivacyofyourdatawhenitissent
orreceivedoveranetworkfromaninternalorexternaldevice.Youwillalsolearnhowto
securethenetworkusingprotocolssuchasHTTPS.
Chapter6.SecuringCommunications
ThischapterpresentsthemechanismsofferedbyAndroidtosecurecommunications
betweenanAndroidapplicationandanexternalentity.Bytheendofthischapter,youwill
knowhowtosecureconnections.Youwillseesomeimplementationsthroughcode
examplesusingAndroidStudio.
Mostapplicationsneedtosharesomesortofdata.Youshouldlearnhowtoprotectthis
dataespeciallywhensensitiveinformationsuchaspersonaldataorauthentication
informationisbeingtransferred.
Thetopicsthatwillbecoveredinthischapterare:
HTTPS
SSLandTSL
Serverandclientcertificates
AndroidStudio
CodeexamplesusingHTTPS
HTTPS
HypertextTransferProtocolSecure(HTTPS)isconsideredanapplicationlayer
protocolbasedonHTTP.Itisdesignedtotransferthehypertextdatasecurely.HTTPSis
largelyusedbybankentities,onlineshops,andingeneral,anyonlineservicethatrequires
sendingprotecteddata.
Firstofall,youneedtounderstandwhatHTTPSbeinganapplicationlayerprotocol
means.Therearetwoimportantconceptualmodelsthatstandardizetheinternalfunctions
ofacommunicationsystem.ThesemodelsaretheOpenSystemsInterconnection(OSI)
modelandtheTransmissionControlProtocol/Internetprotocolsuite(TCP/IP)model.
TheOSImodelconsistsofsevenabstractionlayerswhiletheTCP/IPmodelissimplified
intoonlyfivelayers.Eachlayerdoesnotrepresentaprotocolbutalevelinwhicha
protocolisencapsulated.Forsimplicityandasitsuseismorecommon,wewillfocuson
theTCP/IPmodel,discussedasfollows:
Thephysicallayer:Thislayerdefinesthemostbasicformofcommunication—the
electricalandphysicalspecifications.Theconnectionisdefinedbetweentwodirectly
connectedelementsoveraphysicallyestablishedcommunicationmedium(cable,air,
andsoon.).TheIEEE802.11specificationsoverwhichWi-Fi,Bluetooth,andeven
USBworkaresomeexamplesoftheprotocolsthatoperateinthephysicallayer.
Thelinklayer:Thislayerdefinesthecommunicationestablishedbetweentwo
elementsthatareinthesamelocalnetwork.Noticethattheremightbeseveral
physicalelements(routers,switches,andfurthermore)betweenthesetwoelements.
TheMediaAccessControl(MAC)protocols,suchasEthernet,ISDN,orDSLwork
inthislayer.
Theinternetlayer:Thislayerisresponsibleforestablishingcommunication
betweentwoelementsacrossmultiplenetworks.Therearetwomainfunctions
carriedoutinthislayer:hostidentificationandpacketrouting.Themostknown
exampleofaprotocolworkinginthislayerisIP,withIPv4andIPv6beingthemost
extendedversionsofIP.
Thetransportlayer:Thislayerdefinesthecommunicationbetweentwoprocesses
indifferenthoststhatcanpotentiallybeseveralnetworksapart.Thislayerusesports
forthepurposeofprovidingcommunicationchannelsneededbytheapplications.
ThemostcommonprotocolsthatworkonthetransportlayerareTCPandUDP.
WhileTCPisconnection-orientedandisinchargeofidentifyinglostpackagesand
resendingthem,UDPisconnectionlessanddoesnotperformthesechecks.
Theapplicationlayer:Thisisthelayerthatapplicationsuseinordertoprovideuser
services.Thislayeristhemostimportantfordevelopers,sinceitisusuallytheone
wewillbeworkingwith.Themodelofthislayerenablesyoutotreatthetransport
layerandlowerlayersasablackbox;theyprovideaserviceandyoudonotneedto
worryaboutthem.Therearehundredsofprotocolsthatworkovertheapplication
layer,forexampleHTTPanditssecureversionHTTPS,FileTransferProtocol
(FTP),SimpleMailTransferProtocol(SMTP),andsoon.Theapplicationlayerin
theTCP/IPmodelcanbecomparedtoacombinationoftheapplicationlayer,
presentationlayer,andsessionlayerintheOSImodel,asshowninthefollowing
figure:
HTTPSisconsideredtobeanapplicationlayerprotocolthatusescryptographicmethods
basedonSecureSocketsLayer(SSL)orhiselderbrotherTransportLayerSecurity
(TLS)toensurethesecurityofsensitivehypertextdata.However,technically,itisnota
protocolitselfbuttheresultofcombiningHTTPintheapplicationlayerwithSSLorTLS
inthetransportlayer.Thesecurityisthereforenotprovidedintheapplicationlayerbutin
thetransportlayer.HTTPSalsospecifiesthatthetransportlayershouldusetheTCP
protocoltoensurethateverypackageisreceivedcorrectly,asshowninthefollowing
figure:
AlthoughHTTPSisbasedontheapplicationlayerprotocolHTTP,therearesome
differencesbetweenthetwoofthem.Themostimportantare:
URLsstartwithhttp://whenusingtheHTTPprotocolandwithhttps://whenusing
theHTTPSprotocol
Bydefault,HTTPusestheTCPport80.Ontheotherhand,HTTPSusesport443by
default
HTTPisvulnerabletoman-in-the-middleattacksandeavesdropping,andisdesigned
tosolvethesevulnerabilitiesandminimizetherisks
IfyouwanttolearnmoreaboutthedifferencesbetweenHTTPandHTTPS,youcanusea
packetanalyzertoseehowtheexchangeofhypertextisperformedwitheachprotocol,as
showninthefollowingscreenshot.Todothis,werecommendWireshark
(http://www.wireshark.org/),afreeandopensourcesoftware(OSS).Youwilllearnmore
aboutthistoolinChapter10,SupportingTools.
SSLandTLS
SSLisacryptographicprotocolthatsupportssecureconnectionsoveranetwork.SSLwas
originallydesignedbyNetscape.TherearethreemainversionsofSSLandbeingthelatest
one,SSL3.0isthemostcommonlyusedovertheInternet.SSL3.0issupportedby99.5
percentofthewebsitesontheInternet.
TLSisanupdateofSSL3.0.ItiscompatiblewithSSL3.0butitweakensthesecurity
level.ThemostextendedversionofTLSisTLS1.0althoughtherearetwoupdates:TLS
1.1andTLS1.2.TLS1.0issupportedby99.3percentofthewebsitesontheInternet.
AnSSLorTSLconnectionisalwaysinitiatedbytheclient.Datatransferredunderthe
SSLprotocolisencryptedusingasymmetricalalgorithmlikeDataEncryptionStandard
(DES).Anasymmetricalalgorithmisusedtoexchangethekeysforthesymmetrical
algorithm.ThebasicstepstoestablishanSSLconnectionareasfollows:
1. Client->server:Theclientinitiatesthecommunicationwiththeserversendinga
“Hello”message.Thismessagecontainsdifferentcryptographicoptionsavailableto
theclientsortedbypreferenceofuse.
2. Server->client:TheserverrespondsbysendingaHellomessage.Inthiscase,the
messagecontainsthecryptographicmethodandthecompressionmethodchosen.
3. Server->client:Theserversendstheirdigitalcertificate.Thestandardistousean
X.509certificate.Iftheserverrequiresacertificatefromtheclient,aCertificate
Requestmessageissent.
4. Client->server:Theclientcross-checksthecertificatereceivedfromtheserverwith
alistofknownauthorities.Iftheauthorityisnotrecognized,theclientcanaskthe
userforpermissiontomanuallyacceptthecertificate.Theclientalsoassessesifthe
connectionparametersareadequate.Ifeverythingisacceptable,theclientgeneratesa
symmetricrandomkey,whichiscypheredwiththeserverpublickeyreceivedinstep
3.Thecypheredsymmetrickeyisthensenttotheserver.
5. Client->server:Theserverreceivestheencryptedsymmetrickeyandproceedsto
decryptitusinghisprivatekey.
6. Client<->server:Nowboththeclientandtheserverknowthesymmetrickeyand
canstartasecureconnection.
Serverandclientcertificates
Inthissection,youwilllearnmoreabouthowcertificatesareusedandgenerated.A
certificateisadigitallysignedstatementfromanauthoritythatgrantsacertainvalueto
thepublickeyofthesubject.Theyareusedinasymmetricencryptionmethods.
X.509certificateisastandardformatandmusthavethefollowinginformation:
Version:ThisistheX.509versionnumber
Serialnumber:Thisisthesequencenumberofthecertificate
Signaturealgorithm:Thisistheidentifierofthealgorithmusedtosignthe
certificate
Issuer:Thisisthenameoftheauthoritythatsignsthecertificate
Validity:Thisistheperiodoftimeduringwhichthecertificateshouldbeconsidered
valid
Subject:Thisisthenameofthesubjectofthepublickey
Subjectpublickey:Thisisthepublickeyitselfanditsrelatedinformation
Youwillnowlearnhowtocreateaself-signedX.509certificatewithnoadditional
installationnecessarywhatsoever.Youwillseetwoeasywaystogenerateacertificate:
usingatoolavailableineveryJavaDevelopmentKit(JDK)calledKeytoolfromthe
terminalandusingthesametoolfromAndroidStudioinamorevisualway.Thereare
manyotheroptionstocreatecertificatesliketheOpenSSLclient.
Keytoolintheterminal
OpenyouroperatingsystemterminalorgotoTools|OpenTerminalinAndroidStudio,
andwritethefollowingcommand:
keytool-genkey-keyalgRSA-aliasselfsigned-keystoremy_keystore.jksstorepasspassword-validity360-keysize2048
Theparameter–genkeyistheactionthetoolandisgoingtoperform.Inthiscase,itwill
generateakey.Theparameter–keyalgspecifiesthealgorithmtobeused;inthiscase,we
wanttouseRSA.Theparameter–aliasisforthenameoraliasofthekeysbeing
generated.Theparameter–keystoreindicateswhichJKSfileisgoingtobeusedtostore
thekeys.Theparameter–storepassindicatesthemasterpasswordusedtoaccesstheJKS
file.Ifthefileisbeingcreatedjustliketheonecreatedinthisexample,youcansetthe
password,butifthekeystorealreadyexists,youshouldintroduceitspassword.The
parameter–validityspecifiesthenumberofdaysthecertificateisvalid.Finally,withthe
parameter–keysize,youcanindicatethesizeofthekeyinbits.Inthisexample,the
parameter–keysizehasavalueof2048becausewehaveusedanRSAalgorithmwhose
keysarenormallybetween1024and2048bits.
Theexecutionofthepreviouscommandwillpromptasequenceofquestions.Makesure
thatwhenaskedforyourfirstnameandlastname,youanswerwiththedomainnameof
theserveryouwanttogetthecertificatefrom.Ifyouhaveproblemsexecutingthis,you
canaddthekeytooltothepathofthesystem.Theapplicationisavailableinthe/bin
folderofyourJDKinstallationfolderandcanalsobeexecuteddirectlyfromthere:
Whatisyourfirstandlastname?
[Unknown]:www.mydomain.com
Whatisthenameofyourorganizationalunit?
[Unknown]:MyApplication
Whatisthenameofyourorganization?
[Unknown]:MyCompany
WhatisthenameofyourCityorLocality?
[Unknown]:Murcia
WhatisthenameofyourStateorProvince?
[Unknown]:Murcia
Whatisthetwo-lettercountrycodeforthisunit?
[Unknown]:ES
Is<CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,
ST=Murcia,C=ES>correct?
[no]:y
Enterkeypasswordfor<my_keystore>
(RETURNifsameaskeystorepassword):
Thisprocesswillgenerateamy_keystore.jksfileinaJKSformat.Thisfilecontainsboth
privatekeyandpublickeycertificatessomakesurenottoshareitasyourprivatekeyis
whatshouldbekeptfromotherentities.Inordertoextractthecertificate,youcanexecute
thefollowingcommand:
keytool–export–aliasselfsigned–filecertificate.crt–keystore
my_keystore.jks–storepasspassword
Thiswillgenerateafilecalledcertificate.crt,whichcontainsthecertificate.Usingthe
verysametool,wecanprintitscontentsusingthefollowingcommand:
keytool–printcert–filecertificate.crt
Thiswillprinttheinformationofourself-signedcertificate:
Owner:CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,
ST=Murcia,C=ES
Issuer:CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,
ST=Murcia,C=ES
Serialnumber:71e760d8
Validfrom:TueJun0317:42:47BST2014until:FriMay2917:42:47BST
2015
Certificatefingerprints:
MD5:63:34:55:9F:11:74:3A:02:EB:D3:8F:E2:7B:A3:1B:25
SHA1:CA:CF:6E:75:83:F9:01:D9:13:45:A5:DE:D2:95:EB:2E:31:BA:2D:B4
SHA256:
5A:A8:68:87:3D:89:B2:26:60:0F:55:DB:68:F1:24:6E:81:33:8B:3B:B2:57:07:36:D4:
06:B2:1A:C3:03:DE:F0
Algorithm:SHA256withRSA
Version:3
YoucanseehowOwnerandIssuerarethesamesincethecertificateisself-signed.Ifit
wassignedbyadifferentCA,IssuerwouldbethatCA.
AndroidStudio
AndroidStudiohasatooltosignyourAPK.Thisoptioninternallymakesuseofkeytool
tocreateacertificatewithwhichtheAPKislatersigned.Youcanusethefirststepofthis
processtogenerateyourcertificate.NavigatetoBuild|GenerateSignedAPK.Awizard
willappearaskingyoutoselectanalreadyexistingcertificateorcreateanewone.Click
onCreateNewandthefollowingwindowwillappear:
Asyoucansee,itasksfortheexactsameinformationwefilledinusingthekeytool.You
canfollowthesameinstructionsasintheprevioussectiontofilltheinformationrequired
inthisform.
Ifyouwanttolearnmoreaboutcertificatesandcertificateauthorities,youcancheckthe
sectiononAppSigningintheAndroiddevelopmentdocumentationsincethesignatureof
appsalsousesthecertificatesandcertificateauthoritiesat
http://developer.android.com/tools/publishing/app-signing.html.
CodeexamplesusingHTTPS
YoualreadyunderstandhowHTTPSworkstheoretically,buthowcananAndroid
developerusesecureconnectionsusingHTTPS?
ToestablishanHTTPconnection,allyouneedtodoisrunthefollowingthreelinesof
code:
URLurl=newURL("http://wikipedia.org");
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
InputStreamin=connection.getInputStream();
Wikipediasupportssecurecommunications,solet’schangethecodetomakeituse
HTTPSinsteadofHTTP,asshowninthefollowingcode:
URLurl=newURL("https://wikipedia.org");
HttpsURLConnectionconnection=(HttpsURLConnection)url.openConnection();
InputStreamin=connection.getInputStream();
Canyouseethedifference?Well,ifyoucanseethedifference,congratulations!Youhave
averysharpeye.Ifyoucan’t,hereisalittlehint:checktheprotocolintheURLagainand
theHttpURLConnectionclass.NowyouseethelittlesafterhttpintheURLandinthe
classname,andyes,thatisallyouneedtodotostartasecurecommunicationwitha
serverthatsupportsHTTPS.
Easyright?Well,thatisnotentirelytrue.Youmayworkwithcertificatesthataresigned
byatrustedCertificateAuthority(CA)oryoumaynotworkwithcertificatessignedby
atrustedCA.Therearethreedifferentcaseswherethiscanhappen:
TheCAthatissuedthecertificateisunknown
Thecertificatewasself-signed
TheserverismissinganintermediateCA
IftheissuerofthecertificateisanunknownCA,anSSLHandshakExceptionwilloccur.If
youknowthisisgoingtohappen,youcancreateHttpsURLConnection,whichtrusts
certainCAsthatarenotinthelistofthesystem-trustedCAs.TheclassTrustManageris
usedbythesysteminordertovalidateunknowncertificates.Inthefollowingexample,we
willcreateKeyStore,whichcontainsourtrustedCAs.WithKeyStore,wewillinitiate
TrustManager,whichtruststheCAsincludedinKeyStore.WithTrustManagercreated,
wewillinitiateanSSLconnection,shownasfollows:
//Firstwereadthecertificatefromafile
CertificateFactorycf=CertificateFactory.getInstance("X.509");
InputStreamcertificate=newBufferedInputStream(new
FileInputStream("my_keystore.jks"));
Certificateca=cf.generateCertificate(certificate);
//NowwecreatetheKeyStorecontainingthecertificate
Stringtype=KeyStore.getDefaultType();
KeyStorekeyStore=KeyStore.getInstance(type);
keyStore.load(null,null);
keyStore.setCertificateEntry("CA",ca);
//NowwecaninitiatetheTrustManagerwithourKeyStore
Stringalgorithm=TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactorytmf=TrustManagerFactory.getInstance(algorithm);
tmf.init(keyStore);
//WiththeTrustManagerweinitiateaSSLContext
SSLContextcontext=SSLContext.getInstance("TLS");
context.init(null,tmf.getTrustManagers(),null);
//NowwecaninitiatetheconnectionusingtheSSLContext
URLurl=newURL("https://www.mydomain.com");
HttpsURLConnectionconnection=(HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(context.getSocketFactory());
InputStreamin=urlConnection.getInputStream();
Asyoucansee,thelastfourlinesofthecodearesimilartowhatweweredoingbefore
worryingaboutthecertificateauthorities.Wehaveremovedsometryclausesforthesake
ofcleancode,butifyoucopythecodetoAndroidStudio,justfollowitssuggestionsto
treatexceptions.
Inthisexample,weusedthecertificatethatwegeneratedusingtheJavatool—keytool.If
youremember,thecertificatewegeneratedwasself-signed,whichisthesecondcaseand
notthefirst.Fromacodingperspective,bothsituationsaresimilar.Inthefirstone,CAis
notrecognizedsowecreateTrustManagerinordertoacknowledgeit.Inthesecondcase,
itisexactlythesame,buttheissuerofthecertificateisalsothesubject.
IftheserverismissinganintermediateCA,therewillalsobeanSSLHandshakeException
sincethereisamissingCAinthetrustchain.Therearetwowaysyoucansolvethis
situation:
Fromtheserverside:YoucanreconfiguretheservertoincludethemissingCAin
thetrustchain.Thisisobviouslypossibleonlyifyouadministratetheserver.
Fromtheclientside:TheonlyproblemyouhaveisthatthereisamissingCA,
therefore,thatCAisanunknownCA.YoucanthereforeusetheclassTrustManager
aswedidinthefirsttwocasestotrustthemissingCAdirectly.
Summary
Inthischapter,youlearnedaboutnetworkcommunicationsinyourAndroidapplication.
Nowyouunderstandhowthemostcommonprotocolstosecureconnectionswork.You
alsolearnedhowtousetheAPIsthatAndroidofferstosecureyourapplication’s
communications.Finally,youlearnedaboutcertificategeneration.
Inthenextchapter,youwilllearnaboutauthenticationmethods.Youwillseehowtwokeyandthree-keyauthenticationmethodswork.Youwillalsolearnaboutusingbiometric
authenticationinyourapplication.
Chapter7.AuthenticationMethods
ThischapterpresentsdifferenttypesofauthenticationmethodsusedinAndroidmobile
devices.Thischapterwillhelpreaderschoosetheproperauthenticationmethodfortheir
mobileapplication.
First,youwilllearnaboutmultifactorauthenticationandthedifferentauthentication
factors,suchastheknowledgefactor,thepossessionfactor,andtheinherencefactor.You
willthenlearnhowtomakeyourownimplementationofaloginsystemforyourAndroid
application.Youwillalsolearnaboutauthenticatingdifferentservicesusing
AccountManager.
Thetopicsthatwillbecoveredinthischapterare:
Multifactorauthentication
Loginimplementations
AccountManager
Multifactorauthentication
Ifyouthinkofanauthenticationmethod,thefirstmethodthatwillcometoyourmindwill
alwaysbethecombinationofausernameandapassword.Whileitssimplicitymakesit
oneofthemostextendedauthenticationmethodsinallkindsofsoftware,itisnotthe
safestmethod.Themultifactorauthenticationapproachcombinesasetofauthentication
methods.Accessisgrantedonlyifeachmethodderivesapositiveresult.Two-factor
authenticationandthree-factorauthenticationinvolvetwoandthreeauthentication
factors,respectively.Althoughtwo-factorauthenticationandaboveareoftenconsideredto
bestrongauthenticationmethodsandareinfactmoresecure,youcanalsoachievestrong
authenticationforyourserviceusingonlyoneauthenticationfactor.Therearethreekinds
ofauthenticationfactorsthatserveasataxonomyforauthenticationtechniques:the
knowledgefactor,thepossessionfactor,andtheinherencefactor.
Theknowledgefactor
Thecombinationofausernameandpasswordisanexampleofaknowledgefactor.When
usingaknowledgefactor,theuserisrequiredtoprovideinformationhe/sheknowsin
ordertograntaccess:somethingtheuserknows.
Themostwidelyusedmethodsare:
Username/password:Thecombinationofacertainkindofidentifierfortheuser,
generallyausernameorane-mailaddress,andapasswordisthemostextended
authenticationtechnique.Whiletheusernameore-mailaddressmaybepublic,the
passwordshouldalwaysremainasecret.
Pattern:Patternsareusedasauthenticationmethodssincethehumanbrainismore
likelytoremembergraphicalpatternsthanstringsofcharactersornumbers.Thereare
severaltypesofpatternsthatofteninvolvea3x3gridalthoughbiggergridsarealso
used.
PIN:ThePINisaverybasicpasswordthathasbeentraditionallyusedinthebanking
systemforATMs,creditcards,andsoon.Itconsistsofanarrayofdigits.Itis
technicallyanimplementationofthepasswordtechniques,whereonlydigitsare
allowed.
ThepatternandPINtechniquesareavailablebydefaultastheaccesscontroltoyour
Androidsystem,asshowninthefollowingscreenshot:
Thepossessionfactor
Themostbasicandwell-knownexampleofapossessionfactorisakeythatopensadoor.
Inordertoauthenticateausertryingtoaccessaresource,theyarerequiredtoprovidea
physicalobjecttheypossess:somethingtheuserhas.
Thereareseveralexamplesofpossessionfactors.Themosttypicaltechniquesbasedona
possessionfactorarephysicaltokenssuchassmartcardsormagneticcards.Thetechnique
mostcommonlyusedinAndroidisprobablythecryptographickeys.Wealreadylearned
aboutcryptographickeysintheearlierchapters,andalthoughthesekeysaredigitaland
theuserdoesnothavematerialaccesstothem,theyareconsideredassomethingtheuser
possesses.ThereareotheralgorithmslikeTime-basedOne-TimePassword(TOTP).
TOTPconsistsofcombiningasecretkeywiththecurrenttimestamptogeneratea
passwordthatistemporarilyvalid.
Theinherencefactor
Theinherencefactorisbasedonsomethingtheuseris.Thetechniquesbasedonthisfactor
aretheonesthatareusedfrequently,buttheoneswiththebrightestfuture.Biometric
authenticationmeasuresthedistinctivecharacteristicsofindividualstoidentifytheuser.
Therearetwotypesofbiometricidentifiers:
Physiologicalcharacteristics:Thisiswhentheshapeofthebodyismeasured.The
mostcommonlyknownexamplesarethefingerprintanalysis,facerecognition,and
irisorretinarecognition.InAndroid,thereareseveralimplementationsofface
recognition,andsomesmartphonescomewithahardwaresupportforfingerprint
scanliketheHTCOneMax.
Behavioralcharacteristics:Thisiswhenthebehaviorofapersonismeasured.
Physiologicalcharacteristicsaremoreconsolidatedthanbehavioralcharacteristics.
Themostextendedbehavioralcharacteristicisvoicerecognition.Therearedifferent
implementationsofvoicerecognitionforAndroid.
Loginimplementations
WewillnowseeasmallexampleonhowtoperformauthenticationusingAndroid.The
examplewearegoingtoseehereusestheloginandpasswordcombinationtechnique.We
aregoingtostartwithaverysimpleexampleandincreasethefunctionalitiesaswellasthe
complexitiesineveryiteration.
Firstofall,wewilldefineEditTextandButton,shownasfollows:
<EditText
android:id="@+id/etUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/etPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
<Button
android:id="@+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="login"
android:text="Login"/>
Now,wearegoingtocheckwhetherthecombinationofausernameandpasswordisgood
ornot.Tostart,wewillsimplycheckwhetherboththeusernameandpasswordareadmin,
shownasfollows:
EditTextusername=(EditText)findViewById(R.id.etUsername);
EditTextpassword=(EditText)findViewById(R.id.etPassword);
StringsUsername=username.getText().toString();
StringsPassword=password.getText().toString();
if(sUsername.equals("admin")&&sPassword.equals("admin")){
//Grantaccess
}else{
Toast.makeText(getApplicationContext(),"Wrongpassword",
Toast.LENGTH_SHORT).show();
}
Thisisobviouslynotagoodexampleofasecureauthenticationmethodbutfromthe
example,wecanlearnsomeusefulthings.Forexample,theinputTypeparameterof
EditTextcanbesettotextPasswordwhenusingapasswordfield.
Youarenormallygoingtomakearequesttoyourserverinordertoauthenticatetheuser.
Forexample,inthiscase,weuseSimpleHTTPClienttomaketherequest,shownas
follows:
EditTextusername=(EditText)findViewById(R.id.etUsername);
EditTextpassword=(EditText)findViewById(R.id.etPassword);
StringsUsername=username.getText().toString();
StringsPassword=password.getText().toString();
ArrayList<NameValuePair>params=newArrayList<NameValuePair>();
params.add(newBasicNameValuePair("username",sUsername);
params.add(newBasicNameValuePair("password",sPassword);
Stringresponse=SimpleHttpClient.executeHttpPost(
"http://www.mydomain.com/login",
params);
//Analyzeresponsewithwhattheserverissupposedtoanswer
Youhavetorealizethatthisimplementationalsohasbigproblems,evenbiggerthanthe
previousone.Inthiscase,theusernameandpasswordarebeingtransferredonlineandany
attackercouldseetheminplaintext.Inordertoavoidthis,wecanuseanHTTPS
connectionaswehaveseeninthepreviouschapter.
Therearesomeloginimplementationsthathashtheusernameandpasswordbefore
sendingthemtotheserverinordertoincreasethesecurity,forexample,usingtheSHA1
hashshownasfollows:
EditTextusername=(EditText)findViewById(R.id.editText1);
EditTextpassword=(EditText)findViewById(R.id.editText2);
StringsUsername=SHA1.Sha1Hash(username.getText().toString());
StringsPassword=SHA1.Sha1Hash(password.getText().toString());
ArrayList<NameValuePair>params=newArrayList<NameValuePair>();
params.add(newBasicNameValuePair("username",sUsername);
params.add(newBasicNameValuePair("password",sPassword);
Stringresponse=SimpleHttpClient.executeHttpPost(
"http://www.mydomain.com/login",
params);
//Analyzeresponsewithwhattheserverissupposedtoanswer
Theproblemwiththisimplementationisthatthehashedusernameandpasswordcanstill
besniffedbyanattackerastheyarestillbeingtransferredinplaintext.Thisisacommon
mistake.Sowhenyoustorepasswords,youwanttomakesureyoustoretheirhashed
versions.Thecorrectsolutionwouldbetosendthepasswordusingasecureconnection.
Later,whenyouwanttocheckifthepasswordisright,youapplythehashfunctiontothe
passwordprovidedbytheuserandcompareittothestoredhashedpasswordtosee
whethertheymatch.
InChapter6,SecuringCommunications,wesawhowtoestablishanHTTPSconnection
betweenyourapplicationandaserver.Youcanusethatinformationandthepreceding
exampletocreateasecureloginimplementationforyourapplication.
AccountManager
TheAccountManagerclassprovidesaccesstoalltheregisteredusers’onlineaccounts.
Thisway,theuseronlyneedstoprovidehis/hercredentialsonceforeachaccountand
thenhe/shecangrantaccesstotheseapplicationsinasimplerway.Usingthe
AccountManagerclass,youcangetatokenthatcanbeusedasaformofauthenticationin
differentservices.
Thestepsthatyouneedtotakeinordertomakeuseofthisfeatureareasfollows:
1. First,youneedtomodifythemanifestfileandaddpermissiontousecredentials:
<uses-permission
android:name="android.permission.USE_CREDENTIALS">
</uses-permission>
2. Onceyourapplicationcanusecredentials,youcangetaninstanceof
AccountManagerusingtheget(Contextc)method:
AccountManageram=AccountManager.get(this);
3. Now,youhaveaninstanceofAccountManager,butyouneedtoknowwhich
accountsareavailable.Todothis,youcanusethegetAccountsByType(Strings)
method.TheStringparameteristhenameoftheaccounttype.Inthiscase,wewill
lookfortheFacebookaccounts:
Account[]accounts=am.getAccountsByType("com.facebook.auth.login");
4. Youcanalsousenullastheparametertoobtainalltheavailableaccounts:
Account[]accounts=am.getAccountsByType(null);
5. ThegetAccountsByNamemethodshouldalsobecallediftheapplicationisusinga
previouslysavedaccountselectioninordertomakesurethatthisaccountstillexists
inthedevice.Youcancheckthisbylookinguptheaccountinthearrayofaccounts
returnedbygetAccountsByName.
6. Onceyouhavealistoftheavailableaccounts,youshouldasktheuserwhichaccount
istobeused.Whentheselectionisdone,youcancallthemethod,shownasfollows:
getAuthToken(Accountaccount,StringauthTokenType,Bundleoptions,
Activityactivity,AccountManagerCallback<Bundle>callback,Handler
handler).
7. YouwillgetanauthenticationtokenintheAccountManagerFuture<Bundle>object
foraparticularaccount,whichwillautomaticallyprompttheuserforacceptanceifit
isrequired.
8. Incasethetokenrequestreturnsanerror,therecouldbeacachedinstanceofan
authenticationtokenthatmaybebeingused.Youcancallthe
invalidateAuthToken(StringaccountType,StringauthToken)methodto
removeanobsoletetoken.Oncetheobsoletetokenisremoved,youcanagainrequest
anewtokenusingthegetAuthTokenmethod.
Summary
Inthischapter,youlearnedaboutmultifactorauthenticationandthedifferenttechniques
availableineachauthenticationfactor.Youalsolearnedhowtomakeyourown
implementationofasimpleloginsystem.Finally,youlearnedhowyoucanget
authenticationtokenstoaccessdifferentservicesbyusingAccountManager.
Inthenextchapter,youwilllearnhowtostarttestingyourapplication,testyouruser
interface,andusethetestenvironmentinAndroidStudio.
Chapter8.TestingYourApplication
Youhavelearnedhowtocreatesecureapplications.Now,youwanttoensurethequality
ofyourAndroidapplication.WhatelementscanbetestedinAndroid?Howtestcasesare
developed?DoesAndroidStudiosupporttesting?
ThischapterintroducesthewaysoftestinganapplicationinAndroid.InAndroid,wecan
designteststoevaluatetheuserinterface(UI),activities,services,andcontentproviders.
Inthischapter,wewilllearnaboutUItesting.
Thetopicsthatwillbecoveredinthechapterareasfollows:
TestinginAndroid
TheuiautomatorAPI
Theuiautomatorviewertool
TheUItestproject
RunningUItestcases
TestinginAndroid
ThesecurityandqualityofAndroidapplicationsarethekeyfactorstoitssuccess.Testing
helpsyoudiscoverbugsanderrorsinyourapplication,measureitsaccuracy,andalso
improvesecurity.
AndroidtestingisbasedonJUnit.JUnitisaframeworktowriterepeatabletestsinJava.
Itevaluateswhethertheclassthatistobetestedisworkingasexpected.Therearetwo
typesofteststobecreatedinanAndroidapplication:
TeststhatcanrunontheJavaVirtualMachine(JVM):Ifyouwanttotest
standardJavaclassesthatdonotcalltheAndroidAPI,youcanuseplainJUnittests.
Theexecutionofthistypeoftestisfasterbecauseitdoesnotrequireanytimefor
deploymentonanAndroiddevice,especiallywhenrunningonanemulator.
TeststhatrequiretheAndroidSDK:Ifyouneedtoevaluateclassesthatuse
AndroidAPI,testshavetoberunonanAndroiddeviceusingtheAndroidJUnit
extensions.Fromnowon,wewillbeusingthiskindoftestsincewewanttolearn
howtocheckAndroidclassessuchasactivitiesortheUIcomponents.
Testsareimplementedinmethodscontainedintestclasses.Thesetestsareorganizedin
testpackages.Byconvention,thetestpackagenameisthesameasyourapplication
packagesuffixedwith.test.Testclassnamesarethesameastheelementtobetested
suffixedwithTest.Forexample,thetestclassthatevaluatesyourMainActivityfile
shouldbenamedMainActivityTest.Testmethodnamesareprefixedwithtest.Some
examplesofmethodnamesaretestLayout()andtestOnClick().
TestingtheUI
TheUIcanbeevaluatedusingthewhite-boxtestingorblack-boxtesting.Inthewhite-box
testing,UIcomponentsarecheckedintheactivitiesthatmanagethem.Activitytesting
willbeexplainedinthenextchapter,thatis,Chapter9,UnitandFunctionalTests.The
black-boxtestingisbasedontheuiautomatorAPI.ThisAPIincludesclassestocapture
andmanipulatecomponentsintheapplicationundertest.Thistypeoftestdoesnotrequire
youtoknowtheinternalimplementationoftheapplication.
AndroidStudiodoesnotdirectlysupporttheuiautomatorframework,butsinceitis
availableintheAndroidSDK,wecanuseitanyway.Thestepstocompletethetesting
processareasfollows:
1. Installtheapplicationundertestonadevice(realdeviceoranemulator).
2. AnalyzetheUIcomponentsoftheapplicationundertest,employingthe
uiautomatorviewertool.
3. CreateaJavatestprojecttoimplementyourtestcasesusingtheuiautomatorAPI.
4. CompilethetestprojectintoaJARfileandinstallitonthedevice.
5. Runtheimplementedtests.
WearegoingtoproceedwithacompleteUItestingexampleinthesuccessivesections,
butfirstlet’slearnabouttheuiautomatorAPI.
TheuiautomatorAPI
TheuiautomatorAPIisincludedintheuiautomator.jarlibrary,whichcanbefoundin
yourAndroidSDKinstallationfolder,underthe<android-sdk>/platforms/directory.
TheAPIincludesaTestCaseclassthatextendstheJUnitTestCaseclass:
UiAutomatorTestCase.TomanipulatetheUIcomponents,theUiDevice,UiSelector,
UiObject,UiCollection,andUiScrollableclassesarealsosuppliedtotheAPI.
TheUiDeviceclass
TheUiDeviceclassrepresentsthedevice.WecangettheUiDeviceinstancebycallingthe
getUiDevice()method.Withthisinstanceobject,youcancheckpropertiessuchasthe
orientationorthedisplaysize.Youcanalsoperformdevice-levelactionssuchasclicking
ontheHomebuttonortakingascreenshot.Someexamplesoftheavailablemethodsare
asfollows:
click(intx,inty):Thismethodperformsaclickatthespecifiedcoordinates
getDisplaySizeDp():Thismethodreturnsthedisplaysizeindevice-independent
pixels
pressBack():Thismethodsimulatesapressonthebackbutton
pressHome():Thismethodsimulatesapressonthehomebutton
sleep():Thismethodsimulatesapressonthepowerbuttontosetthescreenoff
takeScreenshot(Filestorepath):Thismethodtakesascreenshotofthecurrent
screen
wakeUp():Thismethodsimulatesapressonthepowerbuttontosetthescreenon
TheUiSelectorclass
TheUiSelectorclassrepresentsthesearchcriteriatoqueryanyUIelementonthescreen.
Ifnocomponentisfound,UiAutomatorObjectNotFoundExceptionisthrown.Ifmore
thanonecomponentisfound,thefirstoneinthelayouthierarchyisreturned.The
UiSelectorclassoffersmethodstorefinethesearch.Someofthemethodsareasfollows:
checked(booleanval):Thismethodmatcheselementsthatarechecked.
childSelector(UiSelectorselector):Thismethodaddsachildselectorcriteria
tothecurrentselector.
className(StringclassName):Thismethodmatcheselementsofthespecified
class.Forexample,youcansearchforbuttonsusingthefollowingcode:
newUiSelector().className("android.widget.Button")
resourceID(Stringid):ThismethodmatchestheelementwiththespecifiedID.
text(Stringtext):Thismethodmatcheselementscontainingtheindicatedvisible
text.Forexample,youcanrefinetheprevioussearchforbuttonsbyaddingasecond
filter,asshowninthefollowingcode:
newUiSelector().className("android.widget.Button").text("Continue")
TheUiObjectclass
TheUiObjectclassrepresentsaUIelement.TheUiObjectinstancesareobtainedfrom
theUiSelectorinstances.TheclassUiObjectprovidesmethodstoperformactionsonthe
UIelements.Someexamplesofthemethodsareasfollows:
click():ThismethodperformsaclickatthecenteroftheUIelement
exists():Thismethodcheckswhethertheelementexists
getText():Thismethodreturnsthetextoftheelement
isChecked():Thismethodreturnswhethertheelementiscurrentlycheckedornot
setText(Stringtext):Thismethodsetsthetextwhethertheelementallowsit
(whetherit’saneditablefield)
TheUiCollectionclass
TheUiCollectionclassrepresentsacollectionofitems.TheUiCollectioninstancesare
obtainedfromtheUiSelectorinstancesthatreturnacontainerofotherchildUIelements.
Themethodsprovidedbythisclassareallrelatedtotheselectionofchildren,shownas
follows:
getChildByDescription(UiSelectorchildPattern,Stringtext):Thismethod
searchesforachildbyitsdescriptionandreturnsaUiObjectobject
getChildByInstance(UiSelectorchildPattern,intinstance):Thismethod
searchesforachildbyitsinstancenumberandreturnsaUiObjectobject
getChildByText(UiSelectorchildPattern,Stringtext):Thismethodsearches
forachildbyitsvisibletextandreturnsaUiObjectobject
getChildCount(UiSelectorchildPattern):Thismethodreturnsthechildcount
TheUiScrollableclass
TheUiScrollableclassrepresentsascrollablecollectionofitems.Thisclassisusefulto
simulatescrollingandbringshiddenelementsintoview.TheUiScrollableinstancesare
obtainedfromtheUiSelectorinstances.Thisclasspresentsmethodssimilartothe
methodsoftheUiCollectionclassandalsoprovidesmethodstosimulatescrolling:
scrollBackward():Thismethodperformsabackwardscroll
scrollForward():Thismethodperformsaforwardscroll
scrollToBeginning():Thismethodscrollstothebeginning
scrollToEnd():Thismethodscrollstotheend
Theuiautomatorviewertool
TheuiautomatorviewertoolservestotakeasnapshotofthecurrentscreenonanAndroid
devicethatisconnectedtothedevelopmentmachine.Thesnapshotallowsyoutoexamine
thelayoutcomponentsthatareincludedinthescreen.Youcanlearnabouthowtheyare
structuredandtheirpropertiessuchasIDs,texts,classes,andfurthermore.The
uiautomatorviewertoolisincludedinthetoolsdirectoryoftheAndroidSDKinstallation:
<android-sdk>/tools/.
Let’slookatanexampletoshowhowthistoolworks.Sinceweareperformingblack-box
testing,theuiautomatorviewertoolcanbeappliedtoanyapplicationalthoughitisnot
developedbyus,nordowehaveitssourcecode.WearegoingtousethedefaultAndroid
clockapplicationbyfollowingthisprocedure:
1. OpenAndroidStudioandlaunchanAndroidVirtualDevice(AVD)intheemulator.
Youcanalsousearealdeviceconnectedtoyourcomputer.
2. Whenthedeviceiscompletelyloaded,opentheapplicationdrawerandselectthe
Clockapplication.
3. BackintheAndroidStudioIDE,clickontheToolsmenuandselecttheOpen
Terminaloptiontoopentheterminalpanel.
4. Usingtheterminal,navigatetotheAndroidtoolsfolderwherethe
uiautomatorviewerexecutableisfound.InUnix-basedsystems,youcanfinditby
usingthecommand:
$cdandroidSDK/tools/
5. Launchuiautomatorviewerbyusingthecommand:
$./uiautomatorviewer
6. Theuiautomatorviewertoolisnowopenandshowsanemptywindow.Clickonthe
buttoniconfromthetopbar,whichhintsattheDeviceScreenshot(uiautomator
dump).Thisbuttonismarkedinredinthefollowingscreenshot.Thisoptionwilltake
asnapshotoftheclockapplicationthatisbeingdisplayedintheforegroundinthe
emulator.
Intheuiautomatorviewer,wecaninspectthelayoutelementsofthescreen.Thefollowing
screenshotshowstheuiautomatorvieweraftercapturingthescreenfromtheclock
application.Ontheleftsideoftheviewer,thesnapshotisdisplayed.Youcanhoverthe
mouseoverittonavigateandselecttheUIcomponents.Onthetop-rightpartofthe
viewer,thelayouthierarchyislisted.Wecanexpandandcollapsethelayoutsandselect
individualelements.Inthefollowingscreenshotofourexample,thelayoutcontainingthe
hourisselected.Onthebottom-rightpartoftheviewer,thepropertiesoftheselected
componentaredetailed.
TheUItestproject
ThetestcodetoevaluatetheUIofanapplicationhastobeincludedinanormalJava
project.ThisJavaprojectwillbebuiltintoaJARfile,whichwillbecopiedintheAndroid
devicetoevaluatetheapplicationundertest.SinceAndroidStudiodoesnotsupportthe
uiautomatorframework,forthissectionyoucanuseanyothertoolthatallowsyoucreate
aJavaproject.Therequiredstepsareasfollows:
1. CreateastandardJavaproject.Thisisthetestprojectwherethetestcodewillbe
implementedusingtheuiautomatorAPI.YoucancallthisprojectUITestProject.
2. ImporttheJUnitlibraryintoyourtestproject.Currently,JUnit3.8isthesupported
version.
3. ImporttheAndroidlibraryasanexternalJARintoyourtestproject.ThisJARis
namedandroid.jarandisstoredinyourAndroidSDKinstallationfolderunder
<android-sdk>/platforms/<sdk>/.
4. ImporttheuiautomatorlibraryasanexternalJARintoyourtestproject.ThisJARis
nameduiautomator.jarandisstoredinyourAndroidSDKinstallationfolderunder
<android-sdk>/platforms/<sdk>/.
5. Createanewclassinthesourcefolderofyourtestproject.Youcannametheclass
ClockTest.java.Thisclassisusedtoimplementyourtestcaseandtherefore,hasto
extendtheUiAutomatorTestCaseclass.
6. AddyourtestcodeintheClockTestclass.
YourUItestcodeisnowready.Forourexample,let’saddsomesimplecodejustto
demonstratehowUItestingworks.CreateatestmethodnamedtestOpenAlarmsto
evaluatethealarmbuttonintheclockapplication.Toperformaclickonthealarmbutton,
weneedtoindicateitsID,whichcanbeextractedfromuiautomatorviewer,asshownin
thefollowingscreenshot:
TheresourceIdmethodoftheUiSelectorclasscanbeusedtofindtheUIcomponent
whoseIDiscom.android.deskclock:id/alarms_button.Theobjectcreatedcanbe
checkedandifeverythingisfine,aclickissimulatedonit:
publicclassClockTestextendsUiAutomatorTestCase{
publicvoidtestOpenAlarms()throwsUiObjectNotFoundException{
UiObjectalarmButton=newUiObject(newUiSelector().
resourceId("com.android.deskclock:id/alarms_button"));
if(alarmButton.exists()&&alarmButton.isEnabled()){
alarmButton.click();
}
}
}
RunningUItestcases
TheJavatestprojectcreatedintheprevioussectionhastobecompiledintoaJARfileto
runyourtestcases.TheJARfilehastobecopiedontothesameAndroiddeviceinwhich
theapplicationundertestisrunning.Followthenextstepstorunyourtestcase:
1. OpentheterminalpanelinAndroidStudio(Tools|OpenTerminal).
2. NavigatetotheAndroidStudiostoolsfolderwheretheandroidexecutableisfound:
$cdandroidSDK/tools/
3. GettheIDoftheAndroidtargetthatyouwanttouseinyourproject.Executethe
androidexecutablewiththelistofthetargetactions.Thiscommandwilllistthe
availableAndroidtargetsalongwiththeirIDs:
$./androidlisttargets
4. Executetheandroidexecutablewiththecreateuitest-projectaction.This
commandreceivesthenameoftheoutputproject(-n),theIDoftheAndroidtarget(t),andthepathofyourJavatestproject(-p)asparameters.Thisstepistogenerate
theproject’sbuildfileasatestproject:
$./androidcreateuitest-project–nUITest-t1
-p/Users/myUser/workspace/UITestProject
Note
TheUItestprojectscanonlytargetAPI16andabove;otherwise,anerrorwillbe
prompted.
Asaresult,theUITestProject/build.xmlfileisgeneratedandthe
/Users/myUser/workspace/UITestProject/build.xmlfileisadded.
5. BuildtheJARfilefromtheprojectusingthebuild.xmlfileobtainedbefore.
6. CopytheJARfileintothedeviceusingtheadbutility:
$cdandroidSDK/platform-tools/
$./adbpush/Users/myUser/workspace/UITestProject/bin/UITest.jar
/data/local/tmp
7. Finally,executethenextcommandtoruntheUItestcaseontheconnecteddevice:
$./adbshelluiautomatorruntestUITest.jar-ccom.example.ClockTest
IfyouobservethedevicewhiletheUItestisbeingexecuted,youwillseehowtheactions
implementedinthetestOpenAlarmstestmethodaresimulated.Theresultsareshownin
theterminalpanelasyoucanseeinthefollowingscreenshot,inwhichthetestcase
executionhasbeensuccessful:
Summary
Inthischapter,youlearnedabouttestinginAndroid.Youdevelopedblack-boxtestingfor
youruserinterface.YoualsolearnedhowtocreateatestcaseforyourapplicationUIand
howyoucanrunitonadevice.
Inthenextchapter,youwilllearnmoreabouttestinginAndroid.Youwilldeveloptest
casestoevaluatetheactivitiesofyourapplication.Youwilluseunitandfunctionaltests
andsetupthetestingenvironmentusingAndroidStudio.
Chapter9.UnitandFunctionalTests
YoualreadylearnedaboutAndroidtestinginthepreviouschapter.Youknowhowto
developablack-boxtestoftheUIofyourapplication.Nowyouwanttolearnhowto
implementthewhite-boxtestingforyourapplication.Aretheredifferenttypesofactivity
testing?DoesAndroidStudiosupportactivitytesting?Howcanyougettheresultsofyour
testcases?Wewillbecoveringthesepointsinthischapter.
Inthischapter,youwilllearnhowtouseunitteststhatallowdeveloperstoquicklyverify
thestateandbehaviorofanactivityonitsown.Thechapterwillalsocoverfunctional
tests;theirmainpurposeistochecktheinteractionbetweencomponents.
Thetopicsthatwillbecoveredinthischapterareasfollows:
Differencesbetweenunitandfunctionaltests
AndroidtestingAPI
Creatingasimpleunittestcase
Creatingasimplefunctionaltest
Gettingthetestresults
Testingactivities
Therearetwopossiblemodesoftestingactivities:
Functionaltesting:Infunctionaltesting,theactivitybeingtestediscreatedusingthe
systeminfrastructure.ThetestcodecancommunicatewiththeAndroidsystem,send
eventstotheUI,orlaunchanotheractivity.
Unittesting:Inunittesting,theactivitybeingtestediscreatedwithminimal
connectiontothesysteminfrastructure.Theactivityistestedinisolation.
Inthischapter,wewillexploretheAndroidtestingAPItolearnabouttheclassesand
methodsthatwillhelpyoutesttheactivitiesofyourapplication.
Thetestcaseclasses
TheAndroidtestingAPIisbasedonJUnit.AndroidJUnitextensionsareincludedinthe
android.testpackage.Thefollowingfigurepresentsthemainclassesthatareinvolved
whentestingactivities:
Let’slearnmoreabouttheseclasses:
TestCase:ThisJUnitclassbelongstothejunit.framework.TheTestCasepackage
representsageneraltestcase.ThisclassisextendedbytheAndroidAPI.
InstrumentationTestCase:Thisclassanditssubclassesbelongtotheandroid.test
package.Itrepresentsatestcasethathasaccesstoinstrumentation.
ActivityTestCase:Thisclassisusedtotestactivities,butformoreusefulclasses,
youshoulduseoneofitssubclassesinsteadofthemainclass.
ActivityInstrumentationTestCase2:Thisclassprovidesfunctionaltestingofan
activityandisparameterizedwiththeactivityundertest.Forexample,toevaluate
yourMainActivity,youhavetocreateatestclassnamedMainActivityTestthat
extendstheActivityInstrumentationTestCase2class,shownasfollows:
publicclassMainActivityTestextends
ActivityInstrumentationTestCase2<MainActivity>
ActivityUnitTestCase:Thisclassprovidesunittestingofanactivityandis
parameterizedwiththeactivityundertest.Forexample,toevaluateyour
MainActivity,youcancreateatestclassnamedMainActivityUnitTestthat
extendstheActivityUnitTestCaseclass,shownasfollows:
publicclassMainActivityUnitTestextends
ActivityUnitTestCase<MainActivity>
ThereisanewtermthathasemergedfromthepreviousclassescalledInstrumentation.
Instrumentation
Theexecutionofanapplicationisruledbythelifecycle,whichisdeterminedbythe
Androidsystem.Forexample,thelifecycleofanactivityiscontrolledbytheinvocation
ofsomemethods:onCreate(),onResume(),onDestroy(),andsoon.Thesemethodsare
calledbytheAndroidsystemandyourcodecannotinvokethem,exceptwhiletesting.The
mechanismtoallowyourtestcodetoinvokecallbackmethodsisknownasAndroid
instrumentation.
Androidinstrumentationisasetofmethodstocontrolacomponentindependentofits
normallifecycle.Toinvokethecallbackmethodsfromyourtestcode,youhavetousethe
classesthatareinstrumented.Forexample,tostarttheactivityundertest,youcanusethe
getActivity()methodthatreturnstheactivityinstance.Foreachtestmethodinvocation,
theactivitywillnotbecreateduntilthefirsttimethismethodiscalled.Instrumentationis
necessarytotestactivitiesconsideringthelifecycleofanactivityisbasedonthecallback
methods.ThesecallbackmethodsincludetheUIeventsaswell.
Fromaninstrumentedtestcase,youcanusethegetInstrumentation()methodtoget
accesstoanInstrumentationobject.Thisclassprovidesmethodsrelatedtothesystem
interactionwiththeapplication.Thecompletedocumentationaboutthisclasscanbe
foundat:http://developer.android.com/reference/android/app/Instrumentation.html.Some
ofthemostimportantmethodsareasfollows:
TheaddMonitormethod:Thismethodaddsamonitortogetinformationabouta
particulartypeofIntentandcanbeusedtolookforthecreationofanactivity.A
monitorcanbecreatedindicatingIntentFilterordisplayingthenameofthe
activitytothemonitor.Optionally,themonitorcanblocktheactivitystarttoreturn
itscannedresult.Youcanusethefollowingcalldefinitionstoaddamonitor:
ActivityMonitoraddMonitor(IntentFilterfilter,ActivityResultresult,
booleanblock).
ActivityMonitoraddMonitor(Stringcls,ActivityResultresult,boolean
block).
Thefollowinglineisanexamplelinecodetoaddamonitor:
Instrumentation.ActivityMonitormonitor=
getInstrumentation().addMonitor(SecondActivity.class.getName(),null,
false);
Theactivitylifecyclemethods:Themethodstocalltheactivitylifecyclemethods
are:callActivityOnCreate,callActivityOnDestroy,callActivityOnPause,
callActivityOnRestart,callActivityOnResume,callActivityOnStart,finish,
andsoon.Forexample,youcanpauseanactivityusingthefollowinglinecode:
getInstrumentation().callActivityOnPause(mActivity);
ThegetTargetContextmethod:Thismethodreturnsthecontextfortheapplication.
ThestartActivitySyncmethod:Thismethodstartsanewactivityandwaitsforitto
beginrunning.Thefunctionreturnswhenthenewactivityhasgonethroughthefull
initializationafterthecalltoitsonCreatemethod.
ThewaitForIdleSyncmethod:Thismethodwaitsfortheapplicationtobeidle
synchronously.
Thetestcasemethods
JUnit’sTestCaseclassprovidesthefollowingprotectedmethodsthatcanbeoverridden
bythesubclasses:
setUp():Thismethodisusedtoinitializethefixturestateofthetestcase.Itis
executedbeforeeverytestmethodisrun.Ifyouoverridethismethod,thefirstlineof
codewillcallthesuperclass.AstandardsetUpmethodshouldfollowthegivencode
definition:
@Override
protectedvoidsetUp()throwsException{
super.setUp();
//Initializethefixturestate
}
tearDown():Thismethodisusedtoteardownthefixturestateofthetestcase.You
shouldusethismethodtoreleaseresources.Itisexecutedafterrunningeverytest
method.Ifyouoverridethismethod,thelastlineofthecodewillcallthesuperclass,
shownasfollows:
@Override
protectedvoidtearDown()throwsException{
//Teardownthefixturestate
super.tearDown();
}
Thefixturestateisusuallyimplementedasagroupofmembervariablesbutitcanalso
consistofdatabaseornetworkconnections.IfyouopenorinitconnectionsinthesetUp
method,theyshouldbeclosedorreleasedinthetearDownmethod.Whentestingactivities
inAndroid,youhavetoinitializetheactivityundertestinthesetUpmethod.Thiscanbe
donewiththegetActivity()method.
TheAssertclassandmethod
JUnit’sTestCaseclassextendstheAssertclass,whichprovidesasetofassertmethods
tocheckforcertainconditions.Whenanassertmethodfails,
AssertionFailedExceptionisthrown.Thetestrunnerwillhandlethemultipleassertion
exceptionstopresentthetestingresults.Optionally,youcanspecifytheerrormessagethat
willbeshowniftheassertfails.YoucanreadtheAndroidreferenceoftheTestCaseclass
toexaminealltheavailablemethodsat
http://developer.android.com/reference/junit/framework/Assert.html.Theassertion
methodsprovidedbytheAssertsuperclassareasfollows:
assertEquals:Thismethodcheckswhetherthetwovaluesprovidedareequal.It
receivestheactualandexpectedvaluethatistobecomparedwitheachother.This
methodisoverloadedtosupportvaluesofdifferenttypes,suchasshort,String,
char,int,byte,boolean,float,double,long,orObject.Forexample,the
followingassertionmethodthrowsanexceptionsincebothvaluesarenotequal:
assertEquals(true,false);
assertTrueorassertFalse:ThesemethodscheckwhetherthegivenBoolean
conditionistrueorfalse.
assertNullorassertNotNull:Thesemethodscheckwhetheranobjectisnullor
not.
assertSameorassertNotSame:Thesemethodscheckwhethertwoobjectsreferto
thesameobjectornot.
fail:Thismethodfailsatest.Itcanbeusedtomakesurethatapartofcodeisnever
reached,forexample,ifyouwanttotestthatamethodthrowsanexceptionwhenit
receivesawrongvalue,asshowninthefollowingcodesnippet:
try{
dontAcceptNullValuesMethod(null);
fail("Noexceptionwasthrown");
}catch(NullPointerExceptionne){
//OK
}
TheAndroidtestingAPI,whichextendsJUnit,providesadditionalandmorepowerful
assertionclasses:ViewAssertsandMoreAsserts.
TheViewAssertsclass
TheassertionmethodsofferedbyJUnit’sAssertclassarenotenoughifyouwanttotest
somespecialAndroidobjectssuchastheonesrelatedtotheUI.TheViewAssertsclass
implementsmoresophisticatedmethodsrelatedtotheAndroidviews,thatis,fortheView
objects.ThewholelistwithalltheassertionmethodscanbeexploredintheAndroid
referenceaboutthisclassat
http://developer.android.com/reference/android/test/ViewAsserts.html.Someofthemare
describedasfollows:
assertBottomAlignedorassertLeftAlignedorassertRightAlignedor
assertTopAligned(Viewfirst,Viewsecond):Thesemethodscheckthatthetwo
specifiedViewobjectsarebottom,left,right,ortopaligned,respectively
assertGroupContainsorassertGroupNotContains(ViewGroupparent,View
child):ThesemethodscheckwhetherthespecifiedViewGroupobjectcontainsthe
specifiedchildView
assertHasScreenCoordinates(Vieworigin,Viewview,intx,inty):This
methodchecksthatthespecifiedViewobjecthasaparticularpositionontheorigin
screen
assertHorizontalCenterAlignedorassertVerticalCenterAligned(View
referenceViewview):ThesemethodscheckthatthespecifiedViewobjectis
horizontallyorverticallyalignedwithrespecttothereferenceview
assertOffScreenAboveorassertOffScreenBelow(Vieworigin,Viewview):
ThesemethodscheckthatthespecifiedViewobjectisaboveorbelowthevisible
screen
assertOnScreen(Vieworigin,Viewview):Thismethodchecksthatthespecified
Viewobjectisloadedonthescreenevenifitisnotvisible
TheMoreAssertsclass
TheAndroidAPIextendssomeofthebasicassertionmethodsfromtheAssertclassto
presentsomeadditionalmethods.SomeofthemethodsincludedintheMoreAssertsclass
are:
assertContainsRegex(StringexpectedRegex,Stringactual):Thismethod
checksthattheexpectedregularexpression(regex)containstheactualgivenstring
assertContentsInAnyOrder(Iterable<?>actual,Object…expected):This
methodchecksthattheiterableobjectcontainsthegivenobjectsandinanyorder
assertContentsInOrder(Iterable<?>actual,Object…expected):Thismethod
checksthattheiterableobjectcontainsthegivenobjects,butinthesameorder
assertEmpty:Thismethodchecksifacollectionisempty
assertEquals:ThismethodextendstheassertEqualsmethodfromJUnittocover
collections:theSetobjects,intarrays,Stringarrays,Objectarrays,andsoon
assertMatchesRegex(StringexpectedRegex,Stringactual):Thismethod
checkswhethertheexpectedregexmatchesthegivenactualstringexactly
OppositemethodssuchasassertNotContainsRegex,assertNotEmpty,
assertNotEquals,andassertNotMatchesRegexareincludedaswell.Allthesemethods
areoverloadedtooptionallyincludeacustomerrormessage.TheAndroidreferenceabout
theMoreAssertsclasscanbeinspectedtolearnmoreabouttheseassertmethodsat
http://developer.android.com/reference/android/test/MoreAsserts.html.
UItestingandTouchUtils
Thetestcodeisexecutedintwodifferentthreadsastheapplicationundertest,although,
boththethreadsruninthesameprocess.WhentestingtheUIofanapplication,UIobjects
canbereferencedfromthetestcode,butyoucannotchangetheirpropertiesorsend
events.TherearetwostrategiestoinvokemethodsthatshouldrunintheUIthread:
Activity.runOnUiThread():ThismethodcreatesaRunnableobjectintheUIthread
inwhichyoucanaddthecodeintherun()method.Forexample,ifyouwantto
requestthefocusofaUIcomponent:
publicvoidtestComponent(){
mActivity.runOnUiThread(
newRunnable(){
publicvoidrun(){
mComponent.requestFocus();
}
}
);
…
}
@UiThreadTest:Thisannotationaffectsthewholemethodbecauseitisexecutedon
theUIthread.Consideringtheannotationreferstoanentiremethod,statementsthat
donotinteractwiththeUIarenotallowedinit.Forexample,considertheprevious
exampleusingthisannotation,shownasfollows:
@UiThreadTest
publicvoidtestComponent(){
mComponent.requestFocus();
…
}
Thereisalsoahelperclassthatprovidesmethodstoperformtouchinteractionsonthe
viewofyourapplication:TouchUtils.ThetoucheventsaresenttotheUIthreadsafely
fromthetestthread;therefore,themethodsoftheTouchUtilsclassshouldnotbeinvoked
intheUIthread.Someofthemethodsprovidedbythishelperclassareasfollows:
TheclickViewmethod:Thismethodsimulatesaclickonthecenterofaview
Thedrag,dragQuarterScreenDown,dragViewBy,dragViewTo,dragViewToTop
methods:ThesemethodssimulateaclickonanUIelementandthendragit
accordingly
ThelongClickViewmethod:Thismethodsimulatesalongpressclickonthecenter
ofaview
ThescrollToToporscrollToBottommethods:ThesemethodsscrollaViewGroupto
thetoporbottom
Themockobjectclasses
TheAndroidtestingAPIprovidessomeclassestocreatemocksystemobjects.Mock
objectsarefakeobjectsthatsimulatethebehaviorofrealobjectsbutaretotallycontrolled
bythetest.Theyallowisolationoftestsfromtherestofthesystem.Mockobjectscan,for
example,simulateapartofthesystemthathasnotbeenimplementedyet,orapartthatis
notpracticaltobetested.
InAndroid,thefollowingmockclassescanbefound:MockApplication,MockContext,
MockContentProvider,MockCursor,MockDialogInterface,MockPackageManager,
MockResources,andMockContentResolver.Theseclassesareunderthe
android.test.mockpackage.Themethodsoftheseobjectsarenonfunctionalandthrow
anexceptioniftheyarecalled.Youhavetooverridethemethodsthatyouwanttouse.
Creatinganactivitytest
Inthissection,wewillcreateanexampleapplicationsothatwecanlearnhowto
implementthetestcasestoevaluateit.Someofthemethodspresentedintheprevious
sectionwillbeputintopractice.Youcandownloadtheexamplecodefilesfromyour
accountathttp://www.packtpub.com.
Ourexampleisasimplealarmapplicationthatconsistsoftwoactivities:MainActivity
andSecondActivity.TheMainActivityimplementsaself-builtdigitalclockusingtext
viewsandbuttons.Thepurposeofcreatingaself-builtdigitalclockistohavemorecode
andelementstouseinourtests.ThelayoutofMainActivityisarelativeonethatincludes
twotextviews:oneforthehour(thetvHourID)andonefortheminutes(thetvMinute
ID).Therearetwobuttonsbelowtheclock:onetosubtract10minutesfromtheclock(the
bMinusID)andonetoadd10minutestotheclock(thebPlusID).Thereisalsoanedit
textfieldtospecifythealarmname.Finally,thereisabuttontolaunchthesecondactivity
(thebValidateID).Eachbuttonhasapertinentmethodthatreceivestheclickeventwhen
thebuttonispressed.Thelayoutlookslikethefollowingscreenshot:
TheSecondActivityreceivesthehourfromtheMainActivityandshowsitsvalueina
textviewsimulatingthatthealarmwassaved.Theobjectivetocreatethissecondactivity
istobeabletotestthelaunchofanotheractivityinourtestcase.
OpenAndroidStudioandtheAndroidprojectundertest.Youcancreateablankproject
withamainactivityandlayout.Laterinthischapter,wewilladdanexamplecodetorun
thetestcases.Intheprojectstructure,thereisafolderandapackagewherethetestswill
besaved:/src/androidTest/java/<your_package>.Ifyoudon’thavethispackage,you
shouldaddit.
Creatingaunittest
Aunittestevaluatestheactivityinisolation.Unittestsareused,forexample,tochecka
methodoftheactivityortocheckthattheactivityhasthecorrectlayout.Inthissection,
wearegoingtocreateaunittestforthemainactivityofourexampleproject.
CreateanewclassinthetestpackageofyourapplicationnamedMainActivityUnitTest.
ThisclassextendstheActivityUnitTestCaseclass,whichisthetestcaseclasstocreate
unittests.Thetestclasshastobeparameterizedwiththeactivityundertestandyoualso
needtoaddthetestcaseconstructor,shownasfollows:
publicclassMainActivityUnitTestextends
ActivityUnitTestCase<MainActivity>{
publicMainActivityUnitTest(){
super(MainActivity.class);
}
Forthisunittestexample,wewillcreatethesetUpmethod,andthenwewilltestthe
buttonstomanagetheclock,mainlayout,andlaunchofthesecondactivity.
Theunittestsetup
Thefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthe
layoutobjectsthatwillbeusedinthetestmethods,shownasfollows:
privateMainActivitymActivity;
privateTextViewmHour,mMinute;
privateButtonmValidate,mMinus,mPlus;
ThegetActivity()methodinitializestheactivityundertest,butrememberthatinunit
tests,theactivityistestedinisolationandtherefore,itisnotautomaticallystartedbythe
system.TheactivityhastobestartedinyourowncodeviaanIntentobject.Thecodefor
thesetUpmethodisasfollows:
@Override
protectedvoidsetUp()throwsException{
super.setUp();
Intentintent=newIntent(getInstrumentation().getTargetContext(),
MainActivity.class);
startActivity(intent,null,null);
mActivity=getActivity();
mHour=(TextView)mActivity.findViewById(R.id.tvHour);
mMinute=(TextView)mActivity.findViewById(R.id.tvMinute);
mValidate=(Button)mActivity.findViewById(R.id.bValidate);
mMinus=(Button)mActivity.findViewById(R.id.bMinus);
mPlus=(Button)mActivity.findViewById(R.id.bPlus);
}
LayoutelementsareaccessedbytheirIDasusual.Becausethetestcodeisincludedina
differentpackage,youhavetoimporttheRclassfromtheapplicationpackage.
Theclocktest
Let’sstartimplementingtestmethods.First,wewillcheckwhethertheclockworks
properly.Thetestmethodconsistsofclickingonboththebuttons,thatis,-10minand+
10minandcheckingwhetherthevaluesforthehourandminutetextsaretheexpected
ones.Sincetheactivityrunsinisolation,theTouchUtilslibrarycannotbeused,butthe
performClickmethodcanbeinvokedinstead,asfollows:
publicvoidtestClock(){
mMinus.performClick();
assertEquals("11",mHour.getText());
assertEquals("50",mMinute.getText());
mPlus.performClick();
mPlus.performClick();
mMinus.performClick();
assertEquals("00",mHour.getText());
assertEquals("00",mMinute.getText());
}
Fromthedefaultlayoutvalues,theinitialhouris00:00.Onclickingtheminusbutton
once,theresultanthouris11:50.Onclickingtheplusbuttontwiceandtheminusbutton
once,thefinalhourisagain00:00.TheconditionsarecheckedusingtheassertEquals
method.
Tip
IfyouwanttotestcomplexUIevents,donotuseunittests;youshouldcreateafunctional
test(ActivityInstrumentationTestCase2testcase).
Thelayouttest
Thesecondtestmethodtobeimplementedisusedtotestwhetherthelayoutiscorrect.
ThetextoftheUIelementscanbechecked,ortheassertionmethodsoftheclass
ViewAssertscanalsobeinvoked.AsimpleexampleofaUItestforourexampleisshown
asfollows:
publicvoidtestUI(){
assertNotNull("Hourtextviewnotfound",mHour);
assertEquals("Wrongbuttonlabel","Validate",mValidate.getText());
ViewAsserts.assertBottomAligned(mHour,mMinute);
}
TheactivityIntenttest
Thelasttestmethodwewillimplementisgoingtocheckwhetherthesecondactivityis
properlylaunched.First,theValidatebuttonisclickedtoexecutethecodethatwillcreate
Intentofthesecondactivity.ThegetStartedActivityIntentmethodwillreturnifany
Intentwaslaunched.Thecodesnippetforthetestmethodisasfollows:
publicvoidtestSecondActivityLaunch(){
mValidate.performClick();
IntenttriggeredIntent=getStartedActivityIntent();
assertNotNull("Intentwasnull",triggeredIntent);
Stringpayload=triggeredIntent.getExtras().getString("hour");
assertEquals("WrongdatapassedtoSecondActivity","00",payload);
}
Inthetestmethod,Intentischeckedtoevaluatewhetheritisnull.Furthermore,thedata
passedtothesecondactivitycanbeexaminedaswell.
Note
ThecreatedIntentisnotreallysenttothesystembecausetheactivityrunsinisolation.
Creatingafunctionaltest
AfunctionaltestevaluatestheactivityanditscommunicationwiththeAndroidsystem.
TheUIeventsorchangesinthelifecycleshouldbecheckedinafunctionaltest.Inthis
section,wewillcreateafunctionaltestforthemainactivityofourexampleproject.
CreateanewclassinthetestpackageofyourapplicationnamedMainActivityTest.This
classextendstheActivityInstrumentationTestCase2classandhastobeparameterized
withtheactivityundertest,shownasfollows:
publicclassMainActivityTestextends
ActivityInstrumentationTestCase2<MainActivity>{
publicMainActivityTest(){
super(MainActivity.class);
}
Forthisexampleoffunctionaltests,wewillevaluatetheUI(white-boxtesting),launchof
thesecondactivity,andstatemanagement.
Thefunctionaltestsetup
Thefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthe
layoutobjectsthatwillbeusedinthetestmethods,shownasfollows:
privateMainActivitymActivity;
privateTextViewmHour,mMinute;
privateButtonmValidate;
privateEditTextmName;
Unlikeunittesting,thegetActivity()methodisenoughtostarttheactivityundertest.
ThesetUpmethodcodeisshownasfollows:
@Override
protectedvoidsetUp()throwsException{
super.setUp();
setActivityInitialTouchMode(false);
mActivity=getActivity();
mHour=(TextView)mActivity.findViewById(R.id.tvHour);
mMinute=(TextView)mActivity.findViewById(R.id.tvMinute);
mValidate=(Button)mActivity.findViewById(R.id.bValidate);
mName=(EditText)mActivity.findViewById(R.id.etName);
}
ThesetActivityInitialTouchModemethodsetstheinitialtouchmodefortheactivity.
Settingthemodeasfalseisnecessarytosetoffthetouchmodeinthedevicesothatthe
keyeventsarenotignored.Thismethodshouldbecalledbeforestartingtheactivitywith
thegetActivitymethodandalsobecauseitcannotbeexecutedontheUIthread.
TheUItest
Inthefirsttestmethod,asanexampleofUItesting,wewillevaluateEditTextcontaining
thenameofthealarm.Thestepstobeimplementedforthistestareasfollows:
1. Requestthefocusoftheedittextelement.ThisstepinteractswithViewofthe
applicationandtherefore,itshouldrunintheUIthread,thatis,themainthreadofthe
application.TorunsomecodeintheUIthread,youcanusetherunOnUiThread()
methodoftheactivityundertest.
2. Sendkeyeventstowritethealarmname.Onlyaninstrumentedclassallowstosend
keyeventstotheactivityundertest.Thankstoinstrumentation,itisnotnecessaryto
runthesecallsintheUIthreadeither.
3. Testthatthetextoftheeditfieldisthesameasexpected.
TheUItestmethodisshownasfollows:
publicvoidtestEditTextName(){
mActivity.runOnUiThread(newRunnable(){
publicvoidrun(){
mName.requestFocus();
}
});
sendKeys(KeyEvent.KEYCODE_A);
sendKeys(KeyEvent.KEYCODE_L);
sendKeys(KeyEvent.KEYCODE_1);
getInstrumentation().waitForIdleSync();
assertEquals("Wrongalarmname","al1",mName.getText().toString());
}
ThewaitForIdleSyncmethodiscalledtowaitfortheapplicationtobeidle.Thus,we
knowforsurethatthetexthasbeencompletelyinsertedinthefield.
TheactivityIntenttest
Unlikeunittests,whenanewIntentiscreated,itissenttotheAndroidsystem.To
monitorthelaunchedactivity,wecanregisteranActivityMonitorobjectusing
instrumentation.Anotherdifferencebetweenfunctionalandunittestsisthatina
functionaltest,wecanusetheTouchUtilslibrarytosendaclickeventonaUIelement,
shownasfollows:
publicvoidtestSecondActivityLaunch(){
Instrumentation.ActivityMonitormonitor=
getInstrumentation().addMonitor(SecondActivity.class.getName(),null,
false);
TouchUtils.clickView(this,mValidate);
SecondActivitysecondActivity=(SecondActivity)
monitor.waitForActivityWithTimeout(2000);
assertNotNull(secondActivity);
getInstrumentation().removeMonitor(monitor);
sendKeys(KeyEvent.KEYCODE_BACK);
}
Ourcodeperformsthefollowingstepsforthistestmethod:
1. Createstheactivitymonitor.
2. SendsaclickeventtotheValidatebutton.
3. Whenthemonitorreceivesthelaunchedactivity,itverifiesthattheactivitywas
launched.
4. Deletesthemonitor.
5. Closesthesecondactivitybysendingaclickeventtothedevice’sbackbutton.
Thestatemanagementtest
Thislasttestmethodcheckswhethertheactivitystateispreservedwhentheactivityis,for
example,pausedorrestarted.Forthisexample,wewillevaluatehowourmainactivity
behaveswhenitispausedandresumed.Theexpectedbehavioristhatthehoursand
minutesaremaintained.Performingareliabletestisnecessarytodirectlychangethetext
viewsbetweenthepausingandresumingoftheactivity.Thischangeensuresthatthe
activityactuallyrestoresthepreviousstate.Thecodeofthismethodisasfollows:
@UiThreadTest
publicvoidtestStateManagement(){
mHour.setText("02");
assertEquals("02",mHour.getText());
getInstrumentation().callActivityOnPause(mActivity);
mHour.setText("11");
getInstrumentation().callActivityOnResume(mActivity);
assertEquals("02",mHour.getText());
}
[email protected]with
@UiThreadTestareexecutedintheUIthread.Intheprevioustestmethod,thesetText
[email protected]st
annotationisnotadded,youhavetousetherunOnUiThread()methodinstead.
Gettingtheresults
WealreadyhaveanapplicationandtwotestcasescreatedinourAndroidproject.The
structureoftheprojectcanbeseeninthefollowingscreenshot.Runtheapplicationonce
tocheckthattherearenoerrorsandinstalltheapplicationonthedevice.Inthissection,
wewillberunningthetestcasesandexaminingtheresults.
InAndroidStudio,selectthepackagecontainingthetestcases.Clickonitusingtheright
mousebutton,andselecttheRun‘Testsin<your_package>’option.Inthebottompart
ofAndroidStudio,opentheRuntabtoseethetestexecution.Ontheleftpartofthistab,
youcaninspectthetestexecutionstate.Fromthebuttonsontheleftside,youcanstopthe
testexecutionorrerunit.Thenextscreenshotshowstheinitialstateofthetestsbeing
initialized.Ontherightpartofthetab,thecommandsandresultsarelistedintheconsole.
Whileatestmethodisbeingexecuted,itisalsorevealedontheleftpanelalongwithits
executionstatesuchaswhetherthetestisstillbeingevaluated,andwhetherthetestwas
passedornotpassed.Whenthetestexecutioniscompleted,alltheresultsaredisplayed.
BydeselectingtheHidePassedicon(highlightedinthepreviousscreenshot),youcansee
allthetestmethods.Overtheconsole,acolorbarisalsoshowningreenorredtoindicate
whetherallthetestswerepassedorwhethertherewereanyfails.Inourexample,allthe
testswerepassedasyoucanseeinthefollowingscreenshot:
Trytoinsertanerrorinanytestmethod,forexample,bychangingthefollowinglineof
codefromthetestStateManagement()testmethod:
assertEquals("30",mMinute.getText());
Changetheprecedinglineofcodetothefollowing:
assertEquals("40",mMinute.getText());
Runthetestsandnoticethatnowthefailisindicatedintheresults.Thefollowing
screenshotshowshowthefailisdisplayed:
Summary
Inthischapter,youlearnedmoreaboutAndroidtesting.Younowunderstandthestructure
oftheAndroidtestingAPIandweknowitsmainclassesandmethods.Youalsolearned
abouttheimportanceofinstrumentationtotestactivitiesoftheAndroidapplications.We
setupthetestingenvironmentusingAndroidStudioandfollowedthecompleteprocessof
testing.
Inthenextchapter,youwilllearnaboutsomeexternaltoolsdifferentfromAndroid
Studio.ThesetoolswillhelpussecureandtestourAndroidapplications.
Chapter10.SupportingTools
Inthischapter,youwilllearnabouttheexternaltoolsdifferentfromthoseavailablein
AndroidStudiothatwillhelpustestourAndroidapplications.Thechapterwillcovertest
toolstoperformunitandfunctionaltests.Itwillalsocovertoolsthathelpussecureour
applicationindifferentways.Wewillendthischapterwithanalternativetoolthatallows
youtoemulateanAndroiddevice.
Thetopicsthataregoingtobecoveredinthischapterare:
ToolsforunittestingAndroidapplications
ToolsforfunctionaltestingAndroidapplications
ToolsforsecuringAndroidapplications
Someothertools
Toolsforunittesting
AswehaveseeninChapter9,UnitandFunctionalTests,unittestingisperformedwith
minimalconnectiontothesysteminfrastructureandteststhedifferentcomponentsin
isolation.WewillseedifferenttoolsthatallowustoeasilyperformunittestsonAndroid
applications.Theyareasfollows:
Spoon
Mockito
AndroidMock
FESTAndroid
Robolectric
Spoon
Spoonisnotanewformofunittesting.Instead,itmakesuseoftheexistingunittesting
instrumentationsuchasJUnittoruntestsonmultipledevices.WithSpoon,youcantest
yourapplicationonmanydevicesatthesametime.Whenthetestiscompleted,youwill
receiveasummarygeneratedbySpoonwithalltheinformationregardingthetest
performedonthedevices.YoucanalsouseSpoonforfunctionaltesting.
ForadevicetobeconsideredbySpoontoruntestson,ithastobevisibletotheAndroid
DebugBridge(adb)devices.Youcanevenperformthetestsondifferenttypesofdevices
atthesametime,suchassmartphones,tablets,phablets,andsoon,andindifferent
versionsofAndroid.Thegreaterthediversityofthedevices,themoreusefulthesummary
willbe.Withabigsampleofdevices,youcanfindmorepotentialissuestobeaddressed.
Wecanseeanexamplewitheightdevicesinthefollowingfigure:
Ifyouwanttoaccessthesummaryofthetestingperformedonasingledevice,youcando
itwiththeDeviceView.SpoonmakesaDeviceViewavailableforeachdeviceinthe
samplesothatyoucanseetheresultsofadeviceindividually.ToaccesstheDeviceView,
youcansimplyclickonthenameofadevice.Wecanseethisviewinthefollowing
figure:
Ifyouwanttoaccessthesummaryofaspecifictestperformedonallthedevicesinthe
sample,youcandoitthroughtheTestView.TheTestViewdisplaystheresultofasingle
testoneverydevice.Incaseofanerror,itwillshowtheinformationthatwasgeneratedby
theerror.ToaccesstheTestView,youcanclickontheiconwiththeshapeofa
smartphoneontheDeviceView.Wecanseeanexampleofthisviewinthefollowing
screenshot:
Ifyouwanttochecktheviewoftheapplicationatanypointintime,youcanusethe
Screenshotfeature.Thisfeatureallowsyoutotakeascreenshotoftheinformationbeing
displayedtotheuseratanygivenmomentduringtheexecution.Thescreenshotsare
availableinboththeDeviceViewifyouwanttoseeallthescreenshotstakeninasingle
device,andtheTestViewifyouwanttoseethescreenshotstakenofeachtestinevery
device.
Tomakeuseofthisfeature,youneedtoincludethespoon-client.jarlibraryinyour
application.Whenyouwanttotakeascreenshot,youcancallthestatic
screenshot(Activity,String)methodoftheSpoonclass,shownasfollows:
Spoon.screenshot(activity,"login_activity");
Note
IfyouwanttoknowmoreaboutSpoonorwanttodownloadthetool,youcanfollowthis
link:
http://square.github.io/spoon/
Mockito
MockitoisamocktestingframeworkforJavathatcanbeusedinconjunctionwithJUnit
andotherunittestingframeworks.IthasbeencompatiblewithAndroidsinceVersion
1.9.5.Mockitoallowstheuseofautomaticunittestingtoenhancethequalityofourcode.
Mostunittestingframeworksarebasedonanexpect-run-verifypattern.Mockito
removesthespecificationofexpectationsreducingthepatterntorun-verify.
Wealreadyknowthatunittestsareperformedoveranisolatedclass.Thismeansthattheir
interactionwithotherclassesshouldbeeliminatedwhenpossible.AsseeninChapter9,
UnitandFunctionalTests,youcanachievetheseinteractionsusingmockobjectsalso
knownasstubs.Mockitoallowsyoutocreatemockobjectsusingthemock()method.
[email protected]
MockitoAnnotationsclass.YoucancalltheMockitoAnnotations.initMocks()method
[email protected]
Theverify()methodcanbecalledonamockobjecttoverifythatacertainmethodwas
called.Tospecifyaconditionandareturnvaluewhentheconditionismet,youcanuse
thewhen()methodinconjunctionwiththethenReturn()method.
Forexample,let’ssaywewanttocheckwhetherthetestmethodwascalledinthe
followingcode:
//Createthemockobject
TestClasstestClassMock=Mockito.mock(TestClass.class);
//Callamethodonthemockobject
booleanresult=testClassMock.test("helloworld");
//Testthereturnvalue
assertTrue(result);
//Checkthatthemethodtest()wascalled
Mockito.verify(testClassMock).test("helloworld");
Mockitocannotbeusedtotestfinalclasses,anonymousclasses,andprimitivetypes.
Note
IfyouwanttolearnmoreaboutMockito,visititswebsite:
https://code.google.com/p/mockito/
AndroidMock
AndroidMockissimilartoMockito.AndroidMockisalsoaframeworktomockclasses
andinterfaces.ItworkswiththeAndroidDalvikVirtualMachine.ItisbasedontheJava
mockingframeworkEasyMockandusesthesamegrammarandsyntax.
InordertolearnaboutthegrammarandsyntaxofAndroidMock,wewillrepeatthesame
exampleaswedidwithMockito:
publicclassMockingTestextendsTestCase{
//Createthemockobject
@UsesMocks(TestClass.class)
TestClasstestClassMock=AndroidMock.createMock(TestClass.class);
//Tellsthemockobjectthatthemethodtestwillbecalledand
//thevaluetruewillbeexpected
AndroidMock.expect(testClassMock.test("helloworld")).andReturn(true);
//Makethemockobjectreadytobetested
AndroidMock.replay(testClassMock);
//Testthereturnvalue
assertTrue(testClassMock.test("helloworld"));
//Testthatthemethodtest()wascalled
AndroidMock.verify(testClassMock);
}
Asyoucansee,themaindifferenceinAndroidMockandMockitoisthatAndroidMock
followsthepatternexpectation-run-verify.
Note
IfyouwanttolearnmoreaboutAndroidMock,youcanvisittheprojectwebsite:
https://code.google.com/p/android-mock/.
FESTAndroid
FESTAndroidisalibrarythatextendstheFESTfunctionalitytoAndroid.FESTisaunit
testframeworkforJava.Itisbasicallyasimplerformofmakingassertions.Inthe
followingcode,weseethedifferencesbetweenJUnit,FEST,andFESTforAndroid:
//AssertionusingJUNIT
assertEquals(View.GONE,view.getVisibility());
//AssertionusingFEST
assertThat(view.getVisibility()).isEqualTo(View.GONE);
//AssertionusingFESTforAndroid
assertThat(view).isGone();
FESTforAndroidoffersassertionsthatareexecuteddirectlyonobjectsinsteadof
properties.Thismakesitpossibletochaintogetherseveralassertions,shownasfollows:
assertThat(layout).isVisible().isVertical().hasChildCount(3);
TherearemanyavailableassertionsfortypicalAndroidobjects,suchasLinearLayout,
ActionBar,Fragment,andMenuItem.
Note
IfyouwanttolearnmoreaboutFEST,youcanvisittheprojectwebsiteat
https://code.google.com/p/fest/.IfyouwanttolearnmoreaboutFESTforAndroid,you
canvisittheURLathttp://square.github.io/fest-android/.
Robolectric
RobolectricallowsyoutorununittestsofyourAndroidapplicationonyourworkstation’s
JavaVirtualMachine.Thishasonemainadvantage,thatis,speed.Runningunittestsin
AndroidmeansthattheapplicationneedstobeloadedeitherontheAndroidemulatoror
onyourdevice.
RobolectrictakesadifferentpaththanmockframeworkssuchasMockitoandinsteadof
mockingouttheAndroidSDK,RobolectricrewritestheAndroidSDKclassesandmakes
itpossibletorunthemonaregularJVM.Itcan,however,beusedinconjunctionwith
mockingtestingframeworkssuchasMockitoorAndroidMock.
[email protected],shownasfollows:
@RunWith(RobolectricTestRunner.class)
publicclassTest1{
//Yourtests
}
Note
IfyouwanttolearnmoreaboutRobolectric,youcanvisittheprojectwebsiteat
http://robolectric.org/.
Toolsforfunctionaltesting
InChapter9,UnitandFunctionalTests,youlearnedhowfunctionaltestsareperformed
withfullconnectiontothesysteminfrastructure.Inthissection,wewilllookatthe
differenttoolsthatallowustoeasilyperformfunctionaltestsinAndroidapplications:
Robotium
Espresso
Appium
Calabash
MonkeyTalk
Bot-bot
Monkey
Wireshark
Robotium
RobotiumrunsontheofficialAndroidtestingframework.Itaddsthenecessaryfeaturesto
runthroughanentireAndroidapplication.Ithasfullsupportforbothnativeandhybrid
applications.
Now,wewillseethestepsneededtorunatestusingRobotiumonourAndroid
application:
1. AddtheRobotiumJARtoyourBuildPath.
2. CreateatestcaseusingtheJUnitTestCaseclass.
3. Writethetestcasecode.
4. Runthetestcase.
TestswithRobotiumareperformedusingthecom.robotium.solo.Soloclassavailablein
theRobotiumlibrary.
Wewillnowseeanexampleofthewhite-boxtestingusingRobotium.Inthisexample,we
havetwoEditTextfields:onewheretheusercaninputanumericvalueValueEditText
andanotheronethatwilldisplaythevalueoftheinputmultipliedby2,ResultEditText.
ThemultiplicationismadewhentheButton1buttonisclicked:
publicclassTestMainextends
ActivityInstrumentationTestCase2<MainActivity>{
//DeclarationoftheSoloobject
privateSolomSolo;
//Constructor
publicTestMain(){
super(Main.class);
}
//SetUp
@Override
protectedvoidsetUp()throwsException{
super.setUp();
//InitiatetheinstanceofSolo
mSolo=newSolo(getInstrumentation(),getActivity());
}
//White-BoxTestCode
publicvoidtestWhiteBox(){
EditTextvalueEditText=(EditText)solo.getView(R.id.ValueEditText);
EditTextresultEditText=(EditText)solo.getView(R.id.ResultEditText);
//ClearstheEditText
mSolo.clearEditText(valueEditText);
//SetsthevalueoftheEditTextto10
mSolo.enterText(valueEditText,String.valueOf(10));
//ClicksonButton1
mSolo.clickOnButton("Button1");
//Asserttocheckifitworked
assertEquals(String.valueOf(20),
resultEditText.getText().toString());
}
}
Note
IfyouwanttolearnmoreaboutRobotium,youcanvisittheprojectwebsiteat
https://code.google.com/p/robotium/.IfyouwanttolearnhowtouseRobotium,we
recommendtheofficialgettingstartedguide:
https://code.google.com/p/robotium/wiki/Getting_Started.
Espresso
EspressoisanAPIthatletsyouteststateexpectations,assertions,andinteractions.There
aremanyactionsthatcanbeperformedwithEspressousingasimplesyntax.Let’ssee
howtheexampleweusedforRobotiumwillbeexecutedwithEspresso:
publicvoidtestWhiteBox(){
//Typethetext"10"intheValueEditText
onView(withId(R.id.ValueEditText)).perform(typeText("10"));
//ClickthebuttonButton1
onView(withId(R.id.Button1)).perform(click());
//Checkifthevaluedisplayedis"20"
onView(withText("20").check(matches(isDisplayed()));
}
TomakeuseoftheEspressolibraryinAndroidStudio,youneedtofollowthesesteps:
1. AddtheEspressoJARasalibrarydependency.
2. AddthisinstrumentationtoyourprojectAndroidManifest.xml:
<instrumentation
android:name="com.google.android.apps.common.testing.testrunner.GoogleI
nstrumentationTestRunner"android:targetPackage="YOUR_PACKAGE"/>
3. ConfigureteststorunwithGoogleInstrumentationTestRunner.
Note
IfyouwanttolearnmoreaboutEspresso,youcanvisittheprojectwebsiteat
https://code.google.com/p/android-test-kit/wiki/Espresso.Ifyouhave15minutesto
spare,werecommendtheirGoogleTestAutomationConference2013presentationat
https://www.youtube.com/watch?v=T7ugmCuNxDU.
Appium
Appiumisanopensourceframeworkthatallowsautomatedtesting.Appiumworkswith
bothnativeandhybridAndroidapplications.ItevenworkswithiOS.Appiumisagood
solutionifyouneedtotestinbothAndroidandiOS.
Note
TodownloadorjustlearnmoreaboutAppium,youcanvisittheirwebsiteat
http://appium.io/.IfyouwanttoseeexamplesforAppium,visittheirGitHubat
https://github.com/appium/appium/tree/master/sample-code/examples.
Calabash
JustlikeAppium,Calabashisalsoamultiplatformframeworkthatperformsautomated
tests.ItworkswithAndroidnativeapplications,hybridapplications,andiOSnative
applications.Calabashallowsyoutotakescreenshotsofthecurrentviewinadetermined
instant.OneofthethingsthatseparateCalabashfromtheothertestingframeworksisthat
itsupportsCucumber.Cucumberallowspeoplewithlessexpertiseinthismattertoeasily
definethebehavioroftheapplicationusingnaturallanguage,forexample:
WhenItouchthe"addition"button
ThenIshouldsee"20"
TheCalabashtoolisbasedonActivityInstrumentationTestCase2fromtheAndroid
SDK.
Note
IfyouwanttoknowmoreaboutCalabash,youcanvisittheprojectwebsite:
http://calaba.sh/.TolearnmoreabouttheCucumberproject,visittheirwebsite:
http://cukes.info/.
MonkeyTalk
MonkeyTalkisyetanothermultiplatformautomatedtestframework.MonkeyTalk
supportsmorefeaturesthanAppiumandCalabash.However,theversionwithevery
featureavailableisasubscription-licensedproductthatiscurrentlyofferedinafreebeta
versionbutwillbechargedwhenthebetaisover.
Note
IfyouwanttodownloadMonkeyTalkorjustlearnmoreaboutit,youcanvisittheproject
websiteathttp://www.cloudmonkeymobile.com/monkeytalk.Toseeanexampleusingthe
MonkeyTalkframeworkwithanAndroidapplication,watchthefollowingYouTube
video:https://www.youtube.com/watch?v=pjDGctTnThQ.
Bot-bot
Bot-botisanAndroidautomationtestingtoolwithtwointerestingfeatures:recordand
replay.Youdonotneedtoaddanykindoflibraryordependencytoyourproject,sincethe
onlythingbot-botneedsisanAPKoftheapplicationyouwanttotest.Therecordfeature
allowsyoutostorethesequenceofeventsthatweretriggered.Itworksbothona
simulatorandarealdevice.TherecordedtestcasescanbeexportedintheCSVformat
andreplayedusingthebot-bottool.
Bot-botconsistsofthreeelements:
Thebot-botserver:Thisserverisusedtostoreandmodifytheactionstakenonthe
Androidapplication.ItincludesasimpleHTMLinterfacethatallowsyoutoview
recordedsessions,viewrecordedentriesofasession,modifyorcreateassertions,
exportrecordedsessionsinCSV,anddeleterecordedsessions.
Thebot-botrecorder:ThisrecordertrackstheuseractionsontheAndroid
applicationthatarebeingtested,andsendsthesetaskstothebot-botserver.It
supportsrecordingofactionsonTextBoxes,Adapters,andSpinners.Italsorecords
clicksonelementsandviews.ItdoesnotsupportactionsonWebViews.
Thebot-botrunner:ThisrunnertakestheexportedsessionsintheCSVformatand
interpretsthem.Thebot-botrunnerthenexecutestheactionsontheAndroid
applicationandgeneratesanHTMLreportthatshowstheexecutionofthetestcases
defined.
ThefollowingscreenshotshowsanexampleofageneratedHTMLreportbythebot-bot
runner:
Bot-botisperfectlyintegratedwithRobotium.
Note
Ifyouwanttodownloadthebot-botapplication,youcanvisittheirwebsite:
http://imaginea.github.io/bot-bot/.Tolearnhowtousethebot-bottool,werecommendthe
officialGetStartedguide:http://imaginea.github.io/bot-bot/pages/get_started.html.
Monkey
Monkeyisacommand-linetoolthatrunsonyourAndroidemulatorordevice.Itgenerates
randomusereventsandsystem-leveleventstostresstestyourapplication.Althoughthe
interactionsarerandom,theyarebasedonaseedingsystemandthereforeyoucanrepeat
thesamesequenceofactionsusingthesameseed.Thisisimportantsinceotherwise,you
wouldnotbeabletorepeatthesequencethatproducedanerrortocheckwhetheritwas
fixed.
TherearefourmaincategoriesofoptionsinMonkey:
Basicconfigurationoptions:Anexampleofthiscanbethehelporverbositylevel
Operationalconstraints:Anexampleofthiscanbethepackagesinwhichthestress
testwillbeperformed
Eventtypes:Anexampleofthiscanbethenumberofevents,randomseed,and
delaybetweenevents
Debuggingoptions:Anexampleofthiscanbekillingtheprocessafteranerroror
ignoringthesecurityexceptions
TolaunchtheMonkey,youneedtouseacommandlineonyourdevelopmentmachine
shownasfollows:
adbshellmonkey–pcom.packt.package–v100
The–pargumentstatesthepackagewheretheMonkeywillsendrandomevents.The–v
parameterstatesthenumberofrandomeventsthatwillbesent.
Note
TherearemanyotherparametersforMonkey.Ifyouwanttolearnabouttheseparameters,
youcanvisittheofficialAndroidguide:
http://developer.android.com/tools/help/monkey.html.
Wireshark
Wireshark,formerlyknownasEthereal,isaprotocolanalyzerusedtoperformanalysis
andsolveproblemsrelatedtonetworkconnectivity.Itsfunctionalityissimilartothetool
tcpdump,butWiresharkprovidesamoreintuitiveGUI.
YoucanuseWiresharkincombinationwithyourAndroidemulatortocheckwhat
informationisbeingtransferredtoandfromyourAndroidapplication.Themainissue
withthistoolisthatyouneedtoknowwhatpackagestoexpect,sinceotherwisethetask
offilteringcanbecomereallydifficult.Thebestadvicewecangiveistoclosethebrowser
andotherprogramsinyourcomputerthatmaygeneratenetworktraffictokeepittoa
minimum.
Inthisbook,wealreadydiscussedWiresharkinChapter6,SecuringCommunications.
OneofthetopicswediscussedwasthatwecanuseWiresharktotestwhetherthedatawe
aresendingisbeingencryptedproperlyornot.OtheralternativestoWiresharkareFiddler
forWindowsandCharlesproxyforOSX.AscreenshotofWiresharkisshowninthe
followingfigure:
Note
IfyouwanttodownloadorlearnmoreaboutWireshark,visittheirwebsite:
http://www.wireshark.org/.
Othertools
Inthislastsection,wewillseeatoolthatisnotdirectlyrelatedtoapplicationtestingor
securitytesting.However,itcansignificantlyimproveourtestingexperience.
Genymotion
GenymotionisanalternativeandunofficialAndroidemulator.Itisbasicallyavirtual
emulatorthatcreatesavirtualimageofAndroidandisoftenconsideredmuchfasterthan
theofficialAndroidemulator.ItisavailableforWindows,Linux,andMacOS.Ifyouare
usingWindowsorLinux,youonlyneedtoinstalltheGenymotiondistributionpackage.
However,ifyouareusingMacOS,youneedtodownloadandinstallVirtualBox
manually.Thefollowingisascreenshotcapturedfromthevirtualdevicemanagerthatlists
allthevirtualdevicesavailable:
Note
IfyouwanttogetstartedwithusingGenymotion,youcanvisitourblog:
http://belencruz.com/2014/01/first-look-at-genymotion-android-emulator/.Todownload
andlearnmoreaboutGenymotion,visittheprojectwebsite:http://www.genymotion.com/.
IfyouareusingMacOSandneedtodownloadVirtualBox,followthislink:
https://www.virtualbox.org/.
Summary
Inthischapter,youlearnedabouttheexternaltoolsthathelpusperformtestsonour
Androidapplications.Thechaptercoveredseveralautomatedunittestingtoolsandseveral
automatedfunctionaltestingtools.Youalsolearnedhowtostresstestourapplications
usingMonkeyandwhattoolswewillneedifwewanttocheckthenetworkconnectivity
ofourapplication.AnalternativeAndroidemulatorthatisinmostcasesfasterthanthe
officialonewasreviewedtoo.
Inthenextchapter,whichisthelastchapter,youwilllearnaboutsometipsthatarevery
usefulfordevelopers.Youwillalsolearnhowtogethelpincaseyouneedit.
Chapter11.FurtherConsiderations
Thischapterprovidessomefurtherconsiderationsthatareusefulfordevelopers.Wewill
reviewwhatarethemostimportantpartsofourapplicationthatweneedtotest.This
chapteralsocontainsinformationabouthowtogethelpformoreadvancedtopics.
Thetopicsthatwillbecoveredinthischapterare:
Whattotest
Developeroptions
Gettinghelp
Whattotest
Inthepreviouschapters,youlearnedabouttheAndroidtestingAPIworkingwithAndroid
Studio.ApartfromknowingaboutactivityandUItesting,consideringwhatpartsofyour
applicationshouldbeevaluatedisalsoimportant.
Networkaccess
Ifyourapplicationdependsonthenetworkaccess,youshouldexaminethebehaviorof
yourapplicationwhendifferentnetworkstatesaregiven.Considerthefollowing
suggestions:
Ifyourapplicationcompletelydependsonthenetworkwhenitislaunchedandthere
isnonetworkaccess,itshouldatleastshowadefaulthomescreen.Yourapplication
shouldnotshowablankscreenwithanyinformationonit.Lettheuserknowthat
he/sheshouldreviewthedeviceconnectivity.Thenetworkstatecanbecheckedusing
theConnectivityManagerclassinthefollowingcode:
ConnectivityManagerconnManager=(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfonetInfo=connManager.getActiveNetworkInfo();
if(netInfo!=null&&netInfo.isConnected()){
//Connect
}else{
//displaydefaultscreen
}
Whenthereareproblemsaccessingthenetworkthataffectthenormalbehaviorof
yourapplication,lettheuserknowthisbydisplayingamessage.
Whenperforminglongnetworkoperations,theusershouldalsobeabletouseyour
application.Checkthatyourapplicationcontinuesworkingproperlyevenwhile
performinglongnetworkoperations.
Yourapplication’sdatashouldmaintainitsconsistency.Ifyourapplicationsendsor
receivesanykindofinformationtoorfromyourserver,thisinformationshouldbe
correctlysynchronized.Checkthatyourapplicationandservercanrecoverfroma
networkfailureandmaintaintheconsistencyofyourapplication’sdata.
Tomitigatenetworkfailures,yourapplicationcancachesomeoftheinformation.
Checkthemanagementofthecachedinformationanditsusagewhenthereisno
networkaccess.
Agoodpolicyistochangethebehaviorofyourapplicationdependingonthetypeof
networkaccess,forexample,itshouldbeabletodetectwhetherthedeviceis
connectedtoaWi-Fior3Gnetworkandworkaccordingly.Youshouldtestwhether
yourapplicationfollowsthedefinedpolicyandwhetheritisabletoreacttochanges
intheconnectiontype.Theconnectiontypecanbecheckedusingthefollowingcode:
booleanwifiConnected=netInfo.getType()==
ConnectivityManager.TYPE_WIFI;
booleanmobileConnected=netInfo.getType()==
ConnectivityManager.TYPE_MOBILE;
Ifthereisanetworkfailure,yourapplicationshouldretryafterawhile.Youshould
checkwhichbehaviorisappropriateforyourapplicationandwhetheritiscapableof
recoveringfromfailures.
Mediaavailability
Ifyourapplicationdependsonexternalmedia,yourcodeshouldchecktheavailabilityof
thatmedia.Whiledesigningyourtests,youshouldevaluatewhetheryourapplication
behavescorrectlyifthemediaisnotavailable.
Forexample,ifyourapplicationworkswithanexternalstorage,youcancheckitsstateby
usingtheEnvironment.getExternalStorageStatemethod,asitwasshowninChapter5,
PreservingDataPrivacy.Totesttheexternalstorageavailability,youcanconfigurethe
AVDtorunontheemulatorfromAndroidStudio,asitisshowninthefollowing
screenshot:
Changeinorientation
Ifadevicesupportsmultipleorientations,yourapplicationshouldbepreparedforthe
same.Youhavetodecidewhetheryourapplicationwillblocktheorientationchangesor
not.Ifyourapplicationsupportsorientationchanges,considerthefollowingsuggestions:
Whenthereisanorientationchange,thecurrentactivityisdestroyedandrestarted.
Checkthattheactivitystateismaintained.Forexample,ifyouractivitycontainsan
inputfieldthattheusercanedit,itscontenthastobepreservedwhenthedevice
orientationchanges.
YourUIshouldalsoadapttothedevice’scurrentorientation.Thepositionand
distributionofyourUIelementsaredifferentonaportraitorientationthanona
landscapeone.YoushouldcheckthatthedesignofyourUIisperfectlydisplayedin
boththeorientations.
YoucanchangetheemulatororientationbypressingCtrl+F11inWindowsorLinux,or
Fn+Ctrl+F11inMacOS.Tochecktheorientationchanges,youcanoverridethe
onConfigurationChangedmethodofyouractivities,shownasfollows:
@Override
publicvoidonConfigurationChanged(ConfigurationnewConfig){
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
…
}elseif(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
…
}
}
Serviceandcontentprovidertesting
InAndroid,wecantesttheUI,activities,services,andcontentproviders.InChapter9,
UnitandFunctionalTests,activitytestingwasexplained.Butyoushouldnotforgetabout
servicestestingandcontentproviderstesting.TheclassesintheAndroidtestingAPIused
toevaluateservicesandcontentprovidersarelistedinthefollowingfigure:
TheAndroidTestCaseclassanditssubclassesbelongtotheandroid.testpackage.It
representsatestcasetobeusedintheAndroidenvironment.Sincethisclassisgeneric,
youshoulduseoneofitssubclasses.TheProviderTestCase2classisusedtotestcontent
providers.TheServiceTestCaseclassisusedtotestservices.
Developeroptions
TheAndroidsystemprovidesasetofon-devicedeveloperoptionsthatwillhelpyoutest
yourapplication.TheseoptionsareavailableintheSettingsmenuofanyAndroiddevice.
OnAndroid4.2andhigher,thedeveloperoptionsarehidden.ClickontheAboutphone
optionintheSettingsmenuandclickontheBuildnumberseventimestomakethem
available.ThefollowingscreenshotshowstheDeveloperoptionsinAndroid’sSettings
menu:
TheDeveloperoptionsareorganizedintosevencategories,describedasfollows:
General:Thisoptionisnotpresentinanycategory.Forexample,youcangetabug
reportbyselectingtheTakebugreportoption.
Debugging:Thiscategoryincludesusefultoolstodebugyourapplication.For
example,whenyouwanttotestyourapplicationonarealdevice,youshouldcheck
theUSBdebuggingoptioncontainedinthiscategory.Youcanalsoselectadebug
app(Selectdebugapp)orallowmocklocations(Allowmocklocations).
Input:Thiscategorycontainstwotools.TheseareShowtouchestoprovideavisual
feedbackfortouchesonthescreen,andPointerlocationtooverlaythetouchdataon
thescreen.
Drawing:Thiscategoryincludesoptionstochangethegraphicalbehaviorofthe
applicationandthesystemitself,suchasShowsurfaceupdates,Showlayout
bounds,ForceRTLlayoutdirection,andSimulatesecondarydisplays.Youmay
wanttodisableanimationsthattakeplacewhenanapplicationisopened.Todoso,
youcansettoAnimationoffthefollowingoptions:Windowanimationscale,
Transitionanimationscale,andAnimatordurationscale.
Hardwareacceleratedrendering:Inthissection,youcanchangethebehaviorof
theGraphicsProcessingUnit(GPU).TheoptionsavailableareForceGPU
rendering,ShowGPUviewupdates,Showhardwarelayersupdates,Debug
GPUoverdraw,Debugnon-rectangularclipoperation,Force4xMSAA,and
DisableHWoverlays.
Monitoring:Thiscategorycontainsoptionsthatallowyoutotrackpossible
problemsormalfunctions.TheoptionsavailableareStrictmodeenabled,Show
CPUusage,ProfileGPUrendering,andEnableOpenGLtraces.
Apps:Thiscategoryincludesoptionstomanagethebehaviorofapplicationswhen
theyarerunninginthebackground.ActivatingDon’tkeepactivitieswilldestroy
everyactivitywhentheuserleavesit.Thebackgroundprocesslimitallowsyouto
controlthenumberofprocessesthatcanbeexecutedinthebackground.Ifyou
activatetheoptionShowallANRs,applicationswilldisplayadialogwhenthey
don’trespond.
Gettinghelp
IfyouwanttoaccesstheAndroidStudiodocumentation,youcandoitthroughtheIntelliJ
IDEAwebhelp.YoucangotoHelp|OnlineDocumentation,oraccessthewebpage
http://www.jetbrains.com/idea/documentation/.YoucanalsogotoHelp|HelpTopicsto
directlyopenthedocumentationcontentstree,orvisitthewebpage
http://www.jetbrains.com/idea/webhelp/intellij-idea.html.
Android’sofficialdocumentationisprovidedbyGoogleandisavailableat
http://developer.android.com/.TheAndroiddocumentationincludeseverykindofguideto
learnhowtoprogramAndroidapplications.Italsoincludesdesignguidelinesandeven
tipsondistributingandpromotingyourapplication.
Someoftheimportantreferencesofallthepreviouschaptersarelistedasfollows:
Chapter1,IntroductiontoSoftwareSecurity:
Glossaryoftermsathttp://www.sans.org/security-resources/glossary-of-terms/
Chapter2,SecurityinAndroidApplications:
Contentprovidersat
http://developer.android.com/guide/topics/providers/content-providers.html
Intentfiltersathttp://developer.android.com/guide/components/intentsfilters.html
Chapter3,MonitoringYourApplication:
DDMSathttp://developer.android.com/tools/debugging/ddms.html
Chapter4,MitigatingVulnerabilities:
ThePatternclassat
http://developer.android.com/reference/java/util/regex/Pattern.html
Storingdataathttp://developer.android.com/training/articles/securitytips.html#StoringData
Chapter5,PreservingDataPrivacy:
Cipherathttp://developer.android.com/reference/javax/crypto/Cipher.html
Storageoptionsathttp://developer.android.com/guide/topics/data/datastorage.html#filesInternal
Chapter6,SecuringCommunications:
Usingcryptographyathttp://developer.android.com/training/articles/securitytips.html#Crypto
SecuritywithHTTPSandSSLat
http://developer.android.com/training/articles/security-ssl.html
Chapter7,AuthenticationMethods:
AccountManagerat
http://developer.android.com/reference/android/accounts/AccountManager.html
Chapter8,TestingYourApplication:
UItestingathttp://developer.android.com/tools/testing/testing_ui.html
uiautomatorathttp://developer.android.com/tools/help/uiautomator/index.html
Chapter9,UnitandFunctionalTests:
Creatingunittestsathttp://developer.android.com/training/activitytesting/activity-unit-testing.html
Creatingfunctionaltestsathttp://developer.android.com/training/activitytesting/activity-functional-testing.html
ViewAssertsat
http://developer.android.com/reference/android/test/ViewAsserts.html
MoreAssertsat
http://developer.android.com/reference/android/test/MoreAsserts.html
Chapter10,SupportingTools:
Spoonathttp://square.github.io/spoon/
Mockitoathttps://code.google.com/p/mockito/
AndroidMockathttps://code.google.com/p/android-mock/
FESTAndroidathttp://square.github.io/fest-android/
Robolectricathttp://robolectric.org/
Robotiumathttps://code.google.com/p/robotium/
Espressoathttps://code.google.com/p/android-test-kit/wiki/Espresso
Appiumathttp://appium.io/
Calabashathttp://calaba.sh/
MonkeyTalkathttp://www.cloudmonkeymobile.com/monkeytalk
Bot-botathttp://imaginea.github.io/bot-bot/
Monkeyathttp://developer.android.com/tools/help/monkey.html
Wiresharkathttp://www.wireshark.org/
Genymotionathttp://www.genymotion.com/
Summary
Inthischapter,youlearnedaboutwhichpartsofourapplicationaremoreimportantto
evaluateandtest.WereviewedthedeveloperoptionsavailableinAndroidandhowto
accessthem.Wealsolearnedhowtogetadditionalhelpusingtheofficialdocumentation
andothersources.
Index
A
acceptancetests/Testingthebasics
accesscontrol,softwaresecurity/Softwaresecurityterms
AccountManagerclass
about/AccountManager
using/AccountManager
activity
about/Intents
Activity.runOnUiThread()method
about/UItestingandTouchUtils
ActivityInstrumentationTestCase2class
about/Thetestcaseclasses
activitylifecyclemethods/Instrumentation
activitytest
creating/Creatinganactivitytest
unittest,creating/Creatingaunittest
functionaltest,creating/Creatingafunctionaltest
executing/Gettingtheresults
ActivityTestCaseclass
about/Thetestcaseclasses
ActivityUnitTestCaseclass
about/Thetestcaseclasses
addMonitormethod/Instrumentation
AllocationTrackertab
displaying/AllocationTracker
Allpairstestingtechnique/Testingthebasics
Android
about/Themobileenvironment
Androidapplication
testing/TestinginAndroid
Androidapplicationpackage(APK)/Permissions
AndroidApplicationSandbox/AnoverviewofAndroidsecurity
AndroidDebugBridge(adb)/Spoon
Androidinstrumentation
about/Instrumentation
AndroidMock
about/AndroidMock
URL/AndroidMock
AndroidSDK
used,fortestingAndroidapplication/TestinginAndroid
Androidsecurity
overview/AnoverviewofAndroidsecurity
features/AnoverviewofAndroidsecurity
AndroidStudio
about/AndroidStudio
URL,fordocumentation/Gettinghelp
help,obtaining/Gettinghelp
AndroidVirtualDevice(AVD)
about/Theuiautomatorviewertool
API
about/Permissions
app
about/Themobileenvironment
Appium
about/Appium
URL,fordownloading/Appium,Calabash
applicationlayer
about/HTTPS
applicationsandboxing/AnoverviewofAndroidsecurity
Assertclass
about/TheAssertclassandmethod
ViewAssertsclass/TheViewAssertsclass
MoreAssertsclass/TheMoreAssertsclass
assertEqualsmethod/TheAssertclassandmethod
assertFalsemethod/TheAssertclassandmethod
assertmethod
about/TheAssertclassandmethod
assertEqualsmethod/TheAssertclassandmethod
assertTruemethod/TheAssertclassandmethod
assertFalsemethod/TheAssertclassandmethod
assertNullmethod/TheAssertclassandmethod
assertNotNullmethod/TheAssertclassandmethod
assertSamemethod/TheAssertclassandmethod
assertNotSamemethod/TheAssertclassandmethod
failmethod/TheAssertclassandmethod
assertNotNullmethod/TheAssertclassandmethod
assertNotSamemethod/TheAssertclassandmethod
assertNullmethod/TheAssertclassandmethod
assertSamemethod/TheAssertclassandmethod
assertTruemethod/TheAssertclassandmethod
asymmetriccryptography,softwaresecurity/Softwaresecurityterms
asymmetricencryption
about/Encryption
authentication,softwaresecurity/Softwaresecurityterms
authenticationfactors
knowledgefactor/Theknowledgefactor
possessionfactor/Thepossessionfactor
inherencefactor/Theinherencefactor
availability,softwaresecurity/Softwaresecurityterms
B
basispathtesting/Testingthebasics
biometricauthentication
about/Theinherencefactor
biometricidentifiers
physiologicalcharacteristics/Theinherencefactor
behavioralcharacteristics/Theinherencefactor
black-boxtesting
about/TestingtheUI
black-boxtests
about/Testingthebasics
black-boxtests,techniques
equivalencepartitioning/Testingthebasics
boundaryvalueanalysis/Testingthebasics
statetransitiontesting/Testingthebasics
allpairstesting/Testingthebasics
syntaxtesting/Testingthebasics
bot-bot
about/Bot-bot
server/Bot-bot
recorder/Bot-bot
runner/Bot-bot
URL,fordownloading/Bot-bot
bot-botrecorder
about/Bot-bot
bot-botrunner
about/Bot-bot
bot-botserver
about/Bot-bot
boundaryvalueanalysistechnique/Testingthebasics
broadcastmessages,types
normal/Intents
ordered/Intents
sticky/Intents
broadcastreceivers
about/Intents
bruteforce,softwaresecurity/Softwaresecurityterms
C
Calabash
about/Calabash
categories,developeroptions
General/Developeroptions
Debugging/Developeroptions
Input/Developeroptions
Drawing/Developeroptions
Hardwareacceleratedrendering/Developeroptions
Monitoring/Developeroptions
Apps/Developeroptions
Cause-effectgraphingtechnique/Testingthebasics
certificate
about/Serverandclientcertificates
creating/Serverandclientcertificates
using/Serverandclientcertificates
certificate.crtfile/Keytoolintheterminal
CertificateAuthority(CA)/CodeexamplesusingHTTPS
certificates
about/AnoverviewofAndroidsecurity
Cipher,softwaresecurity/Softwaresecurityterms
codeinjection,softwaresecurity/Softwaresecurityterms
confidentiality,softwaresecurity/Softwaresecurityterms
Console
about/DebuggingandDDMS
contentprovider
testing/Serviceandcontentprovidertesting
contentproviders
about/Contentproviders
URL,forofficialdocumentation/Contentproviders
securing/Securingthecontentproviders
securing,precautions/Securingthecontentproviders
controlflowtesting/Testingthebasics
crack,softwaresecurity/Softwaresecurityterms
cryptographickeys
about/Thepossessionfactor
D
.dbfile
about/Thedatabasestorage
dangerouspermissionlevel
about/Permissions
data
storing,encryptionused/Usingencryptiontostoredata
databasestorage
about/Thedatabasestorage
DataEncryptionStandard(DES)
about/SSLandTLS
dataflowtesting/Testingthebasics
dataprivacy
about/Dataprivacy
DDMS
about/DebuggingandDDMS
debugger
about/DebuggingandDDMS
debugging
about/DebuggingandDDMS
decryption,softwaresecurity/Softwaresecurityterms
Denial-of-service(DoS)/Softwaresecurityterms
developeroptions
about/Developeroptions
categories/Developeroptions
DeviceView
about/Spoon
Dictionaryattack/Softwaresecurityterms
Distributeddenial-of-service(DDoS)/Softwaresecurityterms
doFinalmethod
about/Encryption
E
electroniccommerce(e-commerce)/Softwaresecurityterms
EmulatorControltab
about/EmulatorControl
TelephonyStatus/EmulatorControl
TelephonyActions/EmulatorControl
LocationControls/EmulatorControl
encryption/Softwaresecurityterms
about/Encryption
symmetricencryption/Encryption
asymmetricencryption/Encryption
key,generating/Generatingakey
used,forstoringdata/Usingencryptiontostoredata
encryptionmethods
using/Theencryptionmethods
Equivalencepartitioningtechnique/Testingthebasics
Espresso
about/Espresso
referencelink/Espresso
exclusivetime/Methodprofiling
expect-run-verifypattern/Mockito
externalstorage
about/Filesintheexternalstorage
publicfiles/Filesintheexternalstorage
privatefiles/Filesintheexternalstorage
F
fabrication,threat/Threat
failmethod/TheAssertclassandmethod
features,Androidsecurity
application-definedpermissions/AnoverviewofAndroidsecurity
interprocesscommunication/AnoverviewofAndroidsecurity
supportforsecurenetworking/AnoverviewofAndroidsecurity
supportforcryptography/AnoverviewofAndroidsecurity
encryptedfilesystem/AnoverviewofAndroidsecurity
applicationsigning/AnoverviewofAndroidsecurity
FEST
referencelink/FESTAndroid
FESTAndroid
about/FESTAndroid
URL/FESTAndroid
FileExplorertab
about/FileExplorer
FTP
about/HTTPS
functionaltest
creating/Creatingafunctionaltest
settingup/Thefunctionaltestsetup
UItestmethod,implementing/TheUItest
activityIntenttestmethod,implementing/TheactivityIntenttest
statemanagementtestmethod,implementing/Thestatemanagementtest
functionaltesting
about/Testingactivities
tools,using/Toolsforfunctionaltesting
G
garbagecollector(GC)
about/Heap
Genymotion
about/Genymotion
URL/Genymotion
getAccountsByNamemethod
about/AccountManager
getActivity()method
about/Instrumentation,Theunittestsetup
getContentResolver().query()method
about/Contentproviders
getContentResolver().query()method,parameters
contentURI/Contentproviders
projection/Contentproviders
selection/Contentproviders
selectionarguments/Contentproviders
sortorder/Contentproviders
getInstrumentation()method
about/Instrumentation
getPreferences()method
about/Sharedpreferences
getSharedPreferences()method
about/Sharedpreferences
getTargetContextmethod/Instrumentation
getUiDevice()method
about/TheUiDeviceclass
GraphicsProcessingUnit(GPU)/Developeroptions
H
hashfunction/Softwaresecurityterms
Heaptab
displaying/Heap
help,AndroidStudio
obtaining/Gettinghelp
Hijackattack/Softwaresecurityterms
HTTP
versus,HTTPS/HTTPS
HTTPS
about/HTTPS
versus,HTTP/HTTPS
SSL/SSLandTLS
TLS/SSLandTLS
certificate,creating/Serverandclientcertificates
Keytool/Keytoolintheterminal
AndroidStudio/AndroidStudio
examples/CodeexamplesusingHTTPS
HypertextTransferProtocolSecure(HTTPS)/Softwaresecurityterms
I
inclusivetime/Methodprofiling
inherencefactor
about/Theknowledgefactor,Theinherencefactor
initmethod/Encryption
inputvalidation
about/Inputvalidation
SQLinjection/SQLinjection
instrumentation
about/Instrumentation
Instrumentationclass
URL,fordocumentation/Instrumentation
addMonitormethod/Instrumentation
activitylifecyclemethods/Instrumentation
getTargetContextmethod/Instrumentation
startActivitySyncmethod/Instrumentation
waitForIdleSyncmethod/Instrumentation
InstrumentationTestCaseclass
about/Thetestcaseclasses
integrationtests/Testingthebasics
integrity,softwaresecurity/Softwaresecurityterms
intents
about/Intents
URL,forofficialdocumentation/Intents
Intents
securing/SecuringIntents
vulnerabilities/SecuringIntents
Intentspoofing
about/SecuringIntents
interapplicationcommunication
about/Interapplicationcommunication,Interapplicationcommunication
intents/Intents
contentproviders/Contentproviders
Intents,securing/SecuringIntents
contentproviders,securing/Securingthecontentproviders
interception,threat/Threat
internalstorage
about/Filesintheinternalstorage
InternationalMobileStationEquipmentIdentity(IMEI)
about/Dataprivacy
InternetAssignedNumbersAuthority(IANA)
about/Inputvalidation
internetlayer
about/HTTPS
interruption,threat/Threat
J
JavaDevelopmentKit(JDK)
about/Serverandclientcertificates
JUnit
about/TestinginAndroid
JVM
about/TestinginAndroid
Androidapplication,testingon/TestinginAndroid
K
key
generating,forencryption/Generatingakey
KeyGeneratorclass/Generatingakey
Keytool
about/Serverandclientcertificates,Keytoolintheterminal
keytoolcommand
-genkeyparameter/Keytoolintheterminal
-keyalgparameter/Keytoolintheterminal
-aliasparameter/Keytoolintheterminal
-keystoreparameter/Keytoolintheterminal
-storepassparameter/Keytoolintheterminal
-validityparameter/Keytoolintheterminal
-keysizeparameter/Keytoolintheterminal
knowledgefactor
username/password/Theknowledgefactor
pattern/Theknowledgefactor
PIN/Theknowledgefactor
L
linklayer
about/HTTPS
LogCat
about/DebuggingandDDMS
loginimplementations
about/Loginimplementations
M
Man-in-the-middleattack/Softwaresecurityterms
MD5,softwaresecurity/Softwaresecurityterms
MediaAccessControl(MAC)/HTTPS
mediaavailability
testing/Mediaavailability
methodprofilingtool
about/Methodprofiling
mobileenvironment
about/Themobileenvironment
mock()method/Mockito
Mockito
about/Mockito
URL/Mockito
mockobjectclasses
about/Themockobjectclasses
MockApplicationclass/Themockobjectclasses
MockContextclass/Themockobjectclasses
MockContentProviderclass/Themockobjectclasses
MockCursorclass/Themockobjectclasses
MockDialogInterfaceclass/Themockobjectclasses
MockPackageManagerclass/Themockobjectclasses
MockResourcesclass/Themockobjectclasses
MockContentResolverclass/Themockobjectclasses
modeflag,internalstorage
MODE_PRIVATE/Filesintheinternalstorage
MODE_APPEND/Filesintheinternalstorage
MODE_WORLD_READABLE/Filesintheinternalstorage
MODE_WORLD_WRITEABLE/Filesintheinternalstorage
modification,threat/Threat
Monkey
about/Monkey
basicconfigurationoptions/Monkey
operationalconstraints/Monkey
eventtypes/Monkey
debuggingoptions/Monkey
URL,forparameters/Monkey
MonkeyTalk
about/MonkeyTalk
URL,fordownloading/MonkeyTalk
MoreAssertsclass/TheAssertclassandmethod
about/TheMoreAssertsclass
assertContainsRegex()method/TheMoreAssertsclass
assertContentsInAnyOrder()method/TheMoreAssertsclass
assertContentsInOrder()method/TheMoreAssertsclass
assertEmpty()method/TheMoreAssertsclass
assertEquals()method/TheMoreAssertsclass
assertMatchesRegex()method/TheMoreAssertsclass
URL/TheMoreAssertsclass
multifactorauthentication
about/Multifactorauthentication
MyPrefsFilefile/Sharedpreferences
MyReadablePrefsFilefile/Sharedpreferences
MyWriteablePrefsFilefile/Sharedpreferences
my_keystore.jksfile/Keytoolintheterminal
N
networkaccess
testing/Networkaccess
NetworkStatisticstab
displaying/NetworkStatistics
normalbroadcast
about/Intents
normalpermissionlevel
about/Permissions
O
onCreatemethod/Instrumentation
openFileOutput()method
about/Filesintheinternalstorage
opensourcesoftware(OSS)
about/HTTPS
operatingmode,sharedpreferences
MODE_PRIVATE/Sharedpreferences
MODE_WORLD_READABLE/Sharedpreferences
operatingsystem(OS)
about/Themobileenvironment
orderedbroadcast
about/Intents
orientationchanges
testing/Changeinorientation
OSImodel
about/HTTPS
versus,TCP/IPmodel/HTTPS
P
-pparameter/Monkey
password,softwaresecurity/Softwaresecurityterms
pattern
about/Theknowledgefactor
Patternclass
DOMAIN_NAMEpattern/Inputvalidation
EMAIL_ADDRESSpattern/Inputvalidation
IP_ADDRESSpattern/Inputvalidation
PHONEpattern/Inputvalidation
TOP_LEVEL_DOMAINpattern/Inputvalidation
WEB_URLpattern/Inputvalidation
PBKDF2algorithm/Usingencryptiontostoredata
permissionlevel
normal/Permissions
dangerous/Permissions
signature/Permissions
signatureOrSystem/Permissions
permissions
about/Permissions,Permissions
phishing,softwaresecurity/Softwaresecurityterms
physicallayer
about/HTTPS
PIN
about/Theknowledgefactor
possessionfactor
about/Thepossessionfactor
privatefiles
about/Filesintheexternalstorage
publicfiles
about/Filesintheexternalstorage
R
regularexpressions
URL,fordocumentation/Inputvalidation
resourceIdmethod/TheUItestproject
risk,softwaresecurity
about/Softwaresecurityterms,Risk
Robolectric
about/Robolectric
URL/Robolectric
Robotium
about/Robotium
referencelink/Robotium
S
Screenshotfeature
about/Spoon
SecretKeySpecclass/Generatingakey
securecode-design,principles
securedefaults/Securecode-designprinciples
leastprivileges/Securecode-designprinciples
clarity/Securecode-designprinciples
smallsurfacearea/Securecode-designprinciples
strongdefense/Securecode-designprinciples
failingsecurely/Securecode-designprinciples
third-partycompanies,nottrusting/Securecode-designprinciples
simplicity/Securecode-designprinciples
Addressvulnerabilities/Securecode-designprinciples
SecureRandomclass/Generatingakey
securitytesting
about/Testingthebasics
white-boxtests/Testingthebasics
black-boxtests/Testingthebasics
sensitivedata
about/Dataprivacy
service
about/Intents
services
testing/Serviceandcontentprovidertesting
setUp()method
about/Thetestcasemethods
SHA1,softwaresecurity/Softwaresecurityterms
sharedpreferences
about/Sharedpreferences
signatureOrSystempermissionlevel
about/Permissions
signaturepermissionlevel
about/Permissions
smartphone
about/Themobileenvironment
vulnerabilities/Themobileenvironment
SMTP
about/HTTPS
sniffingattack,softwaresecurity/Softwaresecurityterms
spoofingattack/Softwaresecurityterms
Spoon
about/Spoon
URL,fordownloading/Spoon
spoon-client.jarlibrary
about/Spoon
SQL
about/Contentproviders
SQLinjection
about/SQLinjection
SSL
about/HTTPS,SSLandTLS
SSL3.0
about/SSLandTLS
SSLconnection
establishing/SSLandTLS
SSLHandshakeException
about/CodeexamplesusingHTTPS
startActivitySyncmethod/Instrumentation
Statementcoverage/Testingthebasics
Statetransitiontestingtechnique/Testingthebasics
stickybroadcast
about/Intents
storageoptions
sharedpreferences/Dataprivacy,Sharedpreferences
internalstorage/Dataprivacy,Filesintheinternalstorage
externalstorage/Dataprivacy,Filesintheexternalstorage
databasestorage/Dataprivacy,Thedatabasestorage
symmetriccryptography/Softwaresecurityterms
symmetricencryption
about/Encryption
Syntaxtestingtechnique/Testingthebasics
SystemInformationtab
about/SystemInformation
systemtests/Testingthebasics
T
TCP/IPmodel
about/HTTPS
physicallayer/HTTPS
linklayer/HTTPS
internetlayer/HTTPS
transportlayer/HTTPS
applicationlayer/HTTPS
versus,OSImodel/HTTPS
tcpdump/Wireshark
tearDown()method
about/Thetestcasemethods
terms,softwaresecurity
accesscontrol/Softwaresecurityterms
asymmetriccryptography/Softwaresecurityterms
authentication/Softwaresecurityterms
authorization/Softwaresecurityterms
availability/Softwaresecurityterms
bruteforce/Softwaresecurityterms
Cipher/Softwaresecurityterms
codeinjection/Softwaresecurityterms
confidentiality/Softwaresecurityterms
crack/Softwaresecurityterms
decryption/Softwaresecurityterms
Denial-of-service(DoS)/Softwaresecurityterms
Distributeddenial-of-service(DDoS)/Softwaresecurityterms
Dictionaryattack/Softwaresecurityterms
encryption/Softwaresecurityterms
hashfunction/Softwaresecurityterms
Hijackattack/Softwaresecurityterms
HypertextTransferProtocolSecure(HTTPS)/Softwaresecurityterms
Integrity/Softwaresecurityterms
MD5/Softwaresecurityterms
Man-in-the-middleattack/Softwaresecurityterms
passwords/Softwaresecurityterms
phishing/Softwaresecurityterms
risk/Softwaresecurityterms
SHA1/Softwaresecurityterms
Sniffingattack/Softwaresecurityterms
spoofingattack/Softwaresecurityterms
symmetriccryptography/Softwaresecurityterms
threat/Softwaresecurityterms
vulnerability/Softwaresecurityterms
TestCaseclass
about/Thetestcaseclasses
setUp()method/Thetestcasemethods
tearDown()method/Thetestcasemethods
testcaseclasses
about/Thetestcaseclasses
TestCaseclass/Thetestcaseclasses
InstrumentationTestCaseclass/Thetestcaseclasses
ActivityTestCaseclass/Thetestcaseclasses
ActivityInstrumentationTestCase2class/Thetestcaseclasses
ActivityUnitTestCaseclass/Thetestcaseclasses
testcasemethods
about/Thetestcasemethods
testing,Androidapplication
onJVM/TestinginAndroid
AndroidSDK,using/TestinginAndroid
testing,contentprovider
about/Serviceandcontentprovidertesting
testing,mediaavailability
about/Mediaavailability
testing,networkaccess
about/Networkaccess
testing,orientationchanges
about/Changeinorientation
testing,services
about/Serviceandcontentprovidertesting
testingactivities
functionaltesting/Testingactivities
unittesting/Testingactivities
testcaseclasses/Thetestcaseclasses
instrumentation/Instrumentation
testcasemethods/Thetestcasemethods
Assertclass/TheAssertclassandmethod
assertmethod/TheAssertclassandmethod
UItesting/UItestingandTouchUtils
TouchUtils/UItestingandTouchUtils
mockobjectclasses/Themockobjectclasses
testinglevels
unittests/Testingthebasics
integrationtests/Testingthebasics
validationtests/Testingthebasics
systemtests/Testingthebasics
acceptancetests/Testingthebasics
TestView
about/Spoon
Threadstab
about/Threads
threat
about/Softwaresecurityterms,Threat
interception/Threat
interruption/Threat
modification/Threat
fabrication/Threat
three-factorauthentication
about/Multifactorauthentication
Time-basedOne-TimePassword(TOTP)
about/Thepossessionfactor
TLS
about/HTTPS,SSLandTLS
tools
Genymotion/Genymotion
tools,functionaltesting
Robotium/Toolsforfunctionaltesting,Robotium
Espresso/Toolsforfunctionaltesting,Espresso
Appium/Toolsforfunctionaltesting,Appium
Calabash/Toolsforfunctionaltesting,Calabash
MonkeyTalk/Toolsforfunctionaltesting,MonkeyTalk
Bot-bot/Toolsforfunctionaltesting
Monkey/Toolsforfunctionaltesting,Monkey
Wireshark/Toolsforfunctionaltesting,Wireshark
bot-bot/Bot-bot
tools,unittesting
Spoon/Toolsforunittesting,Spoon
Mockito/Toolsforunittesting,Mockito
AndroidMock/Toolsforunittesting,AndroidMock
FESTAndroid/Toolsforunittesting,FESTAndroid
Robolectric/Toolsforunittesting,Robolectric
TouchUtils
about/UItestingandTouchUtils
TouchUtilsclass
clickViewmethod/UItestingandTouchUtils
dragmethod/UItestingandTouchUtils
dragQuarterScreenDownmethod/UItestingandTouchUtils
dragViewBymethod/UItestingandTouchUtils
dragViewTomethod/UItestingandTouchUtils
dragViewToTopmethod/UItestingandTouchUtils
longClickViewmethod/UItestingandTouchUtils
scrollToTopmethod/UItestingandTouchUtils
scrollToBottommethod/UItestingandTouchUtils
TrafficStatsclass
about/NetworkStatistics
transportlayer
about/HTTPS
TrustManagerclass/CodeexamplesusingHTTPS
two-factorauthentication
about/Multifactorauthentication
U
@UiThreadTest()method
about/UItestingandTouchUtils
uiautomator.jarlibrary
about/TheuiautomatorAPI
uiautomatorAPI
about/TestingtheUI,TheuiautomatorAPI
UiDeviceclass/TheUiDeviceclass
UiSelectorclass/TheUiSelectorclass
UiObjectclass/TheUiObjectclass
UiCollectionclass/TheUiCollectionclass
UiScrollableclass/TheUiScrollableclass
uiautomatorviewertool
about/Theuiautomatorviewertool
UiCollectionclass
about/TheUiCollectionclass
getChildByDescription(UiSelectorchildPattern,Stringtext)method/The
UiCollectionclass
getChildByInstance(UiSelectorchildPattern,intinstance)method/The
UiCollectionclass
getChildByText(UiSelectorchildPattern,Stringtext)method/TheUiCollection
class
getChildCount(UiSelectorchildPattern)method/TheUiCollectionclass
UiDeviceclass
about/TheUiDeviceclass
click(intx,inty)method/TheUiDeviceclass
getDisplaySizeDp()method/TheUiDeviceclass
pressBack()method/TheUiDeviceclass
pressHome()method/TheUiDeviceclass
sleep()method/TheUiDeviceclass
takeScreenshot(Filestorepath)method/TheUiDeviceclass
wakeUp()method/TheUiDeviceclass
UiObjectclass
about/TheUiObjectclass
click()method/TheUiObjectclass
exists()method/TheUiObjectclass
getText()method/TheUiObjectclass
isChecked()method/TheUiObjectclass
setText(Stringtext)method/TheUiObjectclass
UiScrollableclass
about/TheUiScrollableclass
scrollBackward()method/TheUiScrollableclass
scrollForward()method/TheUiScrollableclass
scrollToBeginning()method/TheUiScrollableclass
scrollToEnd()method/TheUiScrollableclass
UiSelectorclass
about/TheUiSelectorclass
checked(booleanval)method/TheUiSelectorclass
childSelector(UiSelectorselector)method/TheUiSelectorclass
className(StringclassName)method/TheUiSelectorclass
resourceID(Stringid)method/TheUiSelectorclass
text(Stringtext)method/TheUiSelectorclass
UItestcases
executing/RunningUItestcases
UItesting
about/TestingtheUI,UItestingandTouchUtils
white-boxtesting/TestingtheUI
black-boxtesting/TestingtheUI
uiautomatorAPI/TheuiautomatorAPI
uiautomatorviewertool/Theuiautomatorviewertool
UItestproject
creating/TheUItestproject
UIthread
about/Threads
unauthorizedIntentreceipt
about/SecuringIntents
unittest
creating/Creatingaunittest
settingup/Theunittestsetup
clocktestmethod,implementing/Theclocktest
layouttestmethod,implementing/Thelayouttest
activityIntenttestmethod,implementing/TheactivityIntenttest
unittesting
about/Testingactivities
tools,using/Toolsforunittesting
unittests/Testingthebasics
unknownCA
solving/CodeexamplesusingHTTPS
user’sdataandcredentials
handling/Handlingauser’sdataandcredentials
handling,considerations/Handlingauser’sdataandcredentials
userID(UID)/AnoverviewofAndroidsecurity
userinterface(UI)
about/Threads
username/password
about/Theknowledgefactor
V
-vparameter/Monkey
validationtests/Testingthebasics
values,methodprofilingtool
exclusivetime/Methodprofiling
inclusivetime/Methodprofiling
verify()method/Mockito
ViewAssertsclass/TheAssertclassandmethod
about/TheViewAssertsclass
URL/TheViewAssertsclass
assertBottomAligned()method/TheViewAssertsclass
assertLeftAligned()method/TheViewAssertsclass
assertRightAligned()method/TheViewAssertsclass
assertTopAligned()method/TheViewAssertsclass
assertGroupContains()method/TheViewAssertsclass
assertGroupNotContains()method/TheViewAssertsclass
assertHasScreenCoordinates()method/TheViewAssertsclass
assertHorizontalCenterAligned()method/TheViewAssertsclass
assertVerticalCenterAligned()method/TheViewAssertsclass
assertOffScreenAbove()method/TheViewAssertsclass
assertOffScreenBelow()method/TheViewAssertsclass
assertOnScreen()method/TheViewAssertsclass
VirtualBox
URL,fordownloading/Genymotion
vulnerabilities,Intents
unauthorizedIntentreceipt/SecuringIntents
Intentspoofing/SecuringIntents
vulnerabilities,smartphone/Themobileenvironment
vulnerability
about/Softwaresecurityterms,Vulnerability
improperauthentication/Vulnerability
bufferoverflow/Vulnerability
cross-sitescripting(XSS)/Vulnerability
Inputvalidation/Vulnerability
SQLinjection/Vulnerability
W
waitForIdleSyncmethod/Instrumentation
when()method/Mockito
white-boxtesting
about/TestingtheUI
white-boxtests
about/Testingthebasics
white-boxtests,techniques
controlflowtesting/Testingthebasics
dataflowtesting/Testingthebasics
basispathtesting/Testingthebasics
statementcoverage/Testingthebasics
Wireshark
URL/HTTPS
about/Wireshark
URL,fordownloading/Wireshark
X
X.509certificate
version/Serverandclientcertificates
serialnumber/Serverandclientcertificates
signaturealgorithm/Serverandclientcertificates
issuer/Serverandclientcertificates
validity/Serverandclientcertificates
subject/Serverandclientcertificates
subjectpublickey/Serverandclientcertificates
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement