TestingandSecuringAndroidStudioApplications
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
TestingandSecuringAndroidStudioApplications
TestingandSecuringAndroidStudioApplicationsCopyright©2014PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:August2014
Productionreference:1190814
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78398-880-8
www.packtpub.com
CoverimagebyRavajiBabu(<[email protected]>)
CreditsAuthors
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
AbouttheAuthorsBelénCruzZapatareceivedherengineeringdegreeinComputerSciencefromtheUniversityofMurciainSpain,withspecializationinsoftwaretechnologiesandintelligentandknowledgetechnologies.ShehasearnedanMScdegreeinComputerScienceandisnowworkingonherPhDdegreeinSoftwareEngineeringResearchGroupfromtheUniversityofMurcia.
BelénisbasedinSpain;however,duetothefieldofherPhD,sheisnowcollaboratingwithUniversitéMohammedV-SoussiinRabat.Herresearchisfocusedonmobiletechnologiesingeneralandalsoappliestomedicine.
Belénhasworkedasamobiledeveloperforseveralplatforms,suchasAndroid,iOS,andtheWeb.SheistheauthorofthebookonAndroidStudio:AndroidStudioApplicationDevelopment,PacktPublishing.
Tofollowherprojects,shemaintainsablogathttp://www.belencruz.comandyoucanfollowheronTwitterat@belen_cz.
IwouldliketothankPacktPublishingforofferingmetheopportunitytowritethisbook.IwouldparticularlyliketothankParitaKhedekar,RebeccaYoué,andAmeySawantfortheirvaluablehelp.
IwouldalsoliketothankAntonio,theco-authorofthisbook,formakingeverythingsoeasy;mynewfriendsofadventure,especiallyPaloma,Camilla,andAdrián,fortheselastmonths;myfriendsfromwaybackforvisitingme;andfinally,myfamilyforsupportingme.
AntonioHernándezNiñirolahasanengineeringdegreeinComputerScienceandisamobileapplicationdeveloper.HewasbornandraisedinMurciainthesoutheastregionofSpainandiscurrentlylivinginRabat,Morocco.Hehasdevelopedseveralwebsitesandmobileapplications.
AftercompletinghisdegreeinComputerScience,hepursuedaMaster’sdegreeinTeacherTrainingforInformaticsandTechnology.AntoniopushedhisstudiesfurtherandisnowadoctoralcandidateundertheSoftwareEngineeringResearchGroupofthefacultyofComputerScienceattheUniversityofMurcia,andisactuallyaresearcherfortheUniversitéMohammedV-SoussiinRabat.
Youcanvisithiswebsiteathttp://www.ninirola.estofindoutmoreabouthimandhisprojects.
IwouldliketobeginbythankingRebeccaYoué,ParitaKhedekar,andAmeySawantfortheirvaluableinput.ThankyoutoeveryoneatPacktPublishingwhomakewritingabooksuchanenjoyableexperience.
ThankyouBelén,theotherhalfofthisbook,formakingeverythingmuchbetter.Iwouldfinallyliketothankmyfamilyfortheirsupport,mynewfriendsinMorocco,myoldfriendsinSpain,andeveryonewhohelpedmebewhoIamtoday.
AbouttheReviewersNicoKüchlerlivesinBerlin,Germany.Hedidanapprenticeshipasamathematical-technicalsoftwaredeveloper.Hehasworkedforthegambleindustryandasanonlineshopprovider.HehasbeenworkingatDeutschePostE-POSTDevelopmentGmbHfor2yearswithinthescopeofAndroidappdevelopment.
Hehasbeenmaintainingaprojectthatprovidesaquickstartwithtest-drivenAndroidappdevelopmentathttps://github.com/nenick/android-gradle-template.
AnandMohanisageekandastart-upenthusiast.HegraduatedfromtheIndianInstituteofInformationTechnology,Allahabad,in2008.HehasworkedwithOracleIndiaPvt.Ltd.for4years.In2012,Anandstartedhisownventure,TripTern,alongwithhisfriends,whichisacompanythatalgorithmicallyplansoutthemostoptimizedtravelitineraryfortravelersbyutilizingBigDataandmachine-learningalgorithms.AtTripTern,AnandhasdevelopedandimplementedofflineAndroidapplicationssothattravelerscanmodifytheiritineraryonthegowithoutrelyingonanydataplan.
Apartfromworkingonhisstart-up,Anandalsolikestofollowthelatesttrendsintechnologyandbestsecuritypractices.
RaviShankerhasalwaysbeenfascinatedwithtechnology.He’sbeenapassionatepractitionerandanavidfollowerofthedigitalrevolution.HelivesinSydney,Australia.Helovestraveling,presenting,reading,andlisteningtomusic.Whennottinkeringwiththetechnology,healsowieldsasetofbrushesandpaletteofcolorstoputtherightsideofhisbraintowork.
Ravihashonedhisskillsoveradecadeindevelopment,consulting,andproductandprojectmanagementforstart-upstolargecorporationsinairline,transportation,telecom,media,andfinancialservices.HehasworkedintheUSA,UK,Australia,Japan,andmostofAsia-Pacific.Hehasalsorunacoupleofstart-upsofhisowninthepast.
Raviisoftenseenblogging,answeringoraskingquestionsonStackExchange,postingorupvoting,andtweetingonthelatestdevelopmentsindigitalspace.Hehasmadepresentationsatmeetingsandinterestgroupsandhasconductedtrainingclassesonvarioustechnologies.He’salwaysexcitedattheprospectofnewandinnovativedevelopmentsinimprovingthequalityoflife.
AbhinavaSrivastavahascompletedhisBachelorofTechnologydegreeinComputerScienceEngineeringfromIndiain2008andhasalsoreceivedaDiplomainWirelessandMobileComputingfromACTS,C-DAC,Indiain2009.
HestartedhiscareerasaSoftwareEngineeratPersistentSystemsbeforemovingtoSingapore,andiscurrentlyworkingwithMasterCard,Singapore.
Abhinavaisacoretechnologistbyheartandlovestoplaywithopensourcetechnologies.Hemaintainshisownblogathttp://abhinavasblog.blogspot.in/andkeepsjottinghisthoughtsfromtimetotime.
Iwouldliketothankmyfamilymembersfortheircontinuoussupport,especiallymyelder
brother,AbhishekSrivastava,whohasbeenamentorandaninspiration.Lastbutnotleast,IwouldliketoextendmygratitudetoPacktPublishingforgivingmetheopportunitytobeapartofsuchawonderfulexperience.
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmoreYoumightwanttovisitwww.PacktPub.comforsupportfilesanddownloadsrelatedtoyourbook.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewsletters,andreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
http://PacktLib.PacktPub.com
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcanaccess,readandsearchacrossPackt’sentirelibraryofbooks.
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,printandbookmarkcontentOndemandandaccessibleviawebbrowser
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
PrefaceMobileapplicationshavebecomeverypopularinthelastfewyearsthankstoahugeincrementintheuseofmobiledevices.Fromadeveloper’spointofview,Androidhasbecomeanimportantsourceofincomethankstothedifferentapprepositories,suchasGooglePlayandAmazonAppstore.
Withanincreaseinthenumberofapplicationsavailable,usershavebecomemoredemandingaboutthefeaturesoftheapplicationstheyaregoingtouse.Asolidtestingoftheapplicationanditssecurityaspectsarethekeyfactorsinthepursuitofsuccessforanapplication.BugsandsecurityissuesareobviouslynotfeaturesthathelpyourapplicationdowellintheincreasinglymoreexigentmarketofAndroid.
Inthisbook,youaregoingtolearnhowtoturnyourAndroidapplicationintoasolidlydebuggedandsecureapplication.Toachievethis,youwilllearnhowtouseAndroidStudioanditsmostimportantfeatures:testingandsecurity.
WhatthisbookcoversChapter1,IntroductiontoSoftwareSecurity,introducestheprinciplesofsoftwaresecurity.
Chapter2,SecurityinAndroidApplications,describesthedistinctivefeaturesfoundinmobileenvironmentsandtheAndroidsystem.
Chapter3,MonitoringYourApplication,presentsthedebuggingenvironment,oneofthemostimportantfeaturesofanIDE.
Chapter4,MitigatingVulnerabilities,describesthemeasuresthatshouldbetakentopreventattacks.
Chapter5,PreservingDataPrivacy,presentsthemechanismsofferedbyAndroidtopreservetheprivacyofuserdata.
Chapter6,SecuringCommunications,explainsthemechanismsofferedbyAndroidtosecurecommunicationsbetweenanAndroidapplicationandanexternalserver.
Chapter7,AuthenticationMethods,presentsdifferenttypesofauthenticationmethodsusedinAndroidmobiledevices.
Chapter8,TestingYourApplication,introduceswaystotestanapplicationusingAndroidStudio.
Chapter9,UnitandFunctionalTests,coversunitandfunctionalteststhatallowdeveloperstoquicklyverifythestateandbehaviorofanactivityonitsown.
Chapter10,SupportingTools,presentsasetofexternaltoolsdifferentfromAndroidStudiotohelpdeveloperstestanAndroidapplication.
Chapter11,FurtherConsiderations,providessomefurtherconsiderationsthatareusefulfordevelopers.
WhatyouneedforthisbookForthisbook,youneedacomputerwithaWindows,MacOS,orLinuxsystem.YouwillalsoneedtohaveJavaandtheAndroidStudioIDEinstalledonyoursystem.
WhothisbookisforThisbookisaguidefordeveloperswithsomeAndroidknowledge,butwhodonotknowhowtotesttheirapplicationsusingAndroidStudio.Thisbookissuitablefordeveloperswhohaveknowledgeaboutsoftwaresecuritybutnotaboutsecurityinmobileapplications,andalsofordeveloperswhodonothaveanyknowledgeaboutsoftwaresecurity.It’sassumedthatyouarefamiliarwithAndroidanditisalsorecommendedtobefamiliarwiththeAndroidStudioIDE.
ConventionsInthisbook,youwillfindanumberoftextstylesthatwillhelpyoudistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Tosendanorderedbroadcast,youcancallthesendOrderedBroadcastmethod.”
Ablockofcodeissetasfollows:
Instrumentation.ActivityMonitormonitor=
getInstrumentation().addMonitor(SecondActivity.class.getName(),null,
false);
Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:
@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,inmenusordialogboxesforexample,appearinthetextlikethis:“ThemultiplicationismadewhentheButton1buttonisclicked.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitlethroughthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/support,selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.
PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.
QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.
Chapter1.IntroductiontoSoftwareSecurityYouwanttolearnhowtoimproveyourAndroidapplicationssothatthey’resecureandrobust.Youwouldliketolearnaboutmobilesoftwaresecurityanditsmostimportantthreatsandvulnerabilities.Youwantyouruserstobesatisfiedwhileensuringthattheirdataissecureandthattheapplicationhasnobugs.Canyoudothiseasily?Whatdoyouneedtodoinordertoachievethis?
Thischapterwillteachyouthebasicsofsoftwaresecurity.We’llbeginbyteachingyouthedifferentsecuritytermsthatwewilluseinthisbook.You’llseethemostimportantthreatsandvulnerabilitiesthatmayaffectyourapplication.You’llthenlearnaboutsecurecodedesignprinciples,aswellashowtotestourapplicationforsecurityissues.
Inthischapter,wewillcoverthefollowingtopics:
SoftwaresecuritytermsThreats,vulnerabilities,andrisksSecurecodedesignprinciplesSecuritytesting
SoftwaresecuritytermsInrecentyears,theInternethasexperiencedahugeincreaseinelectroniccommerce(e-commerce).Thisincreaseinmonetizationofinformationinthecloudmeansthatattackerscannowberewardedfinancially,socially,andevenpoliticallyforasuccessfulattack.Thereisalowriskinattemptingtheseattacks,sincethereisasmallchanceofgettingcapturedandtherefore,ofprosecution.Withamoremotivatedenemy,companiesandenterpriseshavetoimprovetheirsecuritymeasurestofacethesenewthreats.Theymustidentifythethreatsanddefendthevulnerabilitiesthatmayaffectthedatathathasabigimpactontheirbusiness.
Inordertounderstandthecontentofthisbookcompletely,youwillfirstneedtounderstandsomebasicconceptsaboutsoftwaresecurity:
Accesscontrol:Thisensuresselectiveaccesstoresourcesbyusersthatareentitledtoit.Asymmetriccryptography:Thisisalsoknownasthepublickeycryptographyandusesalgorithmsthatemployapairofkeys—onepublicandoneprivate.Apublickeyisusedtoencryptthedatawhileaprivatekeyisusedtodecryptdata.Authentication:Thisisaprocessthroughwhichwecanconfirmtheidentityofauser.Authorization:Thisisaprocessthroughwhichwegivesomeonepermissiontodoorhavesomething.Availability:Thismeansthatthesystemanddataareavailabletoauthorizeduserswhentheymaymakeuseofit.Bruteforce:Thisisaverybasicandnonoptimalcryptanalysistechniquethattrieseverypossibilitytocrackakeyorapassword.Cipher:Thisisacryptographicalgorithmthatmaybeusedforencryptionanddecryption.Codeinjection:Thisisanattackwherethecodeisinsertedintoapplicationqueries.ThiskindofattackiscommonlyusedtoalterdatabasesviaSQLinjections.Confidentiality:Thisspecifiesthatthedataisonlyavailableforuserswhohavepermissiontoaccessit.Crack:Thisistheprocessthroughwhichanattackerattemptstogainaccesstoamachine,network,orsoftware.Decryption:Thisistheprocessthroughwhichanencryptedmessageistransformedintoitsoriginalstate.Denial-of-service(DoS):Thisisatypeofattackthatmakesanonlineresourceunavailableforafixedamountoftime.Distributeddenial-of-service(DDoS):ThistypeofattackissimilartotheDoSattack,butitisperpetratedfromseveralmachinesandisgenerallymoreeffectivethanaDoSattack.Dictionaryattack:Thisisabasiccryptanalysistechniquethatusesallthewordsinadictionarywhentryingtocrackakeyorpassword.Encryption:Thisisaprocessthroughwhichaplainpieceofdataistransformedinto
anencryptedstate,withtheobjectiveofconcealingthisinformationinordertopreventaccessfromunwantedsources.Hashfunction:Thisisatypeofalgorithmthatmapsdataofdifferentsizesintodataofafixedsize.Hijackattack:Thisisaformofattackinwhichanalreadyestablishedcommunicationisseizedandactsasoneoftheoriginalparticipants.HypertextTransferProtocolSecure(HTTPS):ThisisanapplicationlevelprotocolbasedonHTTPthatallowsasecuretransferofsensitiveinformationintheformofhypertext.Integrity:Thismeansthattheinformationisaccurateandisnotchangedaccidentallyordeliberately.MD5:Thisisaverycommonlyusedhashfunction.Man-in-the-middleattack:Thisisatypeofattackwheretheattackerassumesapositioninthemiddleofacommunication,interceptsandreadsthemessagesofacommunication,andletsthevictimsbelievethattheyaredirectlyconnectedtoeachother.Password:Thisisastringofcharactersusedforauthentication.Phishing:Thisisanattackattemptthatappearstobefromareliablesourceandtrickstheuserintoenteringtheirauthenticationcredentialsinadifferentdomainorapplication.Risk:Thisisthelikelihoodofanattackhappeningandsucceeding.SHA1:Thisisacommonlyusedhashfunction.Sniffingattack:Thisisanattackthatanalysesthepacketsexchangedinanetworkinordertoextractusefulinformationfromthem.Spoofingattack:Thisisanattackwhereanunauthorizedentitygainsaccesstoasystemwiththecredentialsofanauthorizeduser.Symmetriccryptography:Thisisatypeofcryptographythatusesthesamekeyforencryptionanddecryption,andtherefore,everyentitysharesthesamekey.Threat:Thisisacircumstancethatcouldbreachsecurityandcauseharmtothesystem.Vulnerability:Thisisaweaknessthatallowsforathreattooccur.
Threats,vulnerabilities,andrisksTherearethreekeytermsthatyouneedtounderstand.Theyweredefinedintheprevioussection,butwewilltalkalittlebitmoreaboutthemsincetheyarecommonlymixedup.Thesetermsarethreat,risk,andvulnerabilityandtheyarediscussedinthefollowingsections.
ThreatAthreatisanythingthatmayexploitvulnerabilityinordertoaccess,modify,ordestroyinformation.Athreatisthesourceandtypeofanattackandiswhatwetrytodefendagainst.Threatassessmentsareusedtodeterminethebestwaytodefendagainstadeterminedclassofthreat.
Whenweconsideracommunicationbetweentwoauthorizedentities,asource(S)andadestination(D),threatscanbecategorizedintothefollowingfoursegments:
Interception:Thishappenswhenanattackingentityhasanaccesstoacommunicationbetweentwoauthorizedentities.Theentitiesdonotrealizethatinterceptionishappeningandkeeponwiththeircommunicationnormally.Interruption:Thisreferstowhentheattackingentityinterceptsthecommunication.Thesourceentitymaynotrealizethisishappening,whilethedestinationentityhasnoknowledgeofthecommunicationattempt.Modification:Thishappenswhentheattackingentitychangestheinformationsentbetweenthetwoauthorizedentities.Thedestinationentitydoesnotrealizethattheinformationhasbeentamperedwithbytheattackingentity.Fabrication:Thishappenswhentheattackingentityactslikethesourceentity.Thedestinationentityacknowledgesthecommunicationasifitwasproducedbythesourceentity.
VulnerabilityVulnerabilityisaweaknessoraflawinthesecuritysystemofourapplicationthatmaybeusedbyadeterminedthreattoaccess,modify,ordestroyinformation.Vulnerabilitytestingismandatoryandshouldbeperformedrepeatedlytoensurethesecurityofourapplication.
Whenahumanorasystemtriestoexploitvulnerability,itisconsideredtobeanattack.Someofthemostcommonkindsofvulnerabilitiesthatcanbeexploitedtodamageoursystemareasfollows:
Improperauthentication:Thishappenswhenanentityclaimsthatithasbeenauthenticatedandthesoftwaredoesnotcheckwhetherthisistrueorfalse.Thisvulnerabilityaffectsoursystemofaccesscontrol,sinceanattackercanevadetheauthenticationprocess.Averycommonexampleofexploitingthisvulnerabilityismodifyingacookiewhichhasafieldthatdetermineswhethertheuserisloggedin.Settingloggedintotruecancheatthesystemintobelievingthattheentityisalreadyloggedinandisthereforegrantedaccesswhenitshouldnotbegranted.Bufferoverflow:Thishappenswhenthesoftwarehasaccesstoadeterminedamountofmemorybuttriestoreadabufferoutofthelimits.Forexample,ifthesoftwarehasabufferofsizeNbuttriestoreadthepositionN+2,itwillreadinformationthatmaybeusedbyanotherprocess.Thisgrantsaccessandevenmodifiestheinformationthatbelongstoapartofthememorywherethesoftwareshouldnothaveaccess.Cross-sitescripting(XSS):Thisisakindofvulnerabilitythatallowsathird-partytoinjectcodeinoursoftware.Itisespeciallycommoninwebsites,butitalsoappliestocertainmobileapplications.ThemostcommonlyusedexamplesofXSSaretheaccesstocookiesfromadifferentsiteandtheinjectionofJavaScriptintoadifferentsite.Inputvalidation:Whenreadinginformationprovidedbytheuser,itisalwaysagoodideatovalidatethedata.Notvalidatingthedatamayresultinanattackerintroducingcertainunexpectedvaluesthatcancauseanissueinthesystem.SQLinjection:Thisisakindofinputvalidationvulnerability.Itisverycommontouseasearchfeatureinalmostanyapplication.ThestringthattheuserintroducesinthesearchfieldisthenintroducedinaSQLsentence.Ifthereisnoanalysisandfilterofthestringprovidedbytheuser,anattackercouldwriteaSQLquerythatwouldbeexecuted.Ifthisiscombinedwithabadaccesscontrol,theattackercouldevendeletethewholedatabase.
RiskAriskisthepotentialforanattackhappeningandbeingsuccessful.Themoresensitivetheinformation,thehighertheriskofattack,asitcancauseahigherlevelofdamagetooursystem.Risksaretheresultofathreatexploitingvulnerabilityandaccessing,modifying,ordestroyingapieceofinformationthatwewanttobeprotected.Riskassessmentsareperformedtoidentifythemostcriticaldangersandtoevaluatethepotentialdamage.Thispotentialdamageiscalculatedthroughastatebetweenthecostofabreachhappening,whichdependsonhowsensitivetheinformationis,andtheprobabilityofthatevent,whichdependsonthethreatsandvulnerabilitiesthatmayaffecttheapplication.
Asyoucansee,thereisaveryimportantrelationshipbetweenthesethreeterms;especiallywhentryingtocorrectlyidentifytheriskthattheinformationstoredsuffers.Assessingthreatsanddetectingvulnerabilitiesiscrucialtotheprotectionoftheinformationinourapplication.
Securecode-designprinciplesInordertoreducethenumberofvulnerabilitiesofyourapplication,agoodsecuritydesignismandatory.Therearemanystandardsandguidelinesthatrecommenddifferentprocessestoproducesecureapplications.Inthissection,wearegoingtoidentifythemostimportantprinciplesthatyoushouldfollowwhendesigningyourapplication:
Securedefaults:Securityisoftheutmostimportanceforanaverageuser.Whendesigningyourapplication,youshouldmakesurethatthemostdemandinguserisgoingtobesatisfiedand,therefore,yourapplicationshouldofferthebestsecuritymethodsavailable.However,therearesomeuserswhomaypreferaccessibilityoversecurityandmaywanttoreducethelevelofsecurity.Forexample,youmaywanttoaddpasswordagingtoyourauthenticationsystem.Thismeansthateveryestablishedperiodoftime,theusersshouldchangetheirpasswordtoanewone.Thismeansanadditionallevelofsecuritybutcanbeannoyingforcertainusers.Addinganoptioninthepreferencestoturnoffthisfeaturecanbeagoodidea.However,alwaysmakesuretosetthedefaulttothemoresecuresetting,andlettheuserdecidewhethertheywanttoincreasetheriskofbreachingtheirinformation.Leastprivileges:Privilegesaresometimesconcededinexcessinordertospeeduptheprocessofdevelopment.Thisprinciplestatesthatyoushouldalwaysconcedetheleastprivilegesaspossibleinordertominimizesecurityrisks.Clarity:Nevertrustobscuritytoensurethesecurityofyourapplication.Concealingtheinformationonhowyoursecuritysystemworksisagoodidea,butitshouldnotbegrantedasenoughbyitself;thesecuritymustcomefromgoodcryptographictechniquesandagoodsecuritydesign.Smallsurfacearea:Ifyouknowyoumayhavevulnerabilityinadeterminedsectionofyourcode,youcantrytominimizetheriskofathreatexploitingitbyminimizingtheoveralluseofthissection.Forexample,ifyouthinkthatcertainfunctionalitymaybeexploited,youcanrestrictthisfunctionalitytoauthenticatedusers.Strongdefense:Whendefendingagainstacertainattack,theremaybedifferentmethodstouse.Onecontrolcansurelybeenoughbutsensitiveinformationdemandsextraordinarymeasures.Also,usingmorethanonemethodofprecautionismostofthetimesconvenient.Failingsecurely:Whendevelopingourapplication,weaimforthehighestrobustness.However,applicationsfailsometimesandweneedtoadaptourcodetomakesuretheapplicationfailssecurely.WhenprogrammingforAndroid,wecanaddressthisissuebycontrollingeveryexception,forexample,throughthecorrectusageoftryandcatch.Nottrustingthethird-partycompanies:Therearemanyservicesavailablethathavebeendevelopedbythethird-partycompanieswithdifferentprivacyandsecuritypolicies.Itisimportanttoknowthatwhileusingoneoftheseservices,youtrustthecompaniesonhowtheyuseyourinformation.Theprincipleofnottrustingthethird-partycompaniesrecommendsthatyoushouldonlytrustanexternalservicewiththeminimalamountofinformationpossibleandalwaysimpliesacertainleveloftrust
withthem.Simplicity:Alwaystrytokeepyoursecuritycodesimple.Althoughitisrecommendedtousecodepatterns,whentalkingaboutsecurity,thesafestandmorerobustwayisitssimplicity.Addressvulnerabilities:Whenyoudetectvulnerability,itisimportanttoaddressthisissuecorrectly.Youneedtounderstandboththevulnerabilityandthethreatandthenactaccordingly.
TestingthebasicsAsstatedbyBorisBeizer,authorofthebookSoftwareTestingTechniques,DreamtechPress:
“Bugslurkincornersandcongregateatboundaries.”
Securitytestingcanbedefinedasaprocessthroughwhichwefindvulnerabilitiesorflawsinoursecuritysystem.Althoughwemaydoexhaustivesecuritytesting,itdoesnotimplythatnoflawsexist.Inthissection,wewillfocusonthetaxonomyofteststhatcanbeperformedinanycircumstance.
Testscanbecategorizedintotwobiggroups:white-boxtestsorstructuraltestsandblack-boxtestsorfunctionaltests.Structuraltesting,morecommonlyknownasthewhite-boxtesting,isatestingmethodthatevaluatestheinternalbehaviorofacomponent.Itisfocusedontheanalysisofthebehaviorofeachprocedureindifferentmomentsofexecution.Thewhite-boxtestevaluateshowthesoftwareproducesaresult.Functionaltesting,specificationtesting,orblack-boxtesting,aremethodsoftestingthatfocusonthefunctionalityofthecomponentratherthanitsstructure.Whenusingthiskindoftest,thetesterisawarethatacertaininputshouldgenerateaparticularoutput.Thistestevaluateswhatthesoftwareproduces.
Thetwotestcategories,white-boxtestandblack-boxtest,areshowninthefollowingdiagrams:
Therearevariouswhite-boxtechniques.However,themostcommonlyusedarecontrolflowtesting,dataflowtesting,basispathtesting,andstatementcoverageandtheyareexplainedasfollows:
Controlflowtesting:Thisevaluatestheflowgraphofthesoftwaretoindicatewhetherthesetoftestscoverseverypossibletestcase.Dataflowtesting:Thisrequiresanevaluationofhowtheprogramvariablesareused.Basispathtesting:Thisensuresthateverypossiblepathinacodehasbeenincludedinthetestcases.Statementcoverage:Thisconsistsoftheevaluationofthecodeandthedevelopment
ofindividualteststhatwillworkoneveryindividuallineofcode.
Theblack-boxtestingdesignalsoincludesdifferenttechniques.Themostfrequentlyusedtechniquesareequivalencepartitioning,boundaryvalueanalysis,cause-effectgraphing,statetransitiontesting,allpairstesting,andsyntaxtesting,andtheyareexplainedasfollows:
Equivalencepartitioning:Thisdividestestcasesindifferentpartitionsthatpresentsimilarcharacteristics.Thistechniquecanhelpinreducingthenumberoftestscases.Boundaryvalueanalysis:Thisisperformedinordertoanalyzethebehaviorofacomponentwhentheinputisneartheextremevalidvalues.Cause-effectgraphing:Thisgraphicallyillustratestherelationshipbetweencircumstancesoreventsthatcauseadeterminedeffectonthesystem.Statetransitiontesting:Thisisperformedthroughanumberofinputsthatmakethesystemexecutevalidorinvalidstatetransitions.Allpairstesting:Thisisacombinatorialmethodthattestseverypossiblecombinationofparameters.Whenthenumberofparametersandthepossiblevaluesforeachparameterarebig,thistesttechniquecanbecombinedwiththeequivalentpartitioningtechniquetoreducethenumberoftestcases.Syntaxtesting:Thisanalysesthespecificationsofacomponenttoevaluateitsbehaviorwithahugenumberofdifferentinputs.Thisprocessisusuallyautomatizedduetothelargenumberofinputsrequired.
Whentestinganapplication,therearedifferentlevelsoftestingthatdependonthesizeofthepartofthesysteminvolved.Therearefivecommonlyknownlevelsoftests:unit,integration,validation,system,andacceptance.
Unittests:Thesetestsfocusoneachindividualcomponent.Thesetestsareusuallyperformedbythesamedevelopmentteamandconsistofaseriesofteststhatevaluatethebehaviorofasinglecomponentcheckingforthecorrectnessofthedataanditsintegrity.Integrationtests:Thesetestsareperformedbythedevelopmentteam.Thesetestsassessthecommunicationbetweendifferentcomponents.Validationtests:Thesetestsareperformedbythefullydevelopedsoftwareinordertoevaluatethefulfilmentoffunctionalandperformancerequirements.Theycanalsobeusedtoassesshoweasyitistomaintainortoseehowthesoftwaremanageserrors.Systemtests:Thesetestsinvolvethewholesystem.Oncethesoftwareisvalidated,itisintegratedinthesystem.Acceptancetests:Thesetestsareperformedintherealenvironmentwherethesoftwareisused.Theuserperformsthesetestsandacceptsthefinalproduct.
Thehighertheleveloftesting,unittestingbeingthelowestandacceptancetestingthehighest,themorelikelyitistouseblack-boxtests.Unittestsevaluatecomponentsthataresmallandthereforeeasytoanalyzeinbehavior.However,thehigherthelevel,thebiggerthesystem,andthereforethemoredifficultandmoreresource-consumingitistoapplywhite-boxtestingcategory.Thisdoesnotmeanthatyoushouldnotapplytheblack-box
testingcategorywhileperformingunittests,aseachonecomplementstheother.
SummaryInthischapter,learnedthebasicandmostcommonlyusedterminologieswhilediscussingsoftwaresecurity.Youknowthedifferencebetweenthreat,vulnerability,andrisk,andunderstandhoweachoneisrelatedtotheother.Youalsolearnedaboutthedifferentkindsofthreatsandvulnerabilitiesthatcanaffectasystem.Younowknowhowtoproperlyapproachcodingyoursecuritysystemthankstothesecurecodeprinciples.Finally,youlearnedaboutthedifferentmethodsoftestingthatyoushouldconsiderinordertomakeyourapplicationrobust.Properlyunderstandingthesedefinitionsallowsyoutodesignbettersecuritysystemsforyoursoftware.
Soasadeveloper,youhavetoaddressthesecurityofyourapplication,butwhatdoesAndroiddoforyou?Androidhasseveralbuilt-insecuritymeasuresthatreducethefrequencyandthepotentialdamagethatapplicationsecurityissuesmaycause.Inthenextchapter,youwilllearnaboutthesefeaturesandunderstandhowtheywork.
Chapter2.SecurityinAndroidApplicationsYouunderstandthesecurityconceptsinsoftwareandnowyouwanttodiscoverhowthosethreatsandvulnerabilitiesareappliedtoamobileenvironment.YouwanttobeawareofthespecialsecurityfeaturesintheAndroidoperatingsystem.YouarealreadyfamiliarwithAndroid,butyouneedtoknowthecomponentsthatarecriticalforitssecurity.
Thischapterwillshowyouthechallengesthatexistinthemobileenvironment.YouwilllearnabouttheAndroidsecurityarchitectureandaboutwhatapplicationsandboxingmeans.ThischapterwillshowyouthemainfeaturesinAndroidthatwillallowyouprotectyourlocation:permissionsandinterprocesscommunication.
Wewillbecoveringthefollowingtopicsinthischapter:
VulnerabilitiesinthemobileenvironmentAndroidsecurityoverviewPermissionsInterapplicationcommunication
ThemobileenvironmentAndroidisanoperatingsystem(OS)createdforintelligentmobiledeviceswithatouchscreen,suchassmartphonesortablets.Knowingthefeaturesofadeviceisimportanttoidentifythevulnerabilitiesthatcanpotentiallycompromisetheintegrity,confidentiality,oravailabilityofyourapplication(app).
Asmartphoneisaconnecteddeviceandsomalicioussoftwarecaninfectitinseveralways.Thesmartphonecancommunicatewithdifferentdevicesbyawirelessorwiredconnection.Forexample,itcanconnecttoacomputerbyacableoritcanconnecttoanothermobiledevicebyawirelessBluetoothnetwork.Thesecommunicationsallowtheusertotransferdata,files,orsoftware,whichisapossiblepathtoinfectthesmartphonewithmalware.
AsmartphoneisalsoaconnecteddeviceinthesensethatitcanconnecttotheInternetbycellularnetworkslike3GoraccesspointsviaWi-Fi.Internetisthereforeanotherpathofpotentialthreatstothesecurityofsmartphones.
Smartphonesalsohaveinternalvulnerabilities,forexample,maliciousappsthatareinstalledbytheuserthemselves.Thesemaliciousappscancollectthesmartphone’sdatawithouttheuser’sknowledge.Sensitivedatamightbeexposedbecauseofimplementationerrorsorbecauseoferrorsthatoccurwhilesendingdatatothewrongreceiver.Communicationbetweentheappsinstalledinthesmartphonecanbecomeawaytoattackthem.
Thefollowingfigurerepresentsthetypesofexistingvulnerabilitiesinsmartphones.Theconnectiontothenetworkisoneoftheexternalvulnerabilities,sincenetworkconnectionsaresusceptibletosniffingorspoofingattacks.Theconnectionstoexternaldevicesalsoinvolvepotentialvulnerabilitiesasmentionedearlier.Regardinginternalvulnerabilities,implementationerrorscancausefailuresandattackerscantakeadvantageofthem.Finally,userunawarenessisalsoavulnerabilitythataffectstheinternalsofthesmartphone.Forexample,installingappsfromuntrustedsourcesorsettinganimprudentconfigurationforWi-FiorBluetoothservicesisarisk.
Asadeveloper,youcannotcontroltherisksassociatedwithexternaldevicesorthenetwork,noteventhoserelatedtouserunawareness.Therefore,yourresponsibilityistocreaterobustappswithoutimplementationerrorsthatcancausesecuritybreaches.
AnoverviewofAndroidsecurityAndroidprovidesasecurearchitecturetoprotectthesystemanditsapplications.Androidarchitectureisstructuredlikeasoftwarestackinwhicheachcomponentofalayeracceptsthatthelayerfollowingitissecure.ThefollowingfigureshowsasimplifiedversionoftheAndroidsecurityarchitecture:
AndroidOSisamultiuser,Linux-basedplatforminwhicheachapphasadifferentuser.EachapphasitsownuserID(UID)intheLinuxkernelthatisunique.TheUIDisassignedbythesystemandisunknowntotheapp.BecauseoftheuniqueUID,Androidappsruninseparateprocesseswithdifferentpermissions.Thismechanismisknownasapplicationsandboxing.TheAndroidApplicationSandboxisolateseachapplication’sdataandcodeexecutiontoimproveitssecurityandpreventmalware.Thismeansthatundernormalcircumstances,youcannothaveaccesstootherapplication’sdataandotherapplicationsdonothaveaccesstoyourapplication’sdata.AstheApplicationSandboxisimplementedintheLinuxkernel,thesecurityprovidedbythismechanismisextendedtoallthelayersabovethekernel(suchaslibraries,Androidruntime,applicationframework,andapplicationruntime).Forexample,ifamemorycorruptionerrorisgenerated,thiserrorwillonlyhaveconsequencesfortheapplicationinwhichtheerrorwasproduced.
ApplicationsandboxingisoneofthemainsecurityfeaturesofAndroid,butwecanalsofindthefollowingfeaturesinthesecuritymodel:
Application-definedpermissions:Ifapplicationsareisolatedfromeachother,howcantheyshareinformationwhenrequired?Applicationscandefinepermissionstoallowotherapplicationstocontrolitsdata.Therearealsomanypredefinedsystem-basedpermissionscovermanysituationsandthatwillreducethenecessityofcreatingpermissions,especiallyforyourapplication.Interprocesscommunication:Undernormalcircumstances,everycomponentofanapplicationrunsinthesameprocess.However,therearetimeswhendevelopers
decidetoruncertaincomponentsindifferentprocesses.Androidprovidesaninterprocesscommunicationmethodthatissecureandrobust.Supportforsecurenetworking:NetworktransactionsareespeciallyriskyonmobiledevicesthatcommonlyuseunsecuredWi-Finetworksinpublicspaces.Androidsupportsthemostcommonlyusedprotocolstosecureconnectionsundertheseextremeconditions.Supportforcryptography:Androidprovidesaframeworkthatdeveloperscanusewithtestedandrobustimplementationsofcommonlyusedcryptographicmethods.Encryptedfilesystem:Androidprovidesafullfilesystemencryption.ThismeansthattheinformationstoredonanAndroiddeviceisencryptedandisthereforeprotectedatanytimeagainstexternalentities.Thisoptionisnotactivebydefaultandrequiresausernameandapassword.Applicationsigning:Theinstallationpackageofeveryappmustbesignedwithacertificate,whichcanbeaself-signedcertificate.Anattackercanpreservetheiranonymity,sinceit’snotnecessaryforatrustedthird-partytosignthecertificate.Certificatesaremainlyusedtodistinguishdevelopersandallowthesystemtomanagepermissions.Topreventanattackerfrommodifyingyourapplication,youshouldkeepyourcertificatesafe.Furthermore,applicationupdatesmustbesignedwiththissamecertificate.
PermissionsWithapplicationsandboxing,appscannotaccesspartsofthesystemwithoutpermission,butevenwithit,Androidallowsdatasharingwithotherappsoraccesstosomesystemservices.Anappneedstorequestpermissiontoaccessdevicedataortoaccesssystemservices.PermissionsareasecurityfeatureofAndroidsystem,butmisusedpermissionsmakeyourapplicationvulnerable.
Thepermissionneedsofanapparedeclaredinitsmanifestfile.Thismanifestfileisbundledintotheapp’sAndroidapplicationpackage(APK),whichincludesitscompiledcodealongwithotherresources.Thepermissionsrequestedinthemanifestfile(manifestpermissions)willbeshowntotheuserwheninstallingtheapp.Theusershouldreviewthesepermissionsandacceptthemtocompletetheinstallationprocess.Iftheuseragreestothem,theprotectedresourcesareavailabletotheapp.
TipDonotrequestpermissionsthatyourappdoesnotneed.Reducingthenumberofpermissionsmakesyourapplessvulnerable.
PermissionscontrolhowanappinteractswiththesystembyusinganAndroidapplicationprogramminginterface(API).SomeoftheprotectedAPIsthatneedpermissionincludethefollowing:
BluetoothCameraLocationGPSNetworkanddataconnectionsNFCSMSandMMSTelephony
Forexample,torequestpermissiontousethecamera,youhavetoaddthefollowinglinecodeinourmanifestfile:
<uses-permissionandroid:name="android.permission.CAMERA"/>
ThefollowingcodeisusedtorequestpermissiontoaccesstheInternet:
<uses-permissionandroid:name="android.permission.INTERNET"/>
ThefollowingcodeisusedtorequestpermissiontosendaSMS:
<uses-permissionandroid:name="android.permission.SEND_SMS"/>
InterapplicationcommunicationAppsinAndroidcannotaccesseachother’sdatadirectlybecauseofapplicationsandboxing,butAndroid’ssystemprovidessomeothermechanismsfortheapplicationstocommunicatewitheachother.IntentsandcontentprovidersaremechanismsthatwecanuseontheJavaAPIlayer.Intentsandcontentprovidersshouldbeusedcarefullytopreventattacksfrommalwareapplications.Thisisthereasonwhyitisimportanttounderstandtheircharacteristics.
IntentsIntentsareanasynchronousinterprocesscommunicationmechanism.Intentisamessagethatincludesthereceiverandoptionalargumentstopassthedata.ThereceiverofIntentcanbedeclaredexplicitlysothattheIntentissenttoaparticularcomponent,oritcanbedeclaredimplicitlysothattheIntentissenttoanycomponentthatcanhandleit.Intentsareusedforintra-applicationcommunication(inthesameapplication),orforinterapplicationcommunication(indifferentapplications).ThefollowingcomponentscanreceiveIntents:
Activities:Anactivityrepresentsascreenintheapp.Intentscanstartactivities,andtheseactivitiescanreturndatatotheinvokingcomponent.TostartanactivityusingIntent,youcancallthestartActivitymethodorthestartActivityForResultmethodtoreceivearesultfromtheactivity.Services:Aserviceperformslong-runningbackgroundtaskswithoutinteractingwiththeuser.TostartaserviceusingIntent,youcancallthestartServicemethodorthebindServicemethodtobindothercomponentstoit.Broadcastreceivers:Intentscanbesenttomultiplereceiversthroughbroadcastreceivers.WhenareceiverisstartedbecauseofIntent,itrunsinthebackgroundandoftendeliversthemessagetoanactivityoraservice.Somesystemeventsgeneratebroadcastmessagestonotifyyou,forexample,whenthedevicestartschargingorwhenthedevice’sbatterylevelislow.TosendabroadcastmessageusingIntent,youcancallthesendBroadcastmethod.Tosendanorderedbroadcast,youcancallthesendOrderedBroadcastmethod.Tosendastickybroadcast,youcancallthesendStickyBroadcastmethod.Therearethreetypesofbroadcastmessages:
Normalbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoallthereceiversatthesametime.Soonafter,themessageisnolongeravailable.Orderedbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoonereceiveratatimedependingonitsprioritylevel.Anyreceivercanstopthepropagationofthemessagetotherestofthereceivers.Soonafter,themessageisnolongeravailable.Stickybroadcast:Inthistypeofbroadcast,themessageissentbutitdoesnotdisappear.Anexampleofastickybroadcastisthebatterylevel.Anappcanfindoutwhichwasthelastbatterylevelbroadcastbecauseitremainsaccessible.
ApplicationcommunicationbyIntentsallowsthereceiverandoptionalargumentstoreuseeachother’sfeatures.Forexample,ifyouwanttoshowawebpageinyourapp,youcancreateIntenttostartanyactivitythatisabletohandleit.Youdonotneedtoimplementthefunctionalitytodisplayawebpageinourapp.ThefollowingcodeshowsyouhowtocreateIntenttodisplaywebpagecontent:
Intenti=newIntent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.packtpub.com"));
startActivity(i);
Tip
Downloadingtheexamplecode
YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
TheprecedingcodeisanexampleofanimplicitIntentinwhichageneralactionisindicated:Intent.ACTION_VIEW.TheAndroidsystemsearchesforalltheappsthatmatchtheIntent.IfthereismorethanoneapplicationthatmatchestheIntentandtheuserhasnotsetadefaultone,adialogisdisplayedsothattheusercanchoosewhichoneofthemtouse.
IntentsthataresupportedbyacomponentaredeclaredinthemanifestfileusingtheIntentfilters.Thebroadcastreceiverscanbealsobedeclaredatruntime.IntentfilterdeclaresthetypesofIntentsthatacomponentcanrespondto.WhenacomponentincludesanIntentfilter,thecomponentisexportedsoitcanreceiveIntentsfromothercomponents.IntentfiltercanconstrictbytheactionoftheIntent,bythetypeofdata,orbythecategoryoftheIntent.Forexample,ifyouwantyourapptobehaveasabrowser,youhavetocreateanactivitywiththefollowingIntentfiltersinyourmanifestfile:
<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>
Thefollowingexampleshowsyouhowtoregisterareceivertorunwhenthedevicestartscharging:
<receiver…>
<intent-filter>
<actionandroid:name="android.intent.action.ACTION_POWER_CONNECTED"/>
</intent-filter>
</receiver>
NoteIfyouwanttolearnmoreaboutIntents,youmightwanttocheckouttheofficialdocumentation:http://developer.android.com/guide/components/intents-filters.html.
ContentprovidersContentprovidersareamechanismthatallowssharingbetweenapplicationsandservesaspersistentinternaldatastoragefacility.ThedatastoredthroughacontentproviderisstructuredandtheinterfaceisdesignedtobeusedwithaStructuralQueryLanguage(SQL)backend.AlthoughitiscommontouseaSQLdatabasebehindcontentproviders,filestorageorRESTcallscanalsobeused.Ifyouarenotfamiliarwithcontentproviders,youmightwanttocheckouttheofficialdocumentationsinceitisabroadtopic:http://developer.android.com/guide/topics/providers/content-providers.html.Ourinterestincontentprovidersisrelatedtotheirsecurityandpermissions.ContentprovidersaretheperfectscenarioforSQLinjectionattacks.
Toaccessthedataofcontentproviders,therearecontentresolversthatyoucanuseinyourapp.Theprovider’sdataisidentifiedbyacontentURI.Toaccessthecontentprovider,youshouldusethegetContentResolver().query()method,whichreceivesthefollowingparameters:
ContentURI:ThisistheURIthatidentifiesthedata(theFROMclauseinSQL)Projection:Thisspecifiesthecolumnstoretrieveforeachrow(theSELECTclauseinSQL)Selection:Thisisthecriteriatoselecttherows(theWHEREclauseinSQL)Selectionarguments:ThiscomplementsthecriteriatoselecttherowsSortorder:Thisisthesortorderfortherows(theORDERBYclauseinSQL)
TherearesomecontentprovidersofferedbytheAndroidsystemitself,suchasthecalendarproviderandthecontactsprovider.Toaccessthesystemcontentproviders,youneedtorequestthepermissioninyourmanifestfile.Forexample,tobeabletoreadthecontacts,youmustaddthefollowingpermissiontoyourapp:
<uses-permissionandroid:name="android.permission.READ_CONTACTS"/>
Toacquirethewritingaccesspermissions,youmustaddthefollowinglineofcodeinyourmanifest:
<uses-permissionandroid:name="android.permission.WRITE_CONTACTS"/>
Anyothercontentprovider,notonlythoseofthesystem,canindicatetherequiredpermissionsthatotherappsmustrequestsothattheycanaccesstheprovider’sdata.
SummaryInthischapter,youlearnedaboutthevulnerabilitiesassociatedwithmobiledevices—bothexternalandinternal.YounowunderstandtheAndroidarchitectureandthefeaturesprovidedbythesystemtokeepitsafe.YounowknowwhichcomponentsoftheJavaAPIlayerarevulnerabletoattacks,soyoucanlearnhowtomitigatetheminthenextchaptersofthisbook.
Inthenextchapter,wewillstartusingAndroidStudioIDE.AsthefirststeptocreatesecureAndroidapplications,youwilllearnhowtomonitorAndroidapplicationsinthedebuggingenvironmentinordertodetectincorrectbehaviors.
Chapter3.MonitoringYourApplicationYouarenowawareoftheimportanceoflearninghowtomonitortheactivityofyourAndroidapplicationandarealsofamiliarwiththebasicconsoleorlogsthatyouusetodebugyourapplication.However,thereismoretolearnaboutthedebuggingtoolavailableinAndroidStudio.AndroidStudioincludestheDalvikDebugMonitorServer(DDMS)debuggingtool.DoyouwanttousethisdebuggingtoolwhileprogramminginAndroidStudio?
Thischapterpresentsthedebuggingenvironment,oneofthemostimportantfeaturesofanIDE.MonitoringyourAndroidapplicationallowsyoutodetecttheincorrectbehaviorsandsecurityvulnerabilities.Inthischapter,youwilllearnabouttheinformationavailableintheadvanceddebuggingtoolincludedinAndroidStudio:DDMS.
Thetopicsthatwillbecoveredinthischapterareasfollows:
DebuggingandDDMSThreadandmethodprofilingHeapusageandmemoryallocationNetworkstatisticsFileexplorerEmulatorcontrolandsysteminformation
DebuggingandDDMSInAndroidStudio,youcanusedifferentmechanismstodebugyourapplication.Oneofthemisthedebugger.Thedebuggermanagesthebreakpoints,controlstheexecutionofthecode,anddisplaysinformationaboutthevariables.Todebuganapplication,navigatetoRun|Debug‘MyApplication’orclickonthebugiconpresentinthetoolbar.
AnothermechanismistheConsole.TheConsoledisplaystheeventsthataretakingplacewhiletheapplicationisbeinglaunched.Actionssuchasuploadingtheapplicationpackage,installingtheapplicationinthedevice,orlaunchingtheapplicationaredisplayedintheConsole.
LogCatisanotherusefultooltodebugyourapplication.ItisanAndroidloggingsystemthatdisplaysallthelogmessagesgeneratedbythesystemintherunningdevice.Logmessageshaveseverallevelsofsignificance:verbose,debug,information,warning,anderror.
Finally,youalsohaveDDMS,anexcellentdebuggingtoolavailableintheSDKthatisavailabledirectlyinAndroidStudio.Thistoolisthemaintopicofthischapter.
ToopentheDDMStoolinAndroidStudio,navigatetoTools|Android|Monitor(DDMSincluded).Alternatively,youcanclickontheAndroidiconpresentinthetoolbar,whichwillopenawindowwiththeDDMSperspective.
Oncetheperspectiveisopen,asshowninthefollowingscreenshot,youcanseethelistofconnecteddevicestotheleft-handsideofthescreen,alongwithalistoftheprocessesrunningoneachdevice.Ontheright-handsideofthescreen,youcanseethedetailedinformationoftheprocess.Thisinformationisdividedintoseventabs:Threads,Heap,AllocationTracker,NetworkStatistics,FileExplorer,EmulatorControl,andSystemInformation.LogCatandConsoleareaccessibleatthebottomofthewindow.
ThreadsTheThreadstabdisplaysthelistofthreadsthatareapartoftheselectedprocess.Applicationshaveonemainthread,alsocalledastheUIthread,whichdispatchestheeventstotheuserinterface(UI)widgets.Toperformlongoperations,itisnecessarytocreatenewthreadssothatthemainthreadisnotblocked.Ifthemainthreadgetsblocked,thewholeUIwillalsogetblocked.
Toillustratetheworkingofthistool,runthefollowingexample.InAndroidStudio,createanewbasicprojectwithamainlayoutandamainactivity.Addabuttontothemainlayoutnamed,forexample,StartNewThread.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcodeinthemethod:
publicvoidstartNewThread(Viewv){
newThread(newRunnable(){
publicvoidrun(){
Thread.currentThread().setName("MyexampleThread");
try{
Thread.sleep(30000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}).start();
}
Theprecedingmethodcreatesanewthreadintheapplication,althoughitdoesnothingandcontainsonlyasleepinstruction.Youcansetthethreadanametorecognizeiteasily.RuntheapplicationandopentheDDMSperspective.
SelectyourapplicationprocessfromtheDevicessectionandclickontheUpdateThreadsiconpresentonthetoolbaroftheDevicessectionandthethreadswillbeloadedinthecontentofthetab.TheStatuscolumnindicatesthethreadstate,utimeindicatesthetotaltimespentbythethreadexecutingusercode,stimeindicatesthetotaltimespentbythethreadexecutingsystemcode,andNameindicatesthenameofthethread.YoucanidentifythemainthreadintheresultlistwiththeIDnumber1,asshowninthefollowingscreenshot:
ClickontheStartNewThreadbuttonofyourapplicationandnoticethatanewthreadappearsinthelistascanbeobservedinthefollowingscreenshot,MyexampleThread:
Thethreadisactiveforaperiodof30seconds.EverytimeyouclickontheStartNewThreadbutton,anewthreadiscreated.
Thistoolisespeciallyusefulwhilecreatingthreadsinourapplicationapartfromthemainthread.Thankstothistool,wecaneasilycheckwhetherourthreadsarebeingexecutedatacertainpointoftheexecutionorwhethertheyareperformingasexpectedinmemoryusage.
MethodprofilingThemethodprofilingtoolisusedtomeasuretheperformanceofthemethodsofaselectedprocess.Withthistool,youcanaccessthenumberofcallsofamethodandtheCPUtimespentontheirexecution.Therearetwotypesofvaluesavailable,theexclusivetimeandtheinclusivetime:
Exclusivetime:Thisreferstothetimespentintheexecutionofthemethoditself.Inclusivetime:Thisreferstothetotaltimespentintheexecutionofthemethod,whichincludesboththetimespentbythemethodaswellasthetimespentbyanyothermethodcalledinsidethemethod.
Toillustratetheworkingofthistool,wearegoingtorunthefollowingexample.CreateanewbasicprojectwithamainlayoutandamainactivityinAndroidStudio.Youcanalsoreusetheprojectcreatedintheprevioussection.Addabuttontothemainlayout,forexample,StartMethodHierarchy.Createanewmethodthatistobeexecutedwhenthebuttonisclickedandaddthefollowingcodeinthemethod:
publicvoidstartMethodHierarchy(Viewv){
secondMethod();
}
Addthesecondandthethirdmethodinyouractivity,shownasfollows:
privatevoidsecondMethod(){
thirdMethod();
}
privatevoidthirdMethod(){
try{
Thread.sleep(30000);
}catch(InterruptedExceptione){e.printStackTrace();}
}
Asseeninthepreviouscode,youcreateahierarchyofmethodcallsthatyouwillbeabletoobserveinthemethodprofiling.Totakealookatyourmethodprofilingdata,selectyourapplicationprocessinthedevicessectionandclickontheStartMethodProfilingiconpresentonthetoolbaroftheDevicessection.ClickontheStartMethodHierarchybuttonofyourapplicationandwaitforaperiodofatleast30secondssothatthethirdmethodfinishesitsexecution.Oncethethirdmethodfinishesitsexecution,youcanstopthemethodprofilingbyclickingontheStopMethodProfilingicon.
Whenyoustopthemethodprofiling,anewtabwiththeresultanttracewillappearwithintheDDMSperspective.Thetopofthisnewtabrepresentsthemethodcallsinatimegraphwhereeachrowbelongstoeachthreadoftheapplication.Thebottomofthetracerepresentsthesummaryofthetimespentonamethodinatable.
Tosearchforyourapplicationpackageandmainactivity,clickontheNamelabeltoorderthemethodsbytheirname,forexample,com/example/myapplication/app/MainActivity.Thethreemethods
(startMethodHierarchy,secondMethod,andthirdMethod)shouldappearinthelistasisshowninthefollowingscreenshot:
OnexpandingthedetailedinformationofthesecondMethod,youcanseethattheparentisthestartMethodHierarchymethodandthatthethirdMethodmethodisitschild.Thisinformationispresentedinthefollowingscreenshot:
Also,examinetheexclusiveandinclusiverealtimes.TheprecedingscreenshotrevealsthattheinclusiverealtimeforthirdMethodwas30001,138ms,becauseofthesleepclauseof30seconds.ThetimespentintheexecutionofthesecondMethoditselfis0,053ms(exclusiverealtime),butsincetheinclusivetimeincludesthetimespentbythechildrenmethods,itsinclusiverealtimewas30001,191ms.
Methodprofilingcanbeusedtodetectmethodsthatarespendingmoretimethananticipatedintheirexecution.Withthisinformation,youcanlearnwhichmethodsarecausingproblemsandneedtobeoptimized.Youcanalsolearnwhichmethodsaremoretime-consumingsothatyoucanavoidunnecessarycallstothem.
HeapTheHeaptabstoresallnewobjectscreatedintheapplication.Thegarbagecollector(GC)deletestheobjectsthatarenotreferredanymore,releasingunusedmemory.TheHeaptabdisplaystheheapusageforaselectedprocess.
Toillustratetheworkingofthistool,runthefollowingexample.CreateanewbasicprojectwithamainlayoutandamainactivityinAndroidStudio.Addabuttontothemainlayout,forexample,StartMemoryConsumption.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcodetothemethod:
publicvoidmemoryConsumption(Viewv){
list=newArrayList<Button>();
for(inti=0;i<=1000;i++){
list.add(newButton(this));
}
}
Finally,addthedeclarationofthelistasaglobalvariableintheactivity.Thisway,youarepreventingtheGCtoreleasethememorythatstoresthelistafterthemethodfinishesitsexecution.Thedeclarationofthelistasaglobalvariableintheactivityisshownasfollows:
privateList<Button>list;
Inthismethod,youarecreatingalargenumberofnewobjects,forexample,alistcontaining1000buttons.Usingthismethod,youaregoingtoexaminehowthecreationofthelistisreflectedintheheap.RuntheapplicationandopentheDDMSperspective.SelecttheapplicationprocessintheDevicestabandclickontheUpdateHeapiconpresentonthetoolbartoenableit.TheheapinformationisshownafteraGCexecution.SelecttheHeaptabandclickontheCauseGCbutton,andyou’llseetheheapusage.
Thefirsttableofthetabdisplaysasummary:thetotalsize,theallocatedspace,thefreespace,andthenumberofallocatedobjects.Thestatisticstablepresentsthedetailsoftheobjectsthatareallocatedontheheapbyitstype:numberofobjects,totalsizeoftheobjects,sizeofthesmallestandlargestobjects,mediansize,andaveragesize.Wecanselecteachtypeindividually.Thisactionwillloadthebottombargraphwiththenumberofobjectsofthattypeorderedbyitssizeinbytes.Wecanthenclickonthegraphusingtherightbuttonofthemousetochangeitsproperties:title,colors,font,labels,andsoon.WecanalsosaveitasaPNGimage.
Observethenumberofdataobjectsallocatedontheheapasshowninthefollowingscreenshot:
ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMSperspective,causemoreGCexecutionsandnotehowthenumberofobjectsincreaseswhilethemethodisbeingexecuted.Thefollowingscreenshotshowstheheapinformationwhenthemethodhasalreadyfinisheditsexecution.Theallocateddataobjectshavegrownfrom24.822to60.821.
Finally,youcanalsotrytochangethedeclarationofthelistsothatitbecomesalocalvariableinthememoryConsumptionmethod.RepeatthepreviousprocessandnotethatthenewdataobjectsarereleasedbytheGConcetheexecutionofthemethodisfinished.
AllocationTrackerTheAllocationTrackertabdisplaysthememoryallocationsoftheselectedprocess.Theallocationtracker,unliketheheaptool,showsthespecificobjectsbeingallocatedalongwiththethread,themethod,andthelinecodethatallocatedthem.
Youcanagainrunthepreviousexamplecreatedfortheheapmonitortoshowtheresultsoftheallocationtracker.SelecttheapplicationprocessandintheAllocationTrackertabandclickontheStartTrackingbuttontostarttrackingthememoryinformation.Now,clickontheGetAllocationsbutton.Thiswillgetthelistofallocatedobjects,whichincludesafilteronthetopofthetabthatyoucanusetofiltertheobjectsallocatedinyourownclasses.
ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMSperspective,againclickontheGetAllocationsbuttonandobservethenewobjectsthatarelistedintheresults.TheobjectsarethebuttonscreatedinthememoryConsumptionmethod.
Theresultstablepresentstheallocationsize,thethread,theobjectorclass,andthemethodinwhicheachobjectwasallocated.ClickonanyoftheButtonobjectstoseemoreinformationasshownthefollowingscreenshot.
YoucannoticethattheButtonobjectisallocatedinthemainactivityinthememoryConsumptionmethod,andthelineofcodethatallocateditisthelinenumber26.
Wheneveryouneedtoexaminetheobjectsallocatedintheheap,youcanusetheallocationtracker.Youcananalyzetheinteractionsinyourapplicationandimprovethememoryusage.
ThefollowingscreenshotshowsthedetailsoftheButtonobjects:
NetworkStatisticsTheNetworkStatisticstabdisplaysthenetworkresourcesusedbyourapplication.Let’screateasimpleexampletotestthistool.Createanewprojectandaddthefollowingpermissionsinyourmanifestfile:
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
Inthemainlayout,addabuttonnamed,forexample,StartNetworkConnection.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcode:
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,weneedtoexecutethecodeinanewthread.UsinganAsyncTaskclassisabettersolution,butinsteadtheThreadclassisusedtokeepthecodecleaner.Afterdownloadinganimageandbeforedownloadingthenextone,youwillhavetowaitforaperiodof5secondssothattheresultsdisplayedlaterarenotconfusing.Finally,toclearlyseparatethedifferentdownloads,weestablishadifferenttagforeachdownloadusingthesetThreadStatsTagandclearThreadStatsTagmethodsoftheTrafficStatsclass.TheTrafficStatsclassprovidesnetworktrafficstatisticssuchasthenumberofbytesorpackagesreceivedandtransmitted.
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,thepreviousmethoddoesnotexecuteanyadditionalactionsontheimages.Theimagesareonlydownloaded.
RuntheapplicationandopentheDDMSperspective.Togetthenetworkstatisticsofyourapplication,clickontheStartbuttonintheNetworktab.Then,clickontheStartNetworkConnectionbuttonoftheapplicationtostartdownloadingtheimages.Thedatatransferswillappearinthegraphaspacketsaresentorreceived.Thefollowingscreenshotshowstheresultsofthenetworkstatistics:
Inthepreviousscreenshot,thedownloadofthethreeimagescanbeeasilyidentified.ThecolumnsRXbytesandRXpacketsrepresentthetotalnumberofbytesandpacketsreceived.ThecolumnsTXbytesandTXpacketsrepresentthetotalnumberofbytesandpacketstransmitted.Wecanusethenetworkstatisticstooltooptimizethenetworkrequestsinourapplicationandcontrolthepacketsthatarebeingtransferredatacertainpointoftheexecution.
FileExplorerTheFileExplorertabexposesthewholefilesystemofthedevice.Wecanexaminethesize,date,orpermissionsforeachelement.Navigateto/data/app/yourpackagetosearchforyourapplication.apkpackagefile.Tocheckthepathinwhichyourfilesaresavedwhentheyarecreatedoninternalstorage,youcanusethegetFilesDir()methodinyouractivity.Thefilesrelatedtoyourapplicationareusuallylocatedat/data/data/yourpackage.Let’sperformanexample.
Createanewprojectandinthemainlayoutaddabuttonnamed,forexample,CreateNewFile.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcode:
publicvoidcreateNewFile(Viewv){
Stringstring="Helloworld!";
FileOutputStreamoutputStream;
try{
outputStream=openFileOutput("MyFile",MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
}catch(Exceptione){e.printStackTrace();}
}
Usingthepreviouscode,youarecreatinganewtextfileontheinternalstorageofourapplication.RuntheapplicationandopentheFileExplorertaboftheDDMSperspective.Navigateto/data/data/yourpackage/files,whichisempty.ClickontheCreateNewFilebuttonofyourapplicationandcheckthatthenewfilehasbeencreatedat/data/data/yourpackage/files,asshowninthefollowingscreenshot:
EmulatorControlTheEmulatorControltabmakesitpossibletochangestatesoractivitiesinthevirtualdevice.Withthisemulator,youcantestyourapplicationinenvironmentsandsituationsthatwouldotherwisebeimpossibleortime-consumingtoachieve.Thisallowsyoutocheckwhetheritisbehavingasexpectedunderthefollowingspecialconditions:
TelephonyStatus:Youcanchoosethevoiceanddatastatus,changingitsspeedandlatencyTelephonyActions:Youcansimulateanincomingcalls,MMS,orSMSLocationControls:Youcanchangethegeolocationofthedevice
SystemInformationIntheSystemInformationtab,youcanaccessFrameRenderTime,CPUload,andMemoryusageofthedeviceintheformofgraphs.Youcanselectyourapplicationindividuallyandcompareitwiththerestofapplicationsthatarerunningonthedevice.
Ifyouclickonthegraphwiththerightbuttonofthemouse,youwillseeapopupwiththegraphpropertiessuchascolors,font,andtitle.ThegraphcanbecustomizedhereandcanalsobesavedasaPNGimage.
SummaryAftergoingthroughthischapter,youknowhowtodebuganapplication.YoucreatedseveralexamplesinthischaptersoyouknowhowtointerpretthedataprovidedbytheDDMSineachofthetabsavailable.Younowunderstandbetterhowthreads,methodcalls,memoryallocation,andnetworkusageworkinAndroidapplications.
Inthenextchapter,youwillapplyallthatyouhavelearnedfromthisandthepreviouschapter.YouwilllearnhowtoidentifyandmitigatethevulnerabilitiesinAndroidapplications,andyouwillbeabletocreatesecureapplicationsbyfollowingtherecommendationsincludedinthenextchapter.
Chapter4.MitigatingVulnerabilitiesInChapter1,IntroductiontoSoftwareSecurity,wealreadydiscussedthemostimportantvulnerabilitiesthatcanbeexploitedinordertocompromiseyourapplication.Now,youneedtolearnwhatmeasuresyoucantakeinordertoaddressthesevulnerabilitiesandmakeyourapplicationmoresecure.Whateasystepscanbetakeninordertoachievethis?
Thischapterwillshowyouhowtomitigatevulnerabilities.Removingoratleasttreatingvulnerabilitieswillsignificantlyreducetherisksofyoursystem.We’llbeginbylearninghowtovalidateinputfields.We’llalsolearnhowtoavoidcodeinjection,especiallythemostcommonone:SQLinjection.We’llthenseerecommendedpracticeswhenhandlingusercredentialsandwewilllearnhowtomakeourcomponentsmoresecureinordertoavoidvulnerabilitiesintheinterapplicationcommunications.
Thetopicsthatwillbecoveredinthischapterareasfollows:
InputvalidationPermissionsHandlingusers’dataandcredentialsInterapplicationcommunication
InputvalidationAccordingtotheAndroiddevelopmentguidelines,thelackofsufficientinputvalidationmeasuresisoneofthemostcommonsecurityproblemsinAndroidapplications.Thereareseveralproblemsthatcanbederivedfrominsufficientinputvalidationsuchasbufferoverflows,nullpointers,off-by-oneerrors,inconsistenciesinthedatabase,andevencodeinjectionproblems.
Now,wewillseesometipsthatwillhelpustomitigatethisvulnerability.
WecanusetheinputTypeattributeinordertolimitthepossiblecharacterstheusercansetinafield.Forexample,ifwehaveanEditTextfieldwherewewantatelephonenumber,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,itcanhelptomitigatethisvulnerability.However,inordertoensurethatthefieldiscorrect,additionalmeasuresshouldbetaken.
Forexample,ifwehaveEditTextforane-mail,wecancheckifitscontentmatchestheformatofane-mailsimplybyusingthePatternclassfromthejava.util.regexpackageandthePatternclassfromthejava.utilpackage:
publicvoidisEmail(EditTextet){
if(et.getText()==null)returnfalse;
elsereturnPatterns.EMAIL_ADDRESS.matcher
(et.getText().toString()).matches();
}
Therearemorepatternsavailableinthisclassthatwecanuse:
DOMAIN_NAME:ThispatternisusedtocheckthedomainnamesEMAIL_ADDRESS:Thispatternisusedtocheckthee-mailaddressesIP_ADDRESS:ThispatternisusedtochecktheIPaddressesPHONE:ThispatternisintendedtocheckthesubstringsthataresimilartophonenumbersintextandshouldnotbeusedtovalidateaphonenumberTOP_LEVEL_DOMAIN:ThispatternisusedtochecktheInternetAssignedNumbersAuthority(IANA)top-leveldomainsWEB_URL:ThispatternisusedtocheckmostpartsofthewebURLs
Ifweneedtovalidateaninputthatisnotinthislist,wecanuseourownregularexpressions.Thereareplentyofoptionstodothevalidation,butusingthePatternclassfromthejava.util.regexpackageisrecommended.Tolearnmoreaboutregularexpressions,whichwillallowyoutodefineyourownpatterns,youcanchecktheofficial
documentationathttp://developer.android.com/reference/java/util/regex/Pattern.html.
SQLinjectionOneofthemostcommonandharmfulattacksisaparticularkindofcodeinjectionwhereunauthorizedSQLqueriescanaccessorevenalterourdatabase.Toillustratethissituation,let’sconsiderthefollowingexamplewhereyouhavethefollowingcodetochecktheusernameandpasswordthatwasjustenteredbytheuser:
//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?AnattackercansimplywriteausernameandenterthefollowingstringinEditTextforpassword:
''OR'1'='1'
Thiswillgranttheuseraccesstotheusernamesincethestringquerywillappearasfollows:
"SELECT*FROMusersWHEREusername='admin'ANDpassword=''OR'1'=
'1'"
Thebestdefenseagainstthisvulnerabilityistouseparameterizedqueries.Themostimportantmethodsthatwewillbeusingareasfollows:
query(Uriuri,String[]projection,Stringselection,String[]
selectionArgs,StringsortOrder)
insert(Uriuri,ContentValues)
update(Uriuri,ContentValuesvalues,Stringselection,String[]
selectionArgs)
delete(Uriuri,Stringselection,String[]selectionArgs)
NotethatiftheselectionArgsparametercontainsanymeaningfulSQLcharacters,thosecharactersaresanitizedandcanthereforemeannoharmtotheintegrityofthedatabase.Inordertoexecutethecodeusedinthepreviousexamplesafely,wecanusethemethodshowninthefollowingcode:
//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
PermissionsTheAndroidsandboxingsystemalienatesapplicationsfromeachother.Thismeansthattheapplicationsmustexplicitlyshareresourcesthroughtheuseofpermissions.Inordertoaccesstheadditionalcapabilities,weneedtodeclarethepermissionsthatwerequireinourmanifest,andthesepermissionsmustbeacceptedbytheuserafterinstallation.
Ifourapplicationdoesnothaveaccesstomanypermissions,itreducesthevulnerabilitiesthatmayaffectourapplication.Whendevelopingtheapplication,weshouldalwaystrytorequestasfewpermissionsaspossible.Forexample,trytostoredatalocallyinsteadofaskingforapermissionforexternalstorage.Ifitisnotpossible,wecanobviouslyrequestpermissionsbutweshouldaddressthevulnerabilitiesthatthesepermissionscanleadto.
Ifthesystem-definedpermissionsarenotenough,wecancreateourownpermissiontouse,whichwillbedefinedandwillrequireotherentitiestoaskforpermissionwhenrequired.Whencreatingapermission,wehavetoconsiderthedifferentprotectionlevelsavailable:
normal:Thisisthelowestpossiblepermissionlevelandissetbydefaultdangerous:Thispermissionlevelcanbegrantedbytheuserduringinstallationsignature:ThispermissionlevelisgrantedbythesystemifarequestingappissignedwiththesamecertificateastheappthatdeclaredthepermissionsignatureOrSystem:ThispermissionlevelisgrantedbythesystemifarequestingappisintheAndroidsystemimageorissignedwiththesamecertificateastheappthatdeclaredthepermission
Alwaystrytousethesignaturepermissionssincetheyaretransparenttotheuserandgrantaccessonlytoapplicationssignedbythesamedeveloper.Ifweneedtousethedangerouspermissionlevel,wehavetounderstandthatthispermissionisgrantedbytheuserand,therefore,needstobewellexplainedwhendefined.Userscandecidenottoinstalltheapplicationiftheydonotunderstandthepermissionthattheyhavetograntoriftheyperceiveitasapossibleharm.
Wewillseesomeexamplesofcreatingpermissionsinthefollowingsections.
Handlingauser’sdataandcredentialsThebestwaytohandleauser’sdataandcredentialsistominimizetheuseofthisinformation.Weshouldhaveaccesstotheuserdata,storeuserdata,ortransmituserdataonlywhenitiscompletelynecessary.
Inthecaseswherehandlinguser’sdataandcredentialsisnecessary,therearesomeconsiderationsthatweshouldhaveasdevelopers:
Considerusinghashornonreversibleformsofdataifthelogicofyourapplicationallowsit.Donotexposeuser’sdatatootherapplicationsonthedevice.Trytomaketheinterprocesscommunicationasstrictaspossible.Programmingwithmoreflexibleinterprocesscommunicationpermissionscanbemorecomfortable,butitcanalsobeahugevulnerabilityinyoursystem.MinimizetheuseofAPIsthataccesssensitiveinformation,especiallywhentheinformationispersonaldata.DifferentAPIshavedifferentprivacypoliciesandcanevenbemalicioussometimes.Makesureyouunderstandwhateachandeverypieceofdatathatwehavetosupplytoathird-partycomponentisfor.Whenyoudon’tunderstandwhyathird-partycomponentorAPIrequirescertaindata,itisbetternotprovideit.Limitthenumberoftimesusersareaskedforcredentialsasmuchaspossible.Askingforcredentialsanumberoftimescanmaketheuserlessawareofpossiblephishingattacks.LogsareasharedresourceinAndroid,andthereforeyoushouldbecarefulaboutwhichinformationyouwriteontotheselogs.Avoidtransmittingunnecessaryinformationwheneveritispossible.Whentreatingsensitiveinformation,evaluatewhetheritisnecessarytotransmitthatinformationontheserver.Iftheoperationcanbeperformedlocally,youshouldperformitlocally.Whenusingausernameandpasswordauthenticationsystem,besurenottostorethisinformationonthedevice.Ifitisstrictlynecessarytodoso,usecryptographymethodsandneverstoreitasplaindata.
YoucanavoidsomeoftheseproblemsusingtheAndroidclassAccountManager.TheclassAccountManagerprovidesaccesstotheuser’sonlineaccountsthataresetinthedevice.Google,Facebook,andWhatsApphavetheirownauthenticatorsthatareusedtomanagetheauthenticationofyourapplication.Thisalsohasanaddedvalue,thatis,toavoidtheprocessofregistration,whichsometimescandriveawaylazyusers.YouwilllearnmoreaboutthisauthenticationmethodinChapter7,AuthenticationMethods.
InterapplicationcommunicationAsweseeninChapter2,SecurityinAndroidApplications,therearewaystocommunicatebetweenAndroidappsastheycannotsharedataduetoApplicationsandboxing.Thiscommunicationraisessecuritychallengesthatshouldnotbeoverlooked.
SecuringIntentsWhenusingIntents,therearetwokindsofvulnerabilities:unauthorizedIntentreceiptandIntentspoofing.AnunauthorizedIntentreceipthappenswhileusinganimplicitIntent.AstheIntentisbroadcasted,thereisnoguaranteethattheintendedrecipientwillreceiveit.AmaliciousapplicationcandeclareanimplicitIntentbydeclaringallthepossibleactionsintheintentfilter.ThiskindofinterceptioncanleadtoDoSandphishingattacks.
ThebestwaytoprotectagainstthiskindofvulnerabilityistobeverycautiouswithimplicitIntents.
NoteIfyouaresharingsomeprivateinformation,avoidusingimplicitIntents.
Whenpossible,andespeciallywhilesharingprivateinformation,yourapplicationshouldconsiderusingexplicitIntents.YoucanmaketherecipientexplicitbysettingthedestinationclassusingthemethodsetClassName(Contextctxt,StringclassName)asfollows:
Intenti=newIntent();
i.setClassName("com.example.myapplication",
"com.example.myapplication.MyActivity");
YoucanalsousethesetPackage(stringpackageName)methodtolimittheaccesstoasinglepackage:
Intenti=newIntent();
i.setPackage("com.example.myapplication");
AnapplicationwithanexportedcomponentthatdoesnotexpectIntentsfromamaliciousapplicationisvulnerabletoIntentspoofingattacks.Asadeveloper,youshouldlimityourcomponent’sexposurebysettingdifferentpermissionlevelrequirementsinthemanifest.
Thedefaultvaluesofcertainpropertiescanbemisleadingandmaychangefromoneversiontoanother.Itisagoodideatoindicatethenatureofyouractivityexplicitly.Forexample,let’smakeouractivityPrivateActivityprivate:
<activity
android:name=".PrivateActivity"
android:exported="false">
</activity>
Ifwewanttomakeouractivityaccessibletoexternalapplications,wecanexplicitlyindicatewhichapplicationshavetheselectiveaccess.Inthiscase,we’llmakeSelectiveActivityaccessibletootherapplicationsthroughourownpermission.Then,wecanusethispermissiontoindicateselectiveaccesstoSelectiveActivityusingtheIntentfilter,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>
NoteIntentfiltersarenotasecurityfeature.Theyperforminputvalidationinyourreceiverinordertoverifythedatareceived.
SecuringthecontentprovidersInChapter2,SecurityinAndroidApplicationswehavelearnedaboutthecontentprovidermechanismthatallowsapplicationstosharerawdata.OneexternalcomponentcanuseanauthoritynameasahandletoperformSQLqueriestobothreadand/orwritecontent.Weshouldbecarefulanduseacontentprovideronlywhenitiscompletelynecessaryandtakethefollowingprecautions:
Useseparatereadandwriteprovider-levelpermissions.Wecanspecifyeachofthemwiththeattributeandroid:readPermissionandandroid:writePermission.Wecanalsouseboththeattributesbyusingandroid:permission.Usepath-permissiontospecifyeachURIthatyouwanttocontrol.Inthisway,youcanallowpermissionforasingleordifferentURIsinyourprovider.
ThismechanismisalsovulnerabletoSQLinjections.Inordertoeasilyavoidthisvulnerability,Androidsupportsparameterizedqueries.Thecontentprovidermethodssupportparameterization.ThemethodsthatareusedinparameterizedqueriestoacontentproviderarethesameastoanyotherSQLdatabase,andwehavealreadyseentheminthischapter.
SummaryInthischapter,youlearnedhowtomitigatethemostimportantvulnerabilitiesthatcanaffectourAndroidapplication.Youknowhowtouseregularexpressionsinordertovalidateaninput.YouhavealsolearnedaboutSQLinjectionsandhowparameterizedqueriescanhelpovercomethisvulnerability.Weknowhowtohandleuserandcriticalinformation.Finally,welearnedhowtouseIntentsandcontentprovidersinthemostsecurewaypossible.
Inthenextchapter,youwilllearnhowtopreservetheprivacyofourdata.Youwilllearnhowtohandlethedatawhenstoredlocally,thedifferentpossibilities,andwaystosecurethem.Youwillalsolearnaboutcryptographyandhowtoencryptlocaldata.
Chapter5.PreservingDataPrivacyMostapplicationsneedtosavesomekindofdata.YouwanttolearnhowtousethestorageoptionsprovidedbytheAndroidsystem,howcanyouprotectyourdataapplication,whatsecuritymeasuresshouldbetakenineachtypeofstorage,andhowcanyouuseencryptioninAndroidtopreservetheprivacyofyourdata.
ThischapterpresentsthemechanismsofferedbyAndroidtopreserveuserdataprivacy.Youwilllearntohandledatawhenit’sstoredonthedevice,whataretherisksinvolvedwiththestorage,thedifferentstorageoptions,andhowtosecurethestorage.Youwillalsolearnaboutcryptographyandhowtoencryptlocaldata.
Thetopicsthatwillbecoveredinthischapterare:
DataprivacyEncryptionUsingencryptiontostoredata
DataprivacyDataprivacyisanimportantconcernforapplicationsbecausealotofinformationisstoredandmanagedintheapplications:contacts,e-mails,bankaccounts,messages,agenda,socialnetworks,andsoon.Someofthisinformationcanalsobeconsideredassensitivedata.Sensitivedatacanbeanyofthefollowingtypesofinformation:
InformationthatallowsyoutoidentifyadeviceortheuserofthatdevicesuchasthephonenumberortheInternationalMobileStationEquipmentIdentity(IMEI)numberofthatdeviceInformationfromtheresourcesofthedevicesuchastheGPSlocationofthatdeviceInformationcreatedandmanagedbytheapplicationsUsers’personaldatasuchasphotosormessages
Asadeveloper,yourresponsibilityistoprotecttheprivacyoftheinformationthatisstoredbyyourapplication.TherearedifferentmechanismstostoreyourapplicationdatainAndroid,andeachstoragemechanismismeanttokeepaspecifickindofinformation.ThestoragemechanismsprovidedbyAndroidaresharedpreferences,internalandexternalstorage,anddatabasestorage.
SharedpreferencesSharedpreferencesareusedtosavethecollectionofkey-valuepairsoftheprimitivedatatypessuchasboolean,float,int,long,andstring.Thesekey-valuespairsaresavedinyourapplicationdataintheformofanXMLfile,whichisstoredonthedeviceat/data/data/yourpackage/shared_prefs/.Ifyouonlyneedonesharedpreferencefile,youcangetthedefaultonebyusingthegetPreferences()method.Ifyouneedtocreatemorethanonesharedpreferencefile,youcanspecifyitsnamebyusingthegetSharedPreferences()method.Boththesemethodsarereceivedasparametersintheoperatingmode.Theoperatingmodeisstaticfinalint,whichcanhavethefollowingvalues:
MODE_PRIVATE:ThesharedpreferencesinthismodeareprivateandonlyyourapplicationcanworkwiththemMODE_WORLD_READABLE:ThesharedpreferencesinthismodecanbereadbyotherapplicationsMODE_WORLD_WRITEABLE:Thesharedpreferencesinthismodecanbeeditedbyotherapplications
Toillustratethesethreemodes,createanewapplicationprojectandintheonCreatemethodofthemainactivity,addthefollowingtocodetocreatethreesharedpreferencefiles:
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,thereadablesharedpreferencefileisnamedMyReadablePrefsFile,andthewriteablesharedpreferencefileisnamedMyWriteablePrefsFile.Ineachfile,wesaveaBooleanvalue.ExecutetheapplicationandopentheDDMSperspective.OpentheFileExplorertabandnavigatetoyourapplicationfilesunder/data/data/yourpackage/.You’llseethatanewshared_prefsfolderhasbeencreatedandinsidethisfolderthethreepreferencefileshavealsobeencreated,asshowninthefollowingscreenshot:
Observethesystempermissionsofthethreepreferencefiles.TheMyReadablePrefsFilefileallowsanyuserofthesystemtoreaditandtheMyWriteablePrefsFilefileallowsanyuserofthesystemtowriteit.Creatingasharedpreferencefileusinganyofthesetwomodesisverydangerousastheprivacyofthedatastoredinthemisnotpreserved.Therearebettermechanismsthansharedpreferencestodistributedatabetweenapplicationssuchasthecontentproviders.
NoteAlwayscreateyoursharedpreferencesusingtheprivatemodetoreducesecurityholes.
Themodeflagofthesharedpreferencesdeterminesonlythesystempermissionofthefile.TheXMLfileisnotencrypted.YoucancheckthisbydownloadingtheMyPrefsFilefilefromtheDDMSperspective.Openthefileusinganytexteditorandnoticethatthesaveddataisnotencryptedandcanberead.Thecontentofthedownloadedsharedpreferencefileisasshowninthefollowingcode:
<?xmlversion='1.0'encoding='utf-8'standalone='yes'?>
<map>
<booleanname="KeyA"value="true"/>
</map>
Theactualuser,anyapplicationwiththerootsystempermission,oranyattackerthatgainsaccesstothedeviceisabletoreadthisfile.
NoteDonotsavesensitivedataonsharedpreferencesastheyarestoredinanunencryptedfile.
FilesintheinternalstorageInternalstorageallowsyoutosaveanytypeoffileinyourapplication’sdatadirectory,whichisstoredonthedeviceat/data/data/yourpackage/files/.Tocreateafile,youcanusetheopenFileOutput()methodinwhichyoucanspecifythemodeflagasaparameter.Themodeflagcanhavethefollowingvalues:
MODE_PRIVATE:Thefileisprivateinthismodeflagandonlyyourapplicationcanworkwithit.MODE_APPEND:Inthismodeflag,ifthefilealreadyexists,dataiswrittentotheendoftheexistingfile.Ifthefiledoesnotexist,thesystempermissionsforthefilearelikethepermissionsforMODE_PRIVATE.MODE_WORLD_READABLE:Thefileinthismodeflagcanbereadbyotherapplications.MODE_WORLD_WRITEABLE:Thefileinthismodeflagcanbeeditedbyotherapplications.
Justlikethesharedpreferences,creatingafileusingtheMODE_WORLD_READABLEorMODE_WORLD_WRITEABLEflagisverydangerousastheprivacyofthefilecontentisnotpreserved.Infact,boththeflagsweredeprecatedinAndroidAPILevel17.
NoteDonotusetheflagsMODE_WORLD_READABLEorMODE_WORLD_WRITEABLEtocreateyourfiles.
Thecreatedfilesarenotencrypted,thereforeyoucanencryptthefilecontenttopreserveitsprivacy.
FilesintheexternalstorageExternalstoragereferstoaworld-readablepartofstorageinanAndroiddevice.WetendtothinkaboutexternalstorageasanSDcard,butactually,externalstoragecanalsobeanon-removablestorage.Externalstoragemaynotalwaysbeavailable,forexample,iftheSDcardisremovedincasethestoragewasprovidedbyanSDcard,orifthestoragehasbeenmountedtoaPC.Forthisreason,youmustalwayscheckexternalstoragestatebeforeusingit,usingthefollowingcode:
StringexStorageState=Environment.getExternalStorageState();
Intheexternalstorage,therearetwotypesoffiles:publicandprivate.Thesetwotermsshouldnotbeconfusedwiththefilepermissions.Thepublicandprivatefilesinexternalstoragearediscussedindetailasfollows:
Publicfiles:Thesefilesintheexternalstoragearefilesthatcanbesharedwithotherapplications,suchaspictures,music,orringtones.Tofetchthepathofthedirectoriesinwhichthesetypesoffilesshouldbestored,youcanusetheEnvironment.getExternalStoragePublicDirectory()method.Youindicatethetypeofthepubliccontentyouwanttoworkwithasaparameter.SomeexamplesforthistypeflagareDIRECTORY_PICTURES,DIRECTORY_ALARMS,DIRECTORY_DOCUMENTS,DIRECTORY_MUSIC,andDIRECTORY_RINGTONES.Privatefiles:Thesefilesontheexternalstoragearefilesthatbelongtoyourapplicationandhence,theyhavenoutilityoutsideyourapplication.Thesefilesareremovedwhenyourapplicationisuninstalled.Rememberthatalthoughthesetypesoffilesbelongtoyourapplication,theirpermissionsarestillworldreadable.Togetthepathofyourprivatedirectory,youcanusethecontext.getExternalFilesDir()method.
NoteDonotsavesensitiveinformationonexternalstoragebecausefilesinitaregloballyreadableandwriteable.
ThedatabasestorageSQLitedatabasesallowyoutostoreyourdatainaprivatedatabase.Thedatabaseisa.dbfile,whichiscreatedintheinternalstoragedirectoryofyourapplication.Thespecificpathforthisfileis/data/data/yourpackage/databases/.Databasesareprivatebutnotencryptedandthus,theuseroranyattackerthatgainsaccesstothedevicecanreadthedatabasecontent.
NoteSensitivedatashouldbeencryptedandverysensitivedatashouldnotbesavedonthedevice.
EncryptionEncryptionistheprocessofencodingdataintoaformthatcannotbeunderstoodbyunauthorizedusers.Sensitivedatastoredinthedeviceshouldbeencryptedtopreserveitssecurity.Youcanencodedatatosaveitassharedpreferences,asfilesintheinternalstorage,indatabases,oreveninexternalstorage.Butyoushouldrememberthatsensitivedatamustnotbestoredonexternalstorage.Therearetwotypesofencryptionmethods:
Symmetric:Insymmetricencryption,thekeysforencodinganddecodingarethesame.Someexamplesofwell-knownsymmetricalgorithmsareDES,TripleDES,AES,Serpent,Twofish,andBlowfish.Asymmetricorpublic-key:Inasymmetricorpublic-keyencryption,thekeyforencodingisdifferentfromthekeyfordecoding.Theencryptionkeycanbepublicandhence,anyonecanencodedatausingthepublickey.Butonlytheowneroftheprivatekeyisabletodecodeit.Someexamplesofwell-knownasymmetricalgorithmsareRSA,Diffie-Hellman,ElGamal,andDSA.
Usingasymmetricalgorithmisenoughtoencryptourdatasincenobodyelseneedsthepublicencryptionkey.Thefollowingfigureexplainshowsymmetricencryptionworks:
Let’sseeanexampleofhowtoencryptsomeinformation.TheclassthatprovidesimplementationsforencryptionanddecryptionistheCipherclassfromthejavax.cryptopackage.Tousethisclass,youneedtocreateaninstanceindicatingtheencryptionalgorithmandoptionallythemodeorthepadding.Youcanseebothexamplesinthefollowingcodesnippets:
Cipherc=Cipher.getInstance("AES");
Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");
ThenextstepistoinitializetheinstanceusingtheinitmethodoftheCipherclass.Thismethodreceivestheoperation—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—admitmoreparametersthatcanbeconsultedintheAndroidreferenceathttp://developer.android.com/reference/javax/crypto/Cipher.html.
TheencryptionmethodsThefollowingcodeshowsthecompletemethodtoencryptatextusingtheencryptionmethodsdiscussedintheprecedingsection:
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;
}
Thefollowingcodeshowsthecompletemethodtodecryptatextusingthedecryptionmethodsdiscussedintheprecedingsection:
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);
}
GeneratingakeyTogenerateakeyinordertoencryptordecryptyourdata,youcanjustwritedownyourownkeyasaStringdatatype.Forexample,youcanusethefollowinglineofcodebutwithadifferentkey:
privatefinalStringkey="12345678901234567890123456789012";
ToobtainaKeyobjectsothatitcanbepassedasaparametertoyourencryptionanddecryptionmethods,youcanusetheSecretKeySpecclass.Thesimplestconstructorofthisclassreceivesthekeybytesandalgorithmname,asshowninthefollowinglineofcode:
SecretKeySpecsks=newSecretKeySpec(key.getBytes(),"AES");
Althoughwritingyourownkeyissimple,keepingitvisibleinyourcodeisnotsecure.Anyattackerthatgainsaccesstoyourcodecangetthekey.TherightwaytogenerateyourkeyisbyusingtheSecureRandomandKeyGeneratorclasses.Theobjectiveistoobfuscatethekey.
TheSecureRandomclass,asspecifiedintheAndroidreference,generatescryptographicallysecurepseudorandomnumbers.Usingthedefaultconstructorisrecommendedsothataninstanceofthestrongestproviderisreturned.Settingaseedmayalsobeinsecurebecauseitmayreplacethestrongdefaultseed.TheKeyGeneratorclassgeneratessymmetriccryptographickeys.Youshouldremembertosavethegeneratedkeyssothatyoucanusethemlater,evenwhentheapplicationisclosedandrestarted.
NoteYoushouldinvoketheSecureRandomclassusingthedefaultconstructorandwithoutsettinganyseed.
Thefollowingcodeshowsthecompletemethodtogenerateakeyforbothencryptionanddecryption:
publicSecretKeySpecgenerateKey()throwsNoSuchAlgorithmException
{
SecureRandomsecureRandom=newSecureRandom();
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("AES");
keyGenerator.init(256,secureRandom);
SecretKeySpecsks=newSecretKeySpec(key.getEncoded(),"AES");
returnsks;
}
UsingencryptiontostoredataUsingallthemethodsdiscussedintheearliersections,youcannowencryptanyinformationinyourapplication,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:
Thepreviousexamplecanbeadaptedtoencryptthecontentofafileontheinternalstorageofyourapplication,asshowninthefollowingcode:
StringmyData="Mysecretinformationinmyinternalfile";
SecretKeySpecsks=generateKey();
byte[]encoded=encrypt(myData,sks);
FileOutputStreamfos=
openFileOutput("MyEncryptedFile.txt",Context.MODE_PRIVATE);
fos.write(encoded);
fos.close();
Onexecutingthecodeinyourmainactivity,theMyEncryptedFile.txtfilewillbecreatedintheinternalstorage,asseeninthefollowingscreenshot.Downloadthefileandopenitinanytexteditor.Noticethatthecontentisnotunderstandablebecauseitisencoded.
Itismandatoryforyoutostorethepersistentdataencryptedretainingthekeythathasbeenusedforencoding.Thekeycannotbesavedintheinternalstorageasitisconsideredtobesensitivedata.InAndroid4.3,theKeyStorefacilitywasprovidedbutKeyStoreonlystorespublicorprivatekeys.SymmetrickeyscannotbestoredinKeyStore.Toprovideadditionalprotection,thekeyshouldnotbedirectlyaccessibletotheapplication.
NoteThekeyusedtoencryptyourdatashouldbekeptinasafeplace.Ifyoulosethekey,thedatacannotbedecoded.
Thebestsolutiontokeepyourkeysafeistosendittoyourserversothatthekeyisneverallocatedinthedeviceitself.Theuseroranyattackerthatgainsphysicalaccesstothedevicecannotobtainthekey.InChapter6,SecuringCommunications,youwilllearnhowtoprotectyourexternalcommunications.
Analternativesolutionistogeneratethekeyfromapasswordthattheuserhastointroducewhenstartinghis/herapplication.Thekeyisthereforenotstoredinthedeviceandisrememberedbytheuser.Thissolutionisverysecurebutitrequirestheusertointroduceapasswordeverytimetheapplicationisstarted,affectingtheusabilityofyourapplication.InChapter7,AuthenticationMethods,youwilllearnmoreabouttheauthenticationmethods.Togenerateakeyfromapassword,youcanusethePBKDF2algorithmimplementedintheSecretKeyFactoryclass,asshowninthefollowingcodesnippet:
SecretKeyFactoryskf=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
ThekeyisgeneratedcreatingaPBEKeySpecobject,whichreceivesthepassword,abytearrayassalt,theiterationcountofthealgorithm,andthederivedkeylength.Themethodtogenerateakeyofthistypeisasshowninthefollowingcode:
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.
SummaryInthischapter,youlearnedmoreaboutthedifferenttypesofstorageforourdataapplicationinAndroid.Youalsolearnedaboutthecharacteristicsandrisksofeachtypeofstorage.Youalsoknowhowtoencrypttheuserdataandmanagethelocalstorage.Youhavecreatedthenecessarymethodstoencryptyoursensitivedataanduseitinyourapplication.
Inthenextchapter,youwilllearnhowtopreservetheprivacyofyourdatawhenitissentorreceivedoveranetworkfromaninternalorexternaldevice.YouwillalsolearnhowtosecurethenetworkusingprotocolssuchasHTTPS.
Chapter6.SecuringCommunicationsThischapterpresentsthemechanismsofferedbyAndroidtosecurecommunicationsbetweenanAndroidapplicationandanexternalentity.Bytheendofthischapter,youwillknowhowtosecureconnections.YouwillseesomeimplementationsthroughcodeexamplesusingAndroidStudio.
Mostapplicationsneedtosharesomesortofdata.Youshouldlearnhowtoprotectthisdataespeciallywhensensitiveinformationsuchaspersonaldataorauthenticationinformationisbeingtransferred.
Thetopicsthatwillbecoveredinthischapterare:
HTTPSSSLandTSLServerandclientcertificatesAndroidStudioCodeexamplesusingHTTPS
HTTPSHypertextTransferProtocolSecure(HTTPS)isconsideredanapplicationlayerprotocolbasedonHTTP.Itisdesignedtotransferthehypertextdatasecurely.HTTPSislargelyusedbybankentities,onlineshops,andingeneral,anyonlineservicethatrequiressendingprotecteddata.
Firstofall,youneedtounderstandwhatHTTPSbeinganapplicationlayerprotocolmeans.Therearetwoimportantconceptualmodelsthatstandardizetheinternalfunctionsofacommunicationsystem.ThesemodelsaretheOpenSystemsInterconnection(OSI)modelandtheTransmissionControlProtocol/Internetprotocolsuite(TCP/IP)model.TheOSImodelconsistsofsevenabstractionlayerswhiletheTCP/IPmodelissimplifiedintoonlyfivelayers.Eachlayerdoesnotrepresentaprotocolbutalevelinwhichaprotocolisencapsulated.Forsimplicityandasitsuseismorecommon,wewillfocusontheTCP/IPmodel,discussedasfollows:
Thephysicallayer:Thislayerdefinesthemostbasicformofcommunication—theelectricalandphysicalspecifications.Theconnectionisdefinedbetweentwodirectlyconnectedelementsoveraphysicallyestablishedcommunicationmedium(cable,air,andsoon.).TheIEEE802.11specificationsoverwhichWi-Fi,Bluetooth,andevenUSBworkaresomeexamplesoftheprotocolsthatoperateinthephysicallayer.Thelinklayer:Thislayerdefinesthecommunicationestablishedbetweentwoelementsthatareinthesamelocalnetwork.Noticethattheremightbeseveralphysicalelements(routers,switches,andfurthermore)betweenthesetwoelements.TheMediaAccessControl(MAC)protocols,suchasEthernet,ISDN,orDSLworkinthislayer.Theinternetlayer:Thislayerisresponsibleforestablishingcommunicationbetweentwoelementsacrossmultiplenetworks.Therearetwomainfunctionscarriedoutinthislayer:hostidentificationandpacketrouting.ThemostknownexampleofaprotocolworkinginthislayerisIP,withIPv4andIPv6beingthemostextendedversionsofIP.Thetransportlayer:Thislayerdefinesthecommunicationbetweentwoprocessesindifferenthoststhatcanpotentiallybeseveralnetworksapart.Thislayerusesportsforthepurposeofprovidingcommunicationchannelsneededbytheapplications.ThemostcommonprotocolsthatworkonthetransportlayerareTCPandUDP.WhileTCPisconnection-orientedandisinchargeofidentifyinglostpackagesandresendingthem,UDPisconnectionlessanddoesnotperformthesechecks.Theapplicationlayer:Thisisthelayerthatapplicationsuseinordertoprovideuserservices.Thislayeristhemostimportantfordevelopers,sinceitisusuallytheonewewillbeworkingwith.Themodelofthislayerenablesyoutotreatthetransportlayerandlowerlayersasablackbox;theyprovideaserviceandyoudonotneedtoworryaboutthem.Therearehundredsofprotocolsthatworkovertheapplicationlayer,forexampleHTTPanditssecureversionHTTPS,FileTransferProtocol(FTP),SimpleMailTransferProtocol(SMTP),andsoon.TheapplicationlayerintheTCP/IPmodelcanbecomparedtoacombinationoftheapplicationlayer,
presentationlayer,andsessionlayerintheOSImodel,asshowninthefollowingfigure:
HTTPSisconsideredtobeanapplicationlayerprotocolthatusescryptographicmethodsbasedonSecureSocketsLayer(SSL)orhiselderbrotherTransportLayerSecurity(TLS)toensurethesecurityofsensitivehypertextdata.However,technically,itisnotaprotocolitselfbuttheresultofcombiningHTTPintheapplicationlayerwithSSLorTLSinthetransportlayer.Thesecurityisthereforenotprovidedintheapplicationlayerbutinthetransportlayer.HTTPSalsospecifiesthatthetransportlayershouldusetheTCPprotocoltoensurethateverypackageisreceivedcorrectly,asshowninthefollowingfigure:
AlthoughHTTPSisbasedontheapplicationlayerprotocolHTTP,therearesomedifferencesbetweenthetwoofthem.Themostimportantare:
URLsstartwithhttp://whenusingtheHTTPprotocolandwithhttps://whenusingtheHTTPSprotocolBydefault,HTTPusestheTCPport80.Ontheotherhand,HTTPSusesport443bydefaultHTTPisvulnerabletoman-in-the-middleattacksandeavesdropping,andisdesigned
tosolvethesevulnerabilitiesandminimizetherisks
IfyouwanttolearnmoreaboutthedifferencesbetweenHTTPandHTTPS,youcanuseapacketanalyzertoseehowtheexchangeofhypertextisperformedwitheachprotocol,asshowninthefollowingscreenshot.Todothis,werecommendWireshark(http://www.wireshark.org/),afreeandopensourcesoftware(OSS).YouwilllearnmoreaboutthistoolinChapter10,SupportingTools.
SSLandTLSSSLisacryptographicprotocolthatsupportssecureconnectionsoveranetwork.SSLwasoriginallydesignedbyNetscape.TherearethreemainversionsofSSLandbeingthelatestone,SSL3.0isthemostcommonlyusedovertheInternet.SSL3.0issupportedby99.5percentofthewebsitesontheInternet.
TLSisanupdateofSSL3.0.ItiscompatiblewithSSL3.0butitweakensthesecuritylevel.ThemostextendedversionofTLSisTLS1.0althoughtherearetwoupdates:TLS1.1andTLS1.2.TLS1.0issupportedby99.3percentofthewebsitesontheInternet.
AnSSLorTSLconnectionisalwaysinitiatedbytheclient.DatatransferredundertheSSLprotocolisencryptedusingasymmetricalalgorithmlikeDataEncryptionStandard(DES).Anasymmetricalalgorithmisusedtoexchangethekeysforthesymmetricalalgorithm.ThebasicstepstoestablishanSSLconnectionareasfollows:
1. Client->server:Theclientinitiatesthecommunicationwiththeserversendinga“Hello”message.Thismessagecontainsdifferentcryptographicoptionsavailabletotheclientsortedbypreferenceofuse.
2. Server->client:TheserverrespondsbysendingaHellomessage.Inthiscase,themessagecontainsthecryptographicmethodandthecompressionmethodchosen.
3. Server->client:Theserversendstheirdigitalcertificate.ThestandardistouseanX.509certificate.Iftheserverrequiresacertificatefromtheclient,aCertificateRequestmessageissent.
4. Client->server:Theclientcross-checksthecertificatereceivedfromtheserverwithalistofknownauthorities.Iftheauthorityisnotrecognized,theclientcanasktheuserforpermissiontomanuallyacceptthecertificate.Theclientalsoassessesiftheconnectionparametersareadequate.Ifeverythingisacceptable,theclientgeneratesasymmetricrandomkey,whichiscypheredwiththeserverpublickeyreceivedinstep3.Thecypheredsymmetrickeyisthensenttotheserver.
5. Client->server:Theserverreceivestheencryptedsymmetrickeyandproceedstodecryptitusinghisprivatekey.
6. Client<->server:Nowboththeclientandtheserverknowthesymmetrickeyandcanstartasecureconnection.
ServerandclientcertificatesInthissection,youwilllearnmoreabouthowcertificatesareusedandgenerated.Acertificateisadigitallysignedstatementfromanauthoritythatgrantsacertainvaluetothepublickeyofthesubject.Theyareusedinasymmetricencryptionmethods.
X.509certificateisastandardformatandmusthavethefollowinginformation:
Version:ThisistheX.509versionnumberSerialnumber:ThisisthesequencenumberofthecertificateSignaturealgorithm:ThisistheidentifierofthealgorithmusedtosignthecertificateIssuer:ThisisthenameoftheauthoritythatsignsthecertificateValidity:ThisistheperiodoftimeduringwhichthecertificateshouldbeconsideredvalidSubject:ThisisthenameofthesubjectofthepublickeySubjectpublickey:Thisisthepublickeyitselfanditsrelatedinformation
Youwillnowlearnhowtocreateaself-signedX.509certificatewithnoadditionalinstallationnecessarywhatsoever.Youwillseetwoeasywaystogenerateacertificate:usingatoolavailableineveryJavaDevelopmentKit(JDK)calledKeytoolfromtheterminalandusingthesametoolfromAndroidStudioinamorevisualway.TherearemanyotheroptionstocreatecertificatesliketheOpenSSLclient.
KeytoolintheterminalOpenyouroperatingsystemterminalorgotoTools|OpenTerminalinAndroidStudio,andwritethefollowingcommand:
keytool-genkey-keyalgRSA-aliasselfsigned-keystoremy_keystore.jks-
storepasspassword-validity360-keysize2048
Theparameter–genkeyistheactionthetoolandisgoingtoperform.Inthiscase,itwillgenerateakey.Theparameter–keyalgspecifiesthealgorithmtobeused;inthiscase,wewanttouseRSA.Theparameter–aliasisforthenameoraliasofthekeysbeinggenerated.Theparameter–keystoreindicateswhichJKSfileisgoingtobeusedtostorethekeys.Theparameter–storepassindicatesthemasterpasswordusedtoaccesstheJKSfile.Ifthefileisbeingcreatedjustliketheonecreatedinthisexample,youcansetthepassword,butifthekeystorealreadyexists,youshouldintroduceitspassword.Theparameter–validityspecifiesthenumberofdaysthecertificateisvalid.Finally,withtheparameter–keysize,youcanindicatethesizeofthekeyinbits.Inthisexample,theparameter–keysizehasavalueof2048becausewehaveusedanRSAalgorithmwhosekeysarenormallybetween1024and2048bits.
Theexecutionofthepreviouscommandwillpromptasequenceofquestions.Makesurethatwhenaskedforyourfirstnameandlastname,youanswerwiththedomainnameoftheserveryouwanttogetthecertificatefrom.Ifyouhaveproblemsexecutingthis,youcanaddthekeytooltothepathofthesystem.Theapplicationisavailableinthe/binfolderofyourJDKinstallationfolderandcanalsobeexecuteddirectlyfromthere:
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.Thisfilecontainsbothprivatekeyandpublickeycertificatessomakesurenottoshareitasyourprivatekeyiswhatshouldbekeptfromotherentities.Inordertoextractthecertificate,youcanexecutethefollowingcommand:
keytool–export–aliasselfsigned–filecertificate.crt–keystore
my_keystore.jks–storepasspassword
Thiswillgenerateafilecalledcertificate.crt,whichcontainsthecertificate.Usingtheverysametool,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.IfitwassignedbyadifferentCA,IssuerwouldbethatCA.
AndroidStudioAndroidStudiohasatooltosignyourAPK.ThisoptioninternallymakesuseofkeytooltocreateacertificatewithwhichtheAPKislatersigned.Youcanusethefirststepofthisprocesstogenerateyourcertificate.NavigatetoBuild|GenerateSignedAPK.Awizardwillappearaskingyoutoselectanalreadyexistingcertificateorcreateanewone.ClickonCreateNewandthefollowingwindowwillappear:
Asyoucansee,itasksfortheexactsameinformationwefilledinusingthekeytool.Youcanfollowthesameinstructionsasintheprevioussectiontofilltheinformationrequiredinthisform.
Ifyouwanttolearnmoreaboutcertificatesandcertificateauthorities,youcancheckthesectiononAppSigningintheAndroiddevelopmentdocumentationsincethesignatureofappsalsousesthecertificatesandcertificateauthoritiesathttp://developer.android.com/tools/publishing/app-signing.html.
CodeexamplesusingHTTPSYoualreadyunderstandhowHTTPSworkstheoretically,buthowcananAndroiddeveloperusesecureconnectionsusingHTTPS?
ToestablishanHTTPconnection,allyouneedtodoisrunthefollowingthreelinesofcode:
URLurl=newURL("http://wikipedia.org");
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
InputStreamin=connection.getInputStream();
Wikipediasupportssecurecommunications,solet’schangethecodetomakeituseHTTPSinsteadofHTTP,asshowninthefollowingcode:
URLurl=newURL("https://wikipedia.org");
HttpsURLConnectionconnection=(HttpsURLConnection)url.openConnection();
InputStreamin=connection.getInputStream();
Canyouseethedifference?Well,ifyoucanseethedifference,congratulations!Youhaveaverysharpeye.Ifyoucan’t,hereisalittlehint:checktheprotocolintheURLagainandtheHttpURLConnectionclass.NowyouseethelittlesafterhttpintheURLandintheclassname,andyes,thatisallyouneedtodotostartasecurecommunicationwithaserverthatsupportsHTTPS.
Easyright?Well,thatisnotentirelytrue.YoumayworkwithcertificatesthataresignedbyatrustedCertificateAuthority(CA)oryoumaynotworkwithcertificatessignedbyatrustedCA.Therearethreedifferentcaseswherethiscanhappen:
TheCAthatissuedthecertificateisunknownThecertificatewasself-signedTheserverismissinganintermediateCA
IftheissuerofthecertificateisanunknownCA,anSSLHandshakExceptionwilloccur.Ifyouknowthisisgoingtohappen,youcancreateHttpsURLConnection,whichtrustscertainCAsthatarenotinthelistofthesystem-trustedCAs.TheclassTrustManagerisusedbythesysteminordertovalidateunknowncertificates.Inthefollowingexample,wewillcreateKeyStore,whichcontainsourtrustedCAs.WithKeyStore,wewillinitiateTrustManager,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,thelastfourlinesofthecodearesimilartowhatweweredoingbeforeworryingaboutthecertificateauthorities.Wehaveremovedsometryclausesforthesakeofcleancode,butifyoucopythecodetoAndroidStudio,justfollowitssuggestionstotreatexceptions.
Inthisexample,weusedthecertificatethatwegeneratedusingtheJavatool—keytool.Ifyouremember,thecertificatewegeneratedwasself-signed,whichisthesecondcaseandnotthefirst.Fromacodingperspective,bothsituationsaresimilar.Inthefirstone,CAisnotrecognizedsowecreateTrustManagerinordertoacknowledgeit.Inthesecondcase,itisexactlythesame,buttheissuerofthecertificateisalsothesubject.
IftheserverismissinganintermediateCA,therewillalsobeanSSLHandshakeExceptionsincethereisamissingCAinthetrustchain.Therearetwowaysyoucansolvethissituation:
Fromtheserverside:YoucanreconfiguretheservertoincludethemissingCAinthetrustchain.Thisisobviouslypossibleonlyifyouadministratetheserver.Fromtheclientside:TheonlyproblemyouhaveisthatthereisamissingCA,therefore,thatCAisanunknownCA.YoucanthereforeusetheclassTrustManageraswedidinthefirsttwocasestotrustthemissingCAdirectly.
SummaryInthischapter,youlearnedaboutnetworkcommunicationsinyourAndroidapplication.Nowyouunderstandhowthemostcommonprotocolstosecureconnectionswork.YoualsolearnedhowtousetheAPIsthatAndroidofferstosecureyourapplication’scommunications.Finally,youlearnedaboutcertificategeneration.
Inthenextchapter,youwilllearnaboutauthenticationmethods.Youwillseehowtwo-keyandthree-keyauthenticationmethodswork.Youwillalsolearnaboutusingbiometricauthenticationinyourapplication.
Chapter7.AuthenticationMethodsThischapterpresentsdifferenttypesofauthenticationmethodsusedinAndroidmobiledevices.Thischapterwillhelpreaderschoosetheproperauthenticationmethodfortheirmobileapplication.
First,youwilllearnaboutmultifactorauthenticationandthedifferentauthenticationfactors,suchastheknowledgefactor,thepossessionfactor,andtheinherencefactor.YouwillthenlearnhowtomakeyourownimplementationofaloginsystemforyourAndroidapplication.YouwillalsolearnaboutauthenticatingdifferentservicesusingAccountManager.
Thetopicsthatwillbecoveredinthischapterare:
MultifactorauthenticationLoginimplementationsAccountManager
MultifactorauthenticationIfyouthinkofanauthenticationmethod,thefirstmethodthatwillcometoyourmindwillalwaysbethecombinationofausernameandapassword.Whileitssimplicitymakesitoneofthemostextendedauthenticationmethodsinallkindsofsoftware,itisnotthesafestmethod.Themultifactorauthenticationapproachcombinesasetofauthenticationmethods.Accessisgrantedonlyifeachmethodderivesapositiveresult.Two-factorauthenticationandthree-factorauthenticationinvolvetwoandthreeauthenticationfactors,respectively.Althoughtwo-factorauthenticationandaboveareoftenconsideredtobestrongauthenticationmethodsandareinfactmoresecure,youcanalsoachievestrongauthenticationforyourserviceusingonlyoneauthenticationfactor.Therearethreekindsofauthenticationfactorsthatserveasataxonomyforauthenticationtechniques:theknowledgefactor,thepossessionfactor,andtheinherencefactor.
TheknowledgefactorThecombinationofausernameandpasswordisanexampleofaknowledgefactor.Whenusingaknowledgefactor,theuserisrequiredtoprovideinformationhe/sheknowsinordertograntaccess:somethingtheuserknows.
Themostwidelyusedmethodsare:
Username/password:Thecombinationofacertainkindofidentifierfortheuser,generallyausernameorane-mailaddress,andapasswordisthemostextendedauthenticationtechnique.Whiletheusernameore-mailaddressmaybepublic,thepasswordshouldalwaysremainasecret.Pattern:Patternsareusedasauthenticationmethodssincethehumanbrainismorelikelytoremembergraphicalpatternsthanstringsofcharactersornumbers.Thereareseveraltypesofpatternsthatofteninvolvea3x3gridalthoughbiggergridsarealsoused.PIN:ThePINisaverybasicpasswordthathasbeentraditionallyusedinthebankingsystemforATMs,creditcards,andsoon.Itconsistsofanarrayofdigits.Itistechnicallyanimplementationofthepasswordtechniques,whereonlydigitsareallowed.
ThepatternandPINtechniquesareavailablebydefaultastheaccesscontroltoyourAndroidsystem,asshowninthefollowingscreenshot:
ThepossessionfactorThemostbasicandwell-knownexampleofapossessionfactorisakeythatopensadoor.Inordertoauthenticateausertryingtoaccessaresource,theyarerequiredtoprovideaphysicalobjecttheypossess:somethingtheuserhas.
Thereareseveralexamplesofpossessionfactors.Themosttypicaltechniquesbasedonapossessionfactorarephysicaltokenssuchassmartcardsormagneticcards.ThetechniquemostcommonlyusedinAndroidisprobablythecryptographickeys.Wealreadylearnedaboutcryptographickeysintheearlierchapters,andalthoughthesekeysaredigitalandtheuserdoesnothavematerialaccesstothem,theyareconsideredassomethingtheuserpossesses.ThereareotheralgorithmslikeTime-basedOne-TimePassword(TOTP).TOTPconsistsofcombiningasecretkeywiththecurrenttimestamptogenerateapasswordthatistemporarilyvalid.
TheinherencefactorTheinherencefactorisbasedonsomethingtheuseris.Thetechniquesbasedonthisfactoraretheonesthatareusedfrequently,buttheoneswiththebrightestfuture.Biometricauthenticationmeasuresthedistinctivecharacteristicsofindividualstoidentifytheuser.
Therearetwotypesofbiometricidentifiers:
Physiologicalcharacteristics:Thisiswhentheshapeofthebodyismeasured.Themostcommonlyknownexamplesarethefingerprintanalysis,facerecognition,andirisorretinarecognition.InAndroid,thereareseveralimplementationsoffacerecognition,andsomesmartphonescomewithahardwaresupportforfingerprintscanliketheHTCOneMax.Behavioralcharacteristics:Thisiswhenthebehaviorofapersonismeasured.Physiologicalcharacteristicsaremoreconsolidatedthanbehavioralcharacteristics.Themostextendedbehavioralcharacteristicisvoicerecognition.TherearedifferentimplementationsofvoicerecognitionforAndroid.
LoginimplementationsWewillnowseeasmallexampleonhowtoperformauthenticationusingAndroid.Theexamplewearegoingtoseehereusestheloginandpasswordcombinationtechnique.Wearegoingtostartwithaverysimpleexampleandincreasethefunctionalitiesaswellasthecomplexitiesineveryiteration.
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,wearegoingtocheckwhetherthecombinationofausernameandpasswordisgoodornot.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();
}
Thisisobviouslynotagoodexampleofasecureauthenticationmethodbutfromtheexample,wecanlearnsomeusefulthings.Forexample,theinputTypeparameterofEditTextcanbesettotextPasswordwhenusingapasswordfield.
Youarenormallygoingtomakearequesttoyourserverinordertoauthenticatetheuser.Forexample,inthiscase,weuseSimpleHTTPClienttomaketherequest,shownasfollows:
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,evenbiggerthanthepreviousone.Inthiscase,theusernameandpasswordarebeingtransferredonlineandanyattackercouldseetheminplaintext.Inordertoavoidthis,wecanuseanHTTPSconnectionaswehaveseeninthepreviouschapter.
Therearesomeloginimplementationsthathashtheusernameandpasswordbeforesendingthemtotheserverinordertoincreasethesecurity,forexample,usingtheSHA1hashshownasfollows:
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
Theproblemwiththisimplementationisthatthehashedusernameandpasswordcanstillbesniffedbyanattackerastheyarestillbeingtransferredinplaintext.Thisisacommonmistake.Sowhenyoustorepasswords,youwanttomakesureyoustoretheirhashedversions.Thecorrectsolutionwouldbetosendthepasswordusingasecureconnection.Later,whenyouwanttocheckifthepasswordisright,youapplythehashfunctiontothepasswordprovidedbytheuserandcompareittothestoredhashedpasswordtoseewhethertheymatch.
InChapter6,SecuringCommunications,wesawhowtoestablishanHTTPSconnectionbetweenyourapplicationandaserver.Youcanusethatinformationandtheprecedingexampletocreateasecureloginimplementationforyourapplication.
AccountManagerTheAccountManagerclassprovidesaccesstoalltheregisteredusers’onlineaccounts.Thisway,theuseronlyneedstoprovidehis/hercredentialsonceforeachaccountandthenhe/shecangrantaccesstotheseapplicationsinasimplerway.UsingtheAccountManagerclass,youcangetatokenthatcanbeusedasaformofauthenticationindifferentservices.
Thestepsthatyouneedtotakeinordertomakeuseofthisfeatureareasfollows:
1. First,youneedtomodifythemanifestfileandaddpermissiontousecredentials:
<uses-permission
android:name="android.permission.USE_CREDENTIALS">
</uses-permission>
2. Onceyourapplicationcanusecredentials,youcangetaninstanceofAccountManagerusingtheget(Contextc)method:
AccountManageram=AccountManager.get(this);
3. Now,youhaveaninstanceofAccountManager,butyouneedtoknowwhichaccountsareavailable.Todothis,youcanusethegetAccountsByType(Strings)method.TheStringparameteristhenameoftheaccounttype.Inthiscase,wewilllookfortheFacebookaccounts:
Account[]accounts=am.getAccountsByType("com.facebook.auth.login");
4. Youcanalsousenullastheparametertoobtainalltheavailableaccounts:
Account[]accounts=am.getAccountsByType(null);
5. ThegetAccountsByNamemethodshouldalsobecallediftheapplicationisusingapreviouslysavedaccountselectioninordertomakesurethatthisaccountstillexistsinthedevice.YoucancheckthisbylookinguptheaccountinthearrayofaccountsreturnedbygetAccountsByName.
6. Onceyouhavealistoftheavailableaccounts,youshouldasktheuserwhichaccountistobeused.Whentheselectionisdone,youcancallthemethod,shownasfollows:
getAuthToken(Accountaccount,StringauthTokenType,Bundleoptions,
Activityactivity,AccountManagerCallback<Bundle>callback,Handler
handler).
7. YouwillgetanauthenticationtokenintheAccountManagerFuture<Bundle>objectforaparticularaccount,whichwillautomaticallyprompttheuserforacceptanceifitisrequired.
8. Incasethetokenrequestreturnsanerror,therecouldbeacachedinstanceofanauthenticationtokenthatmaybebeingused.YoucancalltheinvalidateAuthToken(StringaccountType,StringauthToken)methodtoremoveanobsoletetoken.Oncetheobsoletetokenisremoved,youcanagainrequestanewtokenusingthegetAuthTokenmethod.
SummaryInthischapter,youlearnedaboutmultifactorauthenticationandthedifferenttechniquesavailableineachauthenticationfactor.Youalsolearnedhowtomakeyourownimplementationofasimpleloginsystem.Finally,youlearnedhowyoucangetauthenticationtokenstoaccessdifferentservicesbyusingAccountManager.
Inthenextchapter,youwilllearnhowtostarttestingyourapplication,testyouruserinterface,andusethetestenvironmentinAndroidStudio.
Chapter8.TestingYourApplicationYouhavelearnedhowtocreatesecureapplications.Now,youwanttoensurethequalityofyourAndroidapplication.WhatelementscanbetestedinAndroid?Howtestcasesaredeveloped?DoesAndroidStudiosupporttesting?
ThischapterintroducesthewaysoftestinganapplicationinAndroid.InAndroid,wecandesignteststoevaluatetheuserinterface(UI),activities,services,andcontentproviders.Inthischapter,wewilllearnaboutUItesting.
Thetopicsthatwillbecoveredinthechapterareasfollows:
TestinginAndroidTheuiautomatorAPITheuiautomatorviewertoolTheUItestprojectRunningUItestcases
TestinginAndroidThesecurityandqualityofAndroidapplicationsarethekeyfactorstoitssuccess.Testinghelpsyoudiscoverbugsanderrorsinyourapplication,measureitsaccuracy,andalsoimprovesecurity.
AndroidtestingisbasedonJUnit.JUnitisaframeworktowriterepeatabletestsinJava.Itevaluateswhethertheclassthatistobetestedisworkingasexpected.TherearetwotypesofteststobecreatedinanAndroidapplication:
TeststhatcanrunontheJavaVirtualMachine(JVM):IfyouwanttoteststandardJavaclassesthatdonotcalltheAndroidAPI,youcanuseplainJUnittests.TheexecutionofthistypeoftestisfasterbecauseitdoesnotrequireanytimefordeploymentonanAndroiddevice,especiallywhenrunningonanemulator.TeststhatrequiretheAndroidSDK:IfyouneedtoevaluateclassesthatuseAndroidAPI,testshavetoberunonanAndroiddeviceusingtheAndroidJUnitextensions.Fromnowon,wewillbeusingthiskindoftestsincewewanttolearnhowtocheckAndroidclassessuchasactivitiesortheUIcomponents.
Testsareimplementedinmethodscontainedintestclasses.Thesetestsareorganizedintestpackages.Byconvention,thetestpackagenameisthesameasyourapplicationpackagesuffixedwith.test.TestclassnamesarethesameastheelementtobetestedsuffixedwithTest.Forexample,thetestclassthatevaluatesyourMainActivityfileshouldbenamedMainActivityTest.Testmethodnamesareprefixedwithtest.SomeexamplesofmethodnamesaretestLayout()andtestOnClick().
TestingtheUITheUIcanbeevaluatedusingthewhite-boxtestingorblack-boxtesting.Inthewhite-boxtesting,UIcomponentsarecheckedintheactivitiesthatmanagethem.Activitytestingwillbeexplainedinthenextchapter,thatis,Chapter9,UnitandFunctionalTests.Theblack-boxtestingisbasedontheuiautomatorAPI.ThisAPIincludesclassestocaptureandmanipulatecomponentsintheapplicationundertest.Thistypeoftestdoesnotrequireyoutoknowtheinternalimplementationoftheapplication.
AndroidStudiodoesnotdirectlysupporttheuiautomatorframework,butsinceitisavailableintheAndroidSDK,wecanuseitanyway.Thestepstocompletethetestingprocessareasfollows:
1. Installtheapplicationundertestonadevice(realdeviceoranemulator).2. AnalyzetheUIcomponentsoftheapplicationundertest,employingthe
uiautomatorviewertool.3. CreateaJavatestprojecttoimplementyourtestcasesusingtheuiautomatorAPI.4. CompilethetestprojectintoaJARfileandinstallitonthedevice.5. Runtheimplementedtests.
WearegoingtoproceedwithacompleteUItestingexampleinthesuccessivesections,butfirstlet’slearnabouttheuiautomatorAPI.
TheuiautomatorAPITheuiautomatorAPIisincludedintheuiautomator.jarlibrary,whichcanbefoundinyourAndroidSDKinstallationfolder,underthe<android-sdk>/platforms/directory.TheAPIincludesaTestCaseclassthatextendstheJUnitTestCaseclass:UiAutomatorTestCase.TomanipulatetheUIcomponents,theUiDevice,UiSelector,UiObject,UiCollection,andUiScrollableclassesarealsosuppliedtotheAPI.
TheUiDeviceclassTheUiDeviceclassrepresentsthedevice.WecangettheUiDeviceinstancebycallingthegetUiDevice()method.Withthisinstanceobject,youcancheckpropertiessuchastheorientationorthedisplaysize.Youcanalsoperformdevice-levelactionssuchasclickingontheHomebuttonortakingascreenshot.Someexamplesoftheavailablemethodsareasfollows:
click(intx,inty):ThismethodperformsaclickatthespecifiedcoordinatesgetDisplaySizeDp():Thismethodreturnsthedisplaysizeindevice-independentpixelspressBack():ThismethodsimulatesapressonthebackbuttonpressHome():Thismethodsimulatesapressonthehomebuttonsleep():ThismethodsimulatesapressonthepowerbuttontosetthescreenofftakeScreenshot(Filestorepath):ThismethodtakesascreenshotofthecurrentscreenwakeUp():Thismethodsimulatesapressonthepowerbuttontosetthescreenon
TheUiSelectorclassTheUiSelectorclassrepresentsthesearchcriteriatoqueryanyUIelementonthescreen.Ifnocomponentisfound,UiAutomatorObjectNotFoundExceptionisthrown.Ifmorethanonecomponentisfound,thefirstoneinthelayouthierarchyisreturned.TheUiSelectorclassoffersmethodstorefinethesearch.Someofthemethodsareasfollows:
checked(booleanval):Thismethodmatcheselementsthatarechecked.childSelector(UiSelectorselector):Thismethodaddsachildselectorcriteriatothecurrentselector.className(StringclassName):Thismethodmatcheselementsofthespecifiedclass.Forexample,youcansearchforbuttonsusingthefollowingcode:
newUiSelector().className("android.widget.Button")
resourceID(Stringid):ThismethodmatchestheelementwiththespecifiedID.text(Stringtext):Thismethodmatcheselementscontainingtheindicatedvisibletext.Forexample,youcanrefinetheprevioussearchforbuttonsbyaddingasecondfilter,asshowninthefollowingcode:
newUiSelector().className("android.widget.Button").text("Continue")
TheUiObjectclass
TheUiObjectclassrepresentsaUIelement.TheUiObjectinstancesareobtainedfromtheUiSelectorinstances.TheclassUiObjectprovidesmethodstoperformactionsontheUIelements.Someexamplesofthemethodsareasfollows:
click():ThismethodperformsaclickatthecenteroftheUIelementexists():ThismethodcheckswhethertheelementexistsgetText():ThismethodreturnsthetextoftheelementisChecked():ThismethodreturnswhethertheelementiscurrentlycheckedornotsetText(Stringtext):Thismethodsetsthetextwhethertheelementallowsit(whetherit’saneditablefield)
TheUiCollectionclassTheUiCollectionclassrepresentsacollectionofitems.TheUiCollectioninstancesareobtainedfromtheUiSelectorinstancesthatreturnacontainerofotherchildUIelements.Themethodsprovidedbythisclassareallrelatedtotheselectionofchildren,shownasfollows:
getChildByDescription(UiSelectorchildPattern,Stringtext):ThismethodsearchesforachildbyitsdescriptionandreturnsaUiObjectobjectgetChildByInstance(UiSelectorchildPattern,intinstance):ThismethodsearchesforachildbyitsinstancenumberandreturnsaUiObjectobjectgetChildByText(UiSelectorchildPattern,Stringtext):ThismethodsearchesforachildbyitsvisibletextandreturnsaUiObjectobjectgetChildCount(UiSelectorchildPattern):Thismethodreturnsthechildcount
TheUiScrollableclassTheUiScrollableclassrepresentsascrollablecollectionofitems.Thisclassisusefultosimulatescrollingandbringshiddenelementsintoview.TheUiScrollableinstancesareobtainedfromtheUiSelectorinstances.ThisclasspresentsmethodssimilartothemethodsoftheUiCollectionclassandalsoprovidesmethodstosimulatescrolling:
scrollBackward():ThismethodperformsabackwardscrollscrollForward():ThismethodperformsaforwardscrollscrollToBeginning():ThismethodscrollstothebeginningscrollToEnd():Thismethodscrollstotheend
TheuiautomatorviewertoolTheuiautomatorviewertoolservestotakeasnapshotofthecurrentscreenonanAndroiddevicethatisconnectedtothedevelopmentmachine.Thesnapshotallowsyoutoexaminethelayoutcomponentsthatareincludedinthescreen.YoucanlearnabouthowtheyarestructuredandtheirpropertiessuchasIDs,texts,classes,andfurthermore.TheuiautomatorviewertoolisincludedinthetoolsdirectoryoftheAndroidSDKinstallation:<android-sdk>/tools/.
Let’slookatanexampletoshowhowthistoolworks.Sinceweareperformingblack-boxtesting,theuiautomatorviewertoolcanbeappliedtoanyapplicationalthoughitisnotdevelopedbyus,nordowehaveitssourcecode.WearegoingtousethedefaultAndroidclockapplicationbyfollowingthisprocedure:
1. OpenAndroidStudioandlaunchanAndroidVirtualDevice(AVD)intheemulator.Youcanalsousearealdeviceconnectedtoyourcomputer.
2. Whenthedeviceiscompletelyloaded,opentheapplicationdrawerandselecttheClockapplication.
3. BackintheAndroidStudioIDE,clickontheToolsmenuandselecttheOpenTerminaloptiontoopentheterminalpanel.
4. Usingtheterminal,navigatetotheAndroidtoolsfolderwheretheuiautomatorviewerexecutableisfound.InUnix-basedsystems,youcanfinditbyusingthecommand:
$cdandroidSDK/tools/
5. Launchuiautomatorviewerbyusingthecommand:
$./uiautomatorviewer
6. Theuiautomatorviewertoolisnowopenandshowsanemptywindow.Clickonthebuttoniconfromthetopbar,whichhintsattheDeviceScreenshot(uiautomatordump).Thisbuttonismarkedinredinthefollowingscreenshot.Thisoptionwilltakeasnapshotoftheclockapplicationthatisbeingdisplayedintheforegroundintheemulator.
Intheuiautomatorviewer,wecaninspectthelayoutelementsofthescreen.Thefollowingscreenshotshowstheuiautomatorvieweraftercapturingthescreenfromtheclockapplication.Ontheleftsideoftheviewer,thesnapshotisdisplayed.YoucanhoverthemouseoverittonavigateandselecttheUIcomponents.Onthetop-rightpartoftheviewer,thelayouthierarchyislisted.Wecanexpandandcollapsethelayoutsandselectindividualelements.Inthefollowingscreenshotofourexample,thelayoutcontainingthehourisselected.Onthebottom-rightpartoftheviewer,thepropertiesoftheselectedcomponentaredetailed.
TheUItestprojectThetestcodetoevaluatetheUIofanapplicationhastobeincludedinanormalJavaproject.ThisJavaprojectwillbebuiltintoaJARfile,whichwillbecopiedintheAndroiddevicetoevaluatetheapplicationundertest.SinceAndroidStudiodoesnotsupporttheuiautomatorframework,forthissectionyoucanuseanyothertoolthatallowsyoucreateaJavaproject.Therequiredstepsareasfollows:
1. CreateastandardJavaproject.ThisisthetestprojectwherethetestcodewillbeimplementedusingtheuiautomatorAPI.YoucancallthisprojectUITestProject.
2. ImporttheJUnitlibraryintoyourtestproject.Currently,JUnit3.8isthesupportedversion.
3. ImporttheAndroidlibraryasanexternalJARintoyourtestproject.ThisJARisnamedandroid.jarandisstoredinyourAndroidSDKinstallationfolderunder<android-sdk>/platforms/<sdk>/.
4. ImporttheuiautomatorlibraryasanexternalJARintoyourtestproject.ThisJARisnameduiautomator.jarandisstoredinyourAndroidSDKinstallationfolderunder<android-sdk>/platforms/<sdk>/.
5. Createanewclassinthesourcefolderofyourtestproject.YoucannametheclassClockTest.java.Thisclassisusedtoimplementyourtestcaseandtherefore,hastoextendtheUiAutomatorTestCaseclass.
6. AddyourtestcodeintheClockTestclass.
YourUItestcodeisnowready.Forourexample,let’saddsomesimplecodejusttodemonstratehowUItestingworks.CreateatestmethodnamedtestOpenAlarmstoevaluatethealarmbuttonintheclockapplication.Toperformaclickonthealarmbutton,weneedtoindicateitsID,whichcanbeextractedfromuiautomatorviewer,asshowninthefollowingscreenshot:
TheresourceIdmethodoftheUiSelectorclasscanbeusedtofindtheUIcomponentwhoseIDiscom.android.deskclock:id/alarms_button.Theobjectcreatedcanbecheckedandifeverythingisfine,aclickissimulatedonit:
publicclassClockTestextendsUiAutomatorTestCase{
publicvoidtestOpenAlarms()throwsUiObjectNotFoundException{
UiObjectalarmButton=newUiObject(newUiSelector().
resourceId("com.android.deskclock:id/alarms_button"));
if(alarmButton.exists()&&alarmButton.isEnabled()){
alarmButton.click();
}
}
}
RunningUItestcasesTheJavatestprojectcreatedintheprevioussectionhastobecompiledintoaJARfiletorunyourtestcases.TheJARfilehastobecopiedontothesameAndroiddeviceinwhichtheapplicationundertestisrunning.Followthenextstepstorunyourtestcase:
1. OpentheterminalpanelinAndroidStudio(Tools|OpenTerminal).2. NavigatetotheAndroidStudiostoolsfolderwheretheandroidexecutableisfound:
$cdandroidSDK/tools/
3. GettheIDoftheAndroidtargetthatyouwanttouseinyourproject.Executetheandroidexecutablewiththelistofthetargetactions.ThiscommandwilllisttheavailableAndroidtargetsalongwiththeirIDs:
$./androidlisttargets
4. Executetheandroidexecutablewiththecreateuitest-projectaction.Thiscommandreceivesthenameoftheoutputproject(-n),theIDoftheAndroidtarget(-t),andthepathofyourJavatestproject(-p)asparameters.Thisstepistogeneratetheproject’sbuildfileasatestproject:
$./androidcreateuitest-project–nUITest-t1
-p/Users/myUser/workspace/UITestProject
NoteTheUItestprojectscanonlytargetAPI16andabove;otherwise,anerrorwillbeprompted.
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,youwillseehowtheactionsimplementedinthetestOpenAlarmstestmethodaresimulated.Theresultsareshownintheterminalpanelasyoucanseeinthefollowingscreenshot,inwhichthetestcaseexecutionhasbeensuccessful:
SummaryInthischapter,youlearnedabouttestinginAndroid.Youdevelopedblack-boxtestingforyouruserinterface.YoualsolearnedhowtocreateatestcaseforyourapplicationUIandhowyoucanrunitonadevice.
Inthenextchapter,youwilllearnmoreabouttestinginAndroid.Youwilldeveloptestcasestoevaluatetheactivitiesofyourapplication.YouwilluseunitandfunctionaltestsandsetupthetestingenvironmentusingAndroidStudio.
Chapter9.UnitandFunctionalTestsYoualreadylearnedaboutAndroidtestinginthepreviouschapter.Youknowhowtodevelopablack-boxtestoftheUIofyourapplication.Nowyouwanttolearnhowtoimplementthewhite-boxtestingforyourapplication.Aretheredifferenttypesofactivitytesting?DoesAndroidStudiosupportactivitytesting?Howcanyougettheresultsofyourtestcases?Wewillbecoveringthesepointsinthischapter.
Inthischapter,youwilllearnhowtouseunitteststhatallowdeveloperstoquicklyverifythestateandbehaviorofanactivityonitsown.Thechapterwillalsocoverfunctionaltests;theirmainpurposeistochecktheinteractionbetweencomponents.
Thetopicsthatwillbecoveredinthischapterareasfollows:
DifferencesbetweenunitandfunctionaltestsAndroidtestingAPICreatingasimpleunittestcaseCreatingasimplefunctionaltestGettingthetestresults
TestingactivitiesTherearetwopossiblemodesoftestingactivities:
Functionaltesting:Infunctionaltesting,theactivitybeingtestediscreatedusingthesysteminfrastructure.ThetestcodecancommunicatewiththeAndroidsystem,sendeventstotheUI,orlaunchanotheractivity.Unittesting:Inunittesting,theactivitybeingtestediscreatedwithminimalconnectiontothesysteminfrastructure.Theactivityistestedinisolation.
Inthischapter,wewillexploretheAndroidtestingAPItolearnabouttheclassesandmethodsthatwillhelpyoutesttheactivitiesofyourapplication.
ThetestcaseclassesTheAndroidtestingAPIisbasedonJUnit.AndroidJUnitextensionsareincludedintheandroid.testpackage.Thefollowingfigurepresentsthemainclassesthatareinvolvedwhentestingactivities:
Let’slearnmoreabouttheseclasses:
TestCase:ThisJUnitclassbelongstothejunit.framework.TheTestCasepackagerepresentsageneraltestcase.ThisclassisextendedbytheAndroidAPI.InstrumentationTestCase:Thisclassanditssubclassesbelongtotheandroid.testpackage.Itrepresentsatestcasethathasaccesstoinstrumentation.ActivityTestCase:Thisclassisusedtotestactivities,butformoreusefulclasses,youshoulduseoneofitssubclassesinsteadofthemainclass.ActivityInstrumentationTestCase2:Thisclassprovidesfunctionaltestingofanactivityandisparameterizedwiththeactivityundertest.Forexample,toevaluateyourMainActivity,youhavetocreateatestclassnamedMainActivityTestthatextendstheActivityInstrumentationTestCase2class,shownasfollows:
publicclassMainActivityTestextends
ActivityInstrumentationTestCase2<MainActivity>
ActivityUnitTestCase:Thisclassprovidesunittestingofanactivityandisparameterizedwiththeactivityundertest.Forexample,toevaluateyourMainActivity,youcancreateatestclassnamedMainActivityUnitTestthatextendstheActivityUnitTestCaseclass,shownasfollows:
publicclassMainActivityUnitTestextends
ActivityUnitTestCase<MainActivity>
ThereisanewtermthathasemergedfromthepreviousclassescalledInstrumentation.
InstrumentationTheexecutionofanapplicationisruledbythelifecycle,whichisdeterminedbytheAndroidsystem.Forexample,thelifecycleofanactivityiscontrolledbytheinvocationofsomemethods:onCreate(),onResume(),onDestroy(),andsoon.ThesemethodsarecalledbytheAndroidsystemandyourcodecannotinvokethem,exceptwhiletesting.ThemechanismtoallowyourtestcodetoinvokecallbackmethodsisknownasAndroidinstrumentation.
Androidinstrumentationisasetofmethodstocontrolacomponentindependentofitsnormallifecycle.Toinvokethecallbackmethodsfromyourtestcode,youhavetousetheclassesthatareinstrumented.Forexample,tostarttheactivityundertest,youcanusethegetActivity()methodthatreturnstheactivityinstance.Foreachtestmethodinvocation,theactivitywillnotbecreateduntilthefirsttimethismethodiscalled.Instrumentationisnecessarytotestactivitiesconsideringthelifecycleofanactivityisbasedonthecallbackmethods.ThesecallbackmethodsincludetheUIeventsaswell.
Fromaninstrumentedtestcase,youcanusethegetInstrumentation()methodtogetaccesstoanInstrumentationobject.Thisclassprovidesmethodsrelatedtothesysteminteractionwiththeapplication.Thecompletedocumentationaboutthisclasscanbefoundat:http://developer.android.com/reference/android/app/Instrumentation.html.Someofthemostimportantmethodsareasfollows:
TheaddMonitormethod:ThismethodaddsamonitortogetinformationaboutaparticulartypeofIntentandcanbeusedtolookforthecreationofanactivity.AmonitorcanbecreatedindicatingIntentFilterordisplayingthenameoftheactivitytothemonitor.Optionally,themonitorcanblocktheactivitystarttoreturnitscannedresult.Youcanusethefollowingcalldefinitionstoaddamonitor:
ActivityMonitoraddMonitor(IntentFilterfilter,ActivityResultresult,
booleanblock).
ActivityMonitoraddMonitor(Stringcls,ActivityResultresult,boolean
block).
Thefollowinglineisanexamplelinecodetoaddamonitor:
Instrumentation.ActivityMonitormonitor=
getInstrumentation().addMonitor(SecondActivity.class.getName(),null,
false);
Theactivitylifecyclemethods:Themethodstocalltheactivitylifecyclemethodsare:callActivityOnCreate,callActivityOnDestroy,callActivityOnPause,callActivityOnRestart,callActivityOnResume,callActivityOnStart,finish,andsoon.Forexample,youcanpauseanactivityusingthefollowinglinecode:
getInstrumentation().callActivityOnPause(mActivity);
ThegetTargetContextmethod:Thismethodreturnsthecontextfortheapplication.ThestartActivitySyncmethod:Thismethodstartsanewactivityandwaitsforittobeginrunning.Thefunctionreturnswhenthenewactivityhasgonethroughthefull
initializationafterthecalltoitsonCreatemethod.ThewaitForIdleSyncmethod:Thismethodwaitsfortheapplicationtobeidlesynchronously.
ThetestcasemethodsJUnit’sTestCaseclassprovidesthefollowingprotectedmethodsthatcanbeoverriddenbythesubclasses:
setUp():Thismethodisusedtoinitializethefixturestateofthetestcase.Itisexecutedbeforeeverytestmethodisrun.Ifyouoverridethismethod,thefirstlineofcodewillcallthesuperclass.AstandardsetUpmethodshouldfollowthegivencodedefinition:
@Override
protectedvoidsetUp()throwsException{
super.setUp();
//Initializethefixturestate
}
tearDown():Thismethodisusedtoteardownthefixturestateofthetestcase.Youshouldusethismethodtoreleaseresources.Itisexecutedafterrunningeverytestmethod.Ifyouoverridethismethod,thelastlineofthecodewillcallthesuperclass,shownasfollows:
@Override
protectedvoidtearDown()throwsException{
//Teardownthefixturestate
super.tearDown();
}
Thefixturestateisusuallyimplementedasagroupofmembervariablesbutitcanalsoconsistofdatabaseornetworkconnections.IfyouopenorinitconnectionsinthesetUpmethod,theyshouldbeclosedorreleasedinthetearDownmethod.WhentestingactivitiesinAndroid,youhavetoinitializetheactivityundertestinthesetUpmethod.ThiscanbedonewiththegetActivity()method.
TheAssertclassandmethodJUnit’sTestCaseclassextendstheAssertclass,whichprovidesasetofassertmethodstocheckforcertainconditions.Whenanassertmethodfails,AssertionFailedExceptionisthrown.Thetestrunnerwillhandlethemultipleassertionexceptionstopresentthetestingresults.Optionally,youcanspecifytheerrormessagethatwillbeshowniftheassertfails.YoucanreadtheAndroidreferenceoftheTestCaseclasstoexaminealltheavailablemethodsathttp://developer.android.com/reference/junit/framework/Assert.html.TheassertionmethodsprovidedbytheAssertsuperclassareasfollows:
assertEquals:Thismethodcheckswhetherthetwovaluesprovidedareequal.Itreceivestheactualandexpectedvaluethatistobecomparedwitheachother.Thismethodisoverloadedtosupportvaluesofdifferenttypes,suchasshort,String,char,int,byte,boolean,float,double,long,orObject.Forexample,thefollowingassertionmethodthrowsanexceptionsincebothvaluesarenotequal:
assertEquals(true,false);
assertTrueorassertFalse:ThesemethodscheckwhetherthegivenBooleanconditionistrueorfalse.assertNullorassertNotNull:Thesemethodscheckwhetheranobjectisnullornot.assertSameorassertNotSame:Thesemethodscheckwhethertwoobjectsrefertothesameobjectornot.fail:Thismethodfailsatest.Itcanbeusedtomakesurethatapartofcodeisneverreached,forexample,ifyouwanttotestthatamethodthrowsanexceptionwhenitreceivesawrongvalue,asshowninthefollowingcodesnippet:
try{
dontAcceptNullValuesMethod(null);
fail("Noexceptionwasthrown");
}catch(NullPointerExceptionne){
//OK
}
TheAndroidtestingAPI,whichextendsJUnit,providesadditionalandmorepowerfulassertionclasses:ViewAssertsandMoreAsserts.
TheViewAssertsclassTheassertionmethodsofferedbyJUnit’sAssertclassarenotenoughifyouwanttotestsomespecialAndroidobjectssuchastheonesrelatedtotheUI.TheViewAssertsclassimplementsmoresophisticatedmethodsrelatedtotheAndroidviews,thatis,fortheViewobjects.ThewholelistwithalltheassertionmethodscanbeexploredintheAndroidreferenceaboutthisclassathttp://developer.android.com/reference/android/test/ViewAsserts.html.Someofthemaredescribedasfollows:
assertBottomAlignedorassertLeftAlignedorassertRightAlignedor
assertTopAligned(Viewfirst,Viewsecond):ThesemethodscheckthatthetwospecifiedViewobjectsarebottom,left,right,ortopaligned,respectivelyassertGroupContainsorassertGroupNotContains(ViewGroupparent,Viewchild):ThesemethodscheckwhetherthespecifiedViewGroupobjectcontainsthespecifiedchildViewassertHasScreenCoordinates(Vieworigin,Viewview,intx,inty):ThismethodchecksthatthespecifiedViewobjecthasaparticularpositionontheoriginscreenassertHorizontalCenterAlignedorassertVerticalCenterAligned(ViewreferenceViewview):ThesemethodscheckthatthespecifiedViewobjectishorizontallyorverticallyalignedwithrespecttothereferenceviewassertOffScreenAboveorassertOffScreenBelow(Vieworigin,Viewview):ThesemethodscheckthatthespecifiedViewobjectisaboveorbelowthevisiblescreenassertOnScreen(Vieworigin,Viewview):ThismethodchecksthatthespecifiedViewobjectisloadedonthescreenevenifitisnotvisible
TheMoreAssertsclassTheAndroidAPIextendssomeofthebasicassertionmethodsfromtheAssertclasstopresentsomeadditionalmethods.SomeofthemethodsincludedintheMoreAssertsclassare:
assertContainsRegex(StringexpectedRegex,Stringactual):Thismethodchecksthattheexpectedregularexpression(regex)containstheactualgivenstringassertContentsInAnyOrder(Iterable<?>actual,Object…expected):ThismethodchecksthattheiterableobjectcontainsthegivenobjectsandinanyorderassertContentsInOrder(Iterable<?>actual,Object…expected):Thismethodchecksthattheiterableobjectcontainsthegivenobjects,butinthesameorderassertEmpty:ThismethodchecksifacollectionisemptyassertEquals:ThismethodextendstheassertEqualsmethodfromJUnittocovercollections:theSetobjects,intarrays,Stringarrays,Objectarrays,andsoonassertMatchesRegex(StringexpectedRegex,Stringactual):Thismethodcheckswhethertheexpectedregexmatchesthegivenactualstringexactly
OppositemethodssuchasassertNotContainsRegex,assertNotEmpty,assertNotEquals,andassertNotMatchesRegexareincludedaswell.Allthesemethodsareoverloadedtooptionallyincludeacustomerrormessage.TheAndroidreferenceabouttheMoreAssertsclasscanbeinspectedtolearnmoreabouttheseassertmethodsathttp://developer.android.com/reference/android/test/MoreAsserts.html.
UItestingandTouchUtilsThetestcodeisexecutedintwodifferentthreadsastheapplicationundertest,although,boththethreadsruninthesameprocess.WhentestingtheUIofanapplication,UIobjectscanbereferencedfromthetestcode,butyoucannotchangetheirpropertiesorsendevents.TherearetwostrategiestoinvokemethodsthatshouldrunintheUIthread:
Activity.runOnUiThread():ThismethodcreatesaRunnableobjectintheUIthreadinwhichyoucanaddthecodeintherun()method.Forexample,ifyouwanttorequestthefocusofaUIcomponent:
publicvoidtestComponent(){
mActivity.runOnUiThread(
newRunnable(){
publicvoidrun(){
mComponent.requestFocus();
}
}
);
…
}
@UiThreadTest:ThisannotationaffectsthewholemethodbecauseitisexecutedontheUIthread.Consideringtheannotationreferstoanentiremethod,statementsthatdonotinteractwiththeUIarenotallowedinit.Forexample,considerthepreviousexampleusingthisannotation,shownasfollows:
@UiThreadTest
publicvoidtestComponent(){
mComponent.requestFocus();
…
}
Thereisalsoahelperclassthatprovidesmethodstoperformtouchinteractionsontheviewofyourapplication:TouchUtils.ThetoucheventsaresenttotheUIthreadsafelyfromthetestthread;therefore,themethodsoftheTouchUtilsclassshouldnotbeinvokedintheUIthread.Someofthemethodsprovidedbythishelperclassareasfollows:
TheclickViewmethod:ThismethodsimulatesaclickonthecenterofaviewThedrag,dragQuarterScreenDown,dragViewBy,dragViewTo,dragViewToTopmethods:ThesemethodssimulateaclickonanUIelementandthendragitaccordinglyThelongClickViewmethod:ThismethodsimulatesalongpressclickonthecenterofaviewThescrollToToporscrollToBottommethods:ThesemethodsscrollaViewGrouptothetoporbottom
ThemockobjectclassesTheAndroidtestingAPIprovidessomeclassestocreatemocksystemobjects.Mockobjectsarefakeobjectsthatsimulatethebehaviorofrealobjectsbutaretotallycontrolledbythetest.Theyallowisolationoftestsfromtherestofthesystem.Mockobjectscan,forexample,simulateapartofthesystemthathasnotbeenimplementedyet,orapartthatisnotpracticaltobetested.
InAndroid,thefollowingmockclassescanbefound:MockApplication,MockContext,MockContentProvider,MockCursor,MockDialogInterface,MockPackageManager,MockResources,andMockContentResolver.Theseclassesareundertheandroid.test.mockpackage.Themethodsoftheseobjectsarenonfunctionalandthrowanexceptioniftheyarecalled.Youhavetooverridethemethodsthatyouwanttouse.
CreatinganactivitytestInthissection,wewillcreateanexampleapplicationsothatwecanlearnhowtoimplementthetestcasestoevaluateit.Someofthemethodspresentedintheprevioussectionwillbeputintopractice.Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.com.
Ourexampleisasimplealarmapplicationthatconsistsoftwoactivities:MainActivityandSecondActivity.TheMainActivityimplementsaself-builtdigitalclockusingtextviewsandbuttons.Thepurposeofcreatingaself-builtdigitalclockistohavemorecodeandelementstouseinourtests.ThelayoutofMainActivityisarelativeonethatincludestwotextviews:oneforthehour(thetvHourID)andonefortheminutes(thetvMinuteID).Therearetwobuttonsbelowtheclock:onetosubtract10minutesfromtheclock(thebMinusID)andonetoadd10minutestotheclock(thebPlusID).Thereisalsoanedittextfieldtospecifythealarmname.Finally,thereisabuttontolaunchthesecondactivity(thebValidateID).Eachbuttonhasapertinentmethodthatreceivestheclickeventwhenthebuttonispressed.Thelayoutlookslikethefollowingscreenshot:
TheSecondActivityreceivesthehourfromtheMainActivityandshowsitsvalueinatextviewsimulatingthatthealarmwassaved.Theobjectivetocreatethissecondactivityistobeabletotestthelaunchofanotheractivityinourtestcase.
OpenAndroidStudioandtheAndroidprojectundertest.Youcancreateablankprojectwithamainactivityandlayout.Laterinthischapter,wewilladdanexamplecodetorunthetestcases.Intheprojectstructure,thereisafolderandapackagewherethetestswill
besaved:/src/androidTest/java/<your_package>.Ifyoudon’thavethispackage,youshouldaddit.
CreatingaunittestAunittestevaluatestheactivityinisolation.Unittestsareused,forexample,tocheckamethodoftheactivityortocheckthattheactivityhasthecorrectlayout.Inthissection,wearegoingtocreateaunittestforthemainactivityofourexampleproject.
CreateanewclassinthetestpackageofyourapplicationnamedMainActivityUnitTest.ThisclassextendstheActivityUnitTestCaseclass,whichisthetestcaseclasstocreateunittests.Thetestclasshastobeparameterizedwiththeactivityundertestandyoualsoneedtoaddthetestcaseconstructor,shownasfollows:
publicclassMainActivityUnitTestextends
ActivityUnitTestCase<MainActivity>{
publicMainActivityUnitTest(){
super(MainActivity.class);
}
Forthisunittestexample,wewillcreatethesetUpmethod,andthenwewilltestthebuttonstomanagetheclock,mainlayout,andlaunchofthesecondactivity.
TheunittestsetupThefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthelayoutobjectsthatwillbeusedinthetestmethods,shownasfollows:
privateMainActivitymActivity;
privateTextViewmHour,mMinute;
privateButtonmValidate,mMinus,mPlus;
ThegetActivity()methodinitializestheactivityundertest,butrememberthatinunittests,theactivityistestedinisolationandtherefore,itisnotautomaticallystartedbythesystem.TheactivityhastobestartedinyourowncodeviaanIntentobject.ThecodeforthesetUpmethodisasfollows:
@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.Becausethetestcodeisincludedinadifferentpackage,youhavetoimporttheRclassfromtheapplicationpackage.
TheclocktestLet’sstartimplementingtestmethods.First,wewillcheckwhethertheclockworksproperly.Thetestmethodconsistsofclickingonboththebuttons,thatis,-10minand+10minandcheckingwhetherthevaluesforthehourandminutetextsaretheexpectedones.Sincetheactivityrunsinisolation,theTouchUtilslibrarycannotbeused,buttheperformClickmethodcanbeinvokedinstead,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.Onclickingtheminusbuttononce,theresultanthouris11:50.Onclickingtheplusbuttontwiceandtheminusbuttononce,thefinalhourisagain00:00.TheconditionsarecheckedusingtheassertEqualsmethod.
TipIfyouwanttotestcomplexUIevents,donotuseunittests;youshouldcreateafunctionaltest(ActivityInstrumentationTestCase2testcase).
ThelayouttestThesecondtestmethodtobeimplementedisusedtotestwhetherthelayoutiscorrect.ThetextoftheUIelementscanbechecked,ortheassertionmethodsoftheclassViewAssertscanalsobeinvoked.AsimpleexampleofaUItestforourexampleisshownasfollows:
publicvoidtestUI(){
assertNotNull("Hourtextviewnotfound",mHour);
assertEquals("Wrongbuttonlabel","Validate",mValidate.getText());
ViewAsserts.assertBottomAligned(mHour,mMinute);
}
TheactivityIntenttestThelasttestmethodwewillimplementisgoingtocheckwhetherthesecondactivityisproperlylaunched.First,theValidatebuttonisclickedtoexecutethecodethatwillcreateIntentofthesecondactivity.ThegetStartedActivityIntentmethodwillreturnifanyIntentwaslaunched.Thecodesnippetforthetestmethodisasfollows:
publicvoidtestSecondActivityLaunch(){
mValidate.performClick();
IntenttriggeredIntent=getStartedActivityIntent();
assertNotNull("Intentwasnull",triggeredIntent);
Stringpayload=triggeredIntent.getExtras().getString("hour");
assertEquals("WrongdatapassedtoSecondActivity","00",payload);
}
Inthetestmethod,Intentischeckedtoevaluatewhetheritisnull.Furthermore,thedatapassedtothesecondactivitycanbeexaminedaswell.
NoteThecreatedIntentisnotreallysenttothesystembecausetheactivityrunsinisolation.
CreatingafunctionaltestAfunctionaltestevaluatestheactivityanditscommunicationwiththeAndroidsystem.TheUIeventsorchangesinthelifecycleshouldbecheckedinafunctionaltest.Inthissection,wewillcreateafunctionaltestforthemainactivityofourexampleproject.
CreateanewclassinthetestpackageofyourapplicationnamedMainActivityTest.ThisclassextendstheActivityInstrumentationTestCase2classandhastobeparameterizedwiththeactivityundertest,shownasfollows:
publicclassMainActivityTestextends
ActivityInstrumentationTestCase2<MainActivity>{
publicMainActivityTest(){
super(MainActivity.class);
}
Forthisexampleoffunctionaltests,wewillevaluatetheUI(white-boxtesting),launchofthesecondactivity,andstatemanagement.
ThefunctionaltestsetupThefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthelayoutobjectsthatwillbeusedinthetestmethods,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.Settingthemodeasfalseisnecessarytosetoffthetouchmodeinthedevicesothatthekeyeventsarenotignored.ThismethodshouldbecalledbeforestartingtheactivitywiththegetActivitymethodandalsobecauseitcannotbeexecutedontheUIthread.
TheUItestInthefirsttestmethod,asanexampleofUItesting,wewillevaluateEditTextcontaining
thenameofthealarm.Thestepstobeimplementedforthistestareasfollows:
1. Requestthefocusoftheedittextelement.ThisstepinteractswithViewoftheapplicationandtherefore,itshouldrunintheUIthread,thatis,themainthreadoftheapplication.TorunsomecodeintheUIthread,youcanusetherunOnUiThread()methodoftheactivityundertest.
2. Sendkeyeventstowritethealarmname.Onlyaninstrumentedclassallowstosendkeyeventstotheactivityundertest.Thankstoinstrumentation,itisnotnecessarytorunthesecallsintheUIthreadeither.
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,weknowforsurethatthetexthasbeencompletelyinsertedinthefield.
TheactivityIntenttestUnlikeunittests,whenanewIntentiscreated,itissenttotheAndroidsystem.Tomonitorthelaunchedactivity,wecanregisteranActivityMonitorobjectusinginstrumentation.Anotherdifferencebetweenfunctionalandunittestsisthatinafunctionaltest,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.
ThestatemanagementtestThislasttestmethodcheckswhethertheactivitystateispreservedwhentheactivityis,forexample,pausedorrestarted.Forthisexample,wewillevaluatehowourmainactivitybehaveswhenitispausedandresumed.Theexpectedbehavioristhatthehoursandminutesaremaintained.Performingareliabletestisnecessarytodirectlychangethetextviewsbetweenthepausingandresumingoftheactivity.Thischangeensuresthattheactivityactuallyrestoresthepreviousstate.Thecodeofthismethodisasfollows:
@UiThreadTest
publicvoidtestStateManagement(){
mHour.setText("02");
assertEquals("02",mHour.getText());
getInstrumentation().callActivityOnPause(mActivity);
mHour.setText("11");
getInstrumentation().callActivityOnResume(mActivity);
assertEquals("02",mHour.getText());
}
Noticethe@UiThreadTestannotationbeforethemethod.Methodsannotatedwith@UiThreadTestareexecutedintheUIthread.Intheprevioustestmethod,thesetTextmethodonthetextviewhastobeexecutedontheUIthread.Ifthe@UiThreadTestannotationisnotadded,youhavetousetherunOnUiThread()methodinstead.
GettingtheresultsWealreadyhaveanapplicationandtwotestcasescreatedinourAndroidproject.Thestructureoftheprojectcanbeseeninthefollowingscreenshot.Runtheapplicationoncetocheckthattherearenoerrorsandinstalltheapplicationonthedevice.Inthissection,wewillberunningthetestcasesandexaminingtheresults.
InAndroidStudio,selectthepackagecontainingthetestcases.Clickonitusingtherightmousebutton,andselecttheRun‘Testsin<your_package>’option.InthebottompartofAndroidStudio,opentheRuntabtoseethetestexecution.Ontheleftpartofthistab,youcaninspectthetestexecutionstate.Fromthebuttonsontheleftside,youcanstopthetestexecutionorrerunit.Thenextscreenshotshowstheinitialstateofthetestsbeinginitialized.Ontherightpartofthetab,thecommandsandresultsarelistedintheconsole.
Whileatestmethodisbeingexecuted,itisalsorevealedontheleftpanelalongwithitsexecutionstatesuchaswhetherthetestisstillbeingevaluated,andwhetherthetestwaspassedornotpassed.Whenthetestexecutioniscompleted,alltheresultsaredisplayed.BydeselectingtheHidePassedicon(highlightedinthepreviousscreenshot),youcanseeallthetestmethods.Overtheconsole,acolorbarisalsoshowningreenorredtoindicatewhetherallthetestswerepassedorwhethertherewereanyfails.Inourexample,allthetestswerepassedasyoucanseeinthefollowingscreenshot:
Trytoinsertanerrorinanytestmethod,forexample,bychangingthefollowinglineofcodefromthetestStateManagement()testmethod:
assertEquals("30",mMinute.getText());
Changetheprecedinglineofcodetothefollowing:
assertEquals("40",mMinute.getText());
Runthetestsandnoticethatnowthefailisindicatedintheresults.Thefollowingscreenshotshowshowthefailisdisplayed:
SummaryInthischapter,youlearnedmoreaboutAndroidtesting.YounowunderstandthestructureoftheAndroidtestingAPIandweknowitsmainclassesandmethods.YoualsolearnedabouttheimportanceofinstrumentationtotestactivitiesoftheAndroidapplications.WesetupthetestingenvironmentusingAndroidStudioandfollowedthecompleteprocessoftesting.
Inthenextchapter,youwilllearnaboutsomeexternaltoolsdifferentfromAndroidStudio.ThesetoolswillhelpussecureandtestourAndroidapplications.
Chapter10.SupportingToolsInthischapter,youwilllearnabouttheexternaltoolsdifferentfromthoseavailableinAndroidStudiothatwillhelpustestourAndroidapplications.Thechapterwillcovertesttoolstoperformunitandfunctionaltests.Itwillalsocovertoolsthathelpussecureourapplicationindifferentways.WewillendthischapterwithanalternativetoolthatallowsyoutoemulateanAndroiddevice.
Thetopicsthataregoingtobecoveredinthischapterare:
ToolsforunittestingAndroidapplicationsToolsforfunctionaltestingAndroidapplicationsToolsforsecuringAndroidapplicationsSomeothertools
ToolsforunittestingAswehaveseeninChapter9,UnitandFunctionalTests,unittestingisperformedwithminimalconnectiontothesysteminfrastructureandteststhedifferentcomponentsinisolation.WewillseedifferenttoolsthatallowustoeasilyperformunittestsonAndroidapplications.Theyareasfollows:
SpoonMockitoAndroidMockFESTAndroidRobolectric
SpoonSpoonisnotanewformofunittesting.Instead,itmakesuseoftheexistingunittestinginstrumentationsuchasJUnittoruntestsonmultipledevices.WithSpoon,youcantestyourapplicationonmanydevicesatthesametime.Whenthetestiscompleted,youwillreceiveasummarygeneratedbySpoonwithalltheinformationregardingthetestperformedonthedevices.YoucanalsouseSpoonforfunctionaltesting.
ForadevicetobeconsideredbySpoontoruntestson,ithastobevisibletotheAndroidDebugBridge(adb)devices.Youcanevenperformthetestsondifferenttypesofdevicesatthesametime,suchassmartphones,tablets,phablets,andsoon,andindifferentversionsofAndroid.Thegreaterthediversityofthedevices,themoreusefulthesummarywillbe.Withabigsampleofdevices,youcanfindmorepotentialissuestobeaddressed.Wecanseeanexamplewitheightdevicesinthefollowingfigure:
Ifyouwanttoaccessthesummaryofthetestingperformedonasingledevice,youcandoitwiththeDeviceView.SpoonmakesaDeviceViewavailableforeachdeviceinthesamplesothatyoucanseetheresultsofadeviceindividually.ToaccesstheDeviceView,youcansimplyclickonthenameofadevice.Wecanseethisviewinthefollowingfigure:
Ifyouwanttoaccessthesummaryofaspecifictestperformedonallthedevicesinthesample,youcandoitthroughtheTestView.TheTestViewdisplaystheresultofasingletestoneverydevice.Incaseofanerror,itwillshowtheinformationthatwasgeneratedbytheerror.ToaccesstheTestView,youcanclickontheiconwiththeshapeofasmartphoneontheDeviceView.Wecanseeanexampleofthisviewinthefollowingscreenshot:
Ifyouwanttochecktheviewoftheapplicationatanypointintime,youcanusetheScreenshotfeature.Thisfeatureallowsyoutotakeascreenshotoftheinformationbeingdisplayedtotheuseratanygivenmomentduringtheexecution.ThescreenshotsareavailableinboththeDeviceViewifyouwanttoseeallthescreenshotstakeninasingledevice,andtheTestViewifyouwanttoseethescreenshotstakenofeachtestineverydevice.
Tomakeuseofthisfeature,youneedtoincludethespoon-client.jarlibraryinyourapplication.Whenyouwanttotakeascreenshot,youcancallthestaticscreenshot(Activity,String)methodoftheSpoonclass,shownasfollows:
Spoon.screenshot(activity,"login_activity");
NoteIfyouwanttoknowmoreaboutSpoonorwanttodownloadthetool,youcanfollowthislink:
http://square.github.io/spoon/
MockitoMockitoisamocktestingframeworkforJavathatcanbeusedinconjunctionwithJUnitandotherunittestingframeworks.IthasbeencompatiblewithAndroidsinceVersion1.9.5.Mockitoallowstheuseofautomaticunittestingtoenhancethequalityofourcode.Mostunittestingframeworksarebasedonanexpect-run-verifypattern.Mockitoremovesthespecificationofexpectationsreducingthepatterntorun-verify.
Wealreadyknowthatunittestsareperformedoveranisolatedclass.Thismeansthattheirinteractionwithotherclassesshouldbeeliminatedwhenpossible.AsseeninChapter9,UnitandFunctionalTests,youcanachievetheseinteractionsusingmockobjectsalsoknownasstubs.Mockitoallowsyoutocreatemockobjectsusingthemock()method.
Youcanalsoinitializeamockobjectusingthe@MockannotationandtheMockitoAnnotationsclass.YoucancalltheMockitoAnnotations.initMocks()methodtoinitiatethemockobjectsthatweredefinedwiththe@Mockannotation.
Theverify()methodcanbecalledonamockobjecttoverifythatacertainmethodwascalled.Tospecifyaconditionandareturnvaluewhentheconditionismet,youcanusethewhen()methodinconjunctionwiththethenReturn()method.
Forexample,let’ssaywewanttocheckwhetherthetestmethodwascalledinthefollowingcode:
//Createthemockobject
TestClasstestClassMock=Mockito.mock(TestClass.class);
//Callamethodonthemockobject
booleanresult=testClassMock.test("helloworld");
//Testthereturnvalue
assertTrue(result);
//Checkthatthemethodtest()wascalled
Mockito.verify(testClassMock).test("helloworld");
Mockitocannotbeusedtotestfinalclasses,anonymousclasses,andprimitivetypes.
NoteIfyouwanttolearnmoreaboutMockito,visititswebsite:https://code.google.com/p/mockito/
AndroidMockAndroidMockissimilartoMockito.AndroidMockisalsoaframeworktomockclassesandinterfaces.ItworkswiththeAndroidDalvikVirtualMachine.ItisbasedontheJavamockingframeworkEasyMockandusesthesamegrammarandsyntax.
InordertolearnaboutthegrammarandsyntaxofAndroidMock,wewillrepeatthesameexampleaswedidwithMockito:
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,themaindifferenceinAndroidMockandMockitoisthatAndroidMockfollowsthepatternexpectation-run-verify.
NoteIfyouwanttolearnmoreaboutAndroidMock,youcanvisittheprojectwebsite:https://code.google.com/p/android-mock/.
FESTAndroidFESTAndroidisalibrarythatextendstheFESTfunctionalitytoAndroid.FESTisaunittestframeworkforJava.Itisbasicallyasimplerformofmakingassertions.Inthefollowingcode,weseethedifferencesbetweenJUnit,FEST,andFESTforAndroid:
//AssertionusingJUNIT
assertEquals(View.GONE,view.getVisibility());
//AssertionusingFEST
assertThat(view.getVisibility()).isEqualTo(View.GONE);
//AssertionusingFESTforAndroid
assertThat(view).isGone();
FESTforAndroidoffersassertionsthatareexecuteddirectlyonobjectsinsteadofproperties.Thismakesitpossibletochaintogetherseveralassertions,shownasfollows:
assertThat(layout).isVisible().isVertical().hasChildCount(3);
TherearemanyavailableassertionsfortypicalAndroidobjects,suchasLinearLayout,ActionBar,Fragment,andMenuItem.
NoteIfyouwanttolearnmoreaboutFEST,youcanvisittheprojectwebsiteathttps://code.google.com/p/fest/.IfyouwanttolearnmoreaboutFESTforAndroid,youcanvisittheURLathttp://square.github.io/fest-android/.
RobolectricRobolectricallowsyoutorununittestsofyourAndroidapplicationonyourworkstation’sJavaVirtualMachine.Thishasonemainadvantage,thatis,speed.RunningunittestsinAndroidmeansthattheapplicationneedstobeloadedeitherontheAndroidemulatororonyourdevice.
RobolectrictakesadifferentpaththanmockframeworkssuchasMockitoandinsteadofmockingouttheAndroidSDK,RobolectricrewritestheAndroidSDKclassesandmakesitpossibletorunthemonaregularJVM.Itcan,however,beusedinconjunctionwithmockingtestingframeworkssuchasMockitoorAndroidMock.
Robolectricmakesuseofthe@RunWithannotationfromJUnit4,shownasfollows:
@RunWith(RobolectricTestRunner.class)
publicclassTest1{
//Yourtests
}
NoteIfyouwanttolearnmoreaboutRobolectric,youcanvisittheprojectwebsiteathttp://robolectric.org/.
ToolsforfunctionaltestingInChapter9,UnitandFunctionalTests,youlearnedhowfunctionaltestsareperformedwithfullconnectiontothesysteminfrastructure.Inthissection,wewilllookatthedifferenttoolsthatallowustoeasilyperformfunctionaltestsinAndroidapplications:
RobotiumEspressoAppiumCalabashMonkeyTalkBot-botMonkeyWireshark
RobotiumRobotiumrunsontheofficialAndroidtestingframework.ItaddsthenecessaryfeaturestorunthroughanentireAndroidapplication.Ithasfullsupportforbothnativeandhybridapplications.
Now,wewillseethestepsneededtorunatestusingRobotiumonourAndroidapplication:
1. AddtheRobotiumJARtoyourBuildPath.2. CreateatestcaseusingtheJUnitTestCaseclass.3. Writethetestcasecode.4. Runthetestcase.
TestswithRobotiumareperformedusingthecom.robotium.solo.SoloclassavailableintheRobotiumlibrary.
Wewillnowseeanexampleofthewhite-boxtestingusingRobotium.Inthisexample,wehavetwoEditTextfields:onewheretheusercaninputanumericvalueValueEditTextandanotheronethatwilldisplaythevalueoftheinputmultipliedby2,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());
}
}
NoteIfyouwanttolearnmoreaboutRobotium,youcanvisittheprojectwebsiteathttps://code.google.com/p/robotium/.IfyouwanttolearnhowtouseRobotium,werecommendtheofficialgettingstartedguide:https://code.google.com/p/robotium/wiki/Getting_Started.
EspressoEspressoisanAPIthatletsyouteststateexpectations,assertions,andinteractions.TherearemanyactionsthatcanbeperformedwithEspressousingasimplesyntax.Let’sseehowtheexampleweusedforRobotiumwillbeexecutedwithEspresso:
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.
NoteIfyouwanttolearnmoreaboutEspresso,youcanvisittheprojectwebsiteathttps://code.google.com/p/android-test-kit/wiki/Espresso.Ifyouhave15minutestospare,werecommendtheirGoogleTestAutomationConference2013presentationathttps://www.youtube.com/watch?v=T7ugmCuNxDU.
AppiumAppiumisanopensourceframeworkthatallowsautomatedtesting.AppiumworkswithbothnativeandhybridAndroidapplications.ItevenworkswithiOS.AppiumisagoodsolutionifyouneedtotestinbothAndroidandiOS.
NoteTodownloadorjustlearnmoreaboutAppium,youcanvisittheirwebsiteathttp://appium.io/.IfyouwanttoseeexamplesforAppium,visittheirGitHubathttps://github.com/appium/appium/tree/master/sample-code/examples.
CalabashJustlikeAppium,Calabashisalsoamultiplatformframeworkthatperformsautomatedtests.ItworkswithAndroidnativeapplications,hybridapplications,andiOSnativeapplications.Calabashallowsyoutotakescreenshotsofthecurrentviewinadeterminedinstant.OneofthethingsthatseparateCalabashfromtheothertestingframeworksisthatitsupportsCucumber.Cucumberallowspeoplewithlessexpertiseinthismattertoeasilydefinethebehavioroftheapplicationusingnaturallanguage,forexample:
WhenItouchthe"addition"button
ThenIshouldsee"20"
TheCalabashtoolisbasedonActivityInstrumentationTestCase2fromtheAndroidSDK.
NoteIfyouwanttoknowmoreaboutCalabash,youcanvisittheprojectwebsite:http://calaba.sh/.TolearnmoreabouttheCucumberproject,visittheirwebsite:http://cukes.info/.
MonkeyTalkMonkeyTalkisyetanothermultiplatformautomatedtestframework.MonkeyTalksupportsmorefeaturesthanAppiumandCalabash.However,theversionwitheveryfeatureavailableisasubscription-licensedproductthatiscurrentlyofferedinafreebetaversionbutwillbechargedwhenthebetaisover.
NoteIfyouwanttodownloadMonkeyTalkorjustlearnmoreaboutit,youcanvisittheprojectwebsiteathttp://www.cloudmonkeymobile.com/monkeytalk.ToseeanexampleusingtheMonkeyTalkframeworkwithanAndroidapplication,watchthefollowingYouTubevideo:https://www.youtube.com/watch?v=pjDGctTnThQ.
Bot-botBot-botisanAndroidautomationtestingtoolwithtwointerestingfeatures:recordandreplay.Youdonotneedtoaddanykindoflibraryordependencytoyourproject,sincetheonlythingbot-botneedsisanAPKoftheapplicationyouwanttotest.Therecordfeatureallowsyoutostorethesequenceofeventsthatweretriggered.Itworksbothonasimulatorandarealdevice.TherecordedtestcasescanbeexportedintheCSVformatandreplayedusingthebot-bottool.
Bot-botconsistsofthreeelements:
Thebot-botserver:ThisserverisusedtostoreandmodifytheactionstakenontheAndroidapplication.ItincludesasimpleHTMLinterfacethatallowsyoutoviewrecordedsessions,viewrecordedentriesofasession,modifyorcreateassertions,exportrecordedsessionsinCSV,anddeleterecordedsessions.Thebot-botrecorder:ThisrecordertrackstheuseractionsontheAndroidapplicationthatarebeingtested,andsendsthesetaskstothebot-botserver.ItsupportsrecordingofactionsonTextBoxes,Adapters,andSpinners.Italsorecordsclicksonelementsandviews.ItdoesnotsupportactionsonWebViews.Thebot-botrunner:ThisrunnertakestheexportedsessionsintheCSVformatandinterpretsthem.Thebot-botrunnerthenexecutestheactionsontheAndroidapplicationandgeneratesanHTMLreportthatshowstheexecutionofthetestcasesdefined.
ThefollowingscreenshotshowsanexampleofageneratedHTMLreportbythebot-botrunner:
Bot-botisperfectlyintegratedwithRobotium.
NoteIfyouwanttodownloadthebot-botapplication,youcanvisittheirwebsite:http://imaginea.github.io/bot-bot/.Tolearnhowtousethebot-bottool,werecommendtheofficialGetStartedguide:http://imaginea.github.io/bot-bot/pages/get_started.html.
MonkeyMonkeyisacommand-linetoolthatrunsonyourAndroidemulatorordevice.Itgeneratesrandomusereventsandsystem-leveleventstostresstestyourapplication.Althoughtheinteractionsarerandom,theyarebasedonaseedingsystemandthereforeyoucanrepeatthesamesequenceofactionsusingthesameseed.Thisisimportantsinceotherwise,youwouldnotbeabletorepeatthesequencethatproducedanerrortocheckwhetheritwasfixed.
TherearefourmaincategoriesofoptionsinMonkey:
Basicconfigurationoptions:AnexampleofthiscanbethehelporverbositylevelOperationalconstraints:AnexampleofthiscanbethepackagesinwhichthestresstestwillbeperformedEventtypes:Anexampleofthiscanbethenumberofevents,randomseed,anddelaybetweeneventsDebuggingoptions:Anexampleofthiscanbekillingtheprocessafteranerrororignoringthesecurityexceptions
TolaunchtheMonkey,youneedtouseacommandlineonyourdevelopmentmachineshownasfollows:
adbshellmonkey–pcom.packt.package–v100
The–pargumentstatesthepackagewheretheMonkeywillsendrandomevents.The–vparameterstatesthenumberofrandomeventsthatwillbesent.
NoteTherearemanyotherparametersforMonkey.Ifyouwanttolearnabouttheseparameters,youcanvisittheofficialAndroidguide:http://developer.android.com/tools/help/monkey.html.
WiresharkWireshark,formerlyknownasEthereal,isaprotocolanalyzerusedtoperformanalysisandsolveproblemsrelatedtonetworkconnectivity.Itsfunctionalityissimilartothetooltcpdump,butWiresharkprovidesamoreintuitiveGUI.
YoucanuseWiresharkincombinationwithyourAndroidemulatortocheckwhatinformationisbeingtransferredtoandfromyourAndroidapplication.Themainissuewiththistoolisthatyouneedtoknowwhatpackagestoexpect,sinceotherwisethetaskoffilteringcanbecomereallydifficult.Thebestadvicewecangiveistoclosethebrowserandotherprogramsinyourcomputerthatmaygeneratenetworktraffictokeepittoaminimum.
Inthisbook,wealreadydiscussedWiresharkinChapter6,SecuringCommunications.OneofthetopicswediscussedwasthatwecanuseWiresharktotestwhetherthedatawearesendingisbeingencryptedproperlyornot.OtheralternativestoWiresharkareFiddlerforWindowsandCharlesproxyforOSX.AscreenshotofWiresharkisshowninthefollowingfigure:
NoteIfyouwanttodownloadorlearnmoreaboutWireshark,visittheirwebsite:http://www.wireshark.org/.
OthertoolsInthislastsection,wewillseeatoolthatisnotdirectlyrelatedtoapplicationtestingorsecuritytesting.However,itcansignificantlyimproveourtestingexperience.
GenymotionGenymotionisanalternativeandunofficialAndroidemulator.ItisbasicallyavirtualemulatorthatcreatesavirtualimageofAndroidandisoftenconsideredmuchfasterthantheofficialAndroidemulator.ItisavailableforWindows,Linux,andMacOS.IfyouareusingWindowsorLinux,youonlyneedtoinstalltheGenymotiondistributionpackage.However,ifyouareusingMacOS,youneedtodownloadandinstallVirtualBoxmanually.Thefollowingisascreenshotcapturedfromthevirtualdevicemanagerthatlistsallthevirtualdevicesavailable:
NoteIfyouwanttogetstartedwithusingGenymotion,youcanvisitourblog:http://belencruz.com/2014/01/first-look-at-genymotion-android-emulator/.TodownloadandlearnmoreaboutGenymotion,visittheprojectwebsite:http://www.genymotion.com/.IfyouareusingMacOSandneedtodownloadVirtualBox,followthislink:https://www.virtualbox.org/.
SummaryInthischapter,youlearnedabouttheexternaltoolsthathelpusperformtestsonourAndroidapplications.Thechaptercoveredseveralautomatedunittestingtoolsandseveralautomatedfunctionaltestingtools.YoualsolearnedhowtostresstestourapplicationsusingMonkeyandwhattoolswewillneedifwewanttocheckthenetworkconnectivityofourapplication.AnalternativeAndroidemulatorthatisinmostcasesfasterthantheofficialonewasreviewedtoo.
Inthenextchapter,whichisthelastchapter,youwilllearnaboutsometipsthatareveryusefulfordevelopers.Youwillalsolearnhowtogethelpincaseyouneedit.
Chapter11.FurtherConsiderationsThischapterprovidessomefurtherconsiderationsthatareusefulfordevelopers.Wewillreviewwhatarethemostimportantpartsofourapplicationthatweneedtotest.Thischapteralsocontainsinformationabouthowtogethelpformoreadvancedtopics.
Thetopicsthatwillbecoveredinthischapterare:
WhattotestDeveloperoptionsGettinghelp
WhattotestInthepreviouschapters,youlearnedabouttheAndroidtestingAPIworkingwithAndroidStudio.ApartfromknowingaboutactivityandUItesting,consideringwhatpartsofyourapplicationshouldbeevaluatedisalsoimportant.
NetworkaccessIfyourapplicationdependsonthenetworkaccess,youshouldexaminethebehaviorofyourapplicationwhendifferentnetworkstatesaregiven.Considerthefollowingsuggestions:
Ifyourapplicationcompletelydependsonthenetworkwhenitislaunchedandthereisnonetworkaccess,itshouldatleastshowadefaulthomescreen.Yourapplicationshouldnotshowablankscreenwithanyinformationonit.Lettheuserknowthathe/sheshouldreviewthedeviceconnectivity.ThenetworkstatecanbecheckedusingtheConnectivityManagerclassinthefollowingcode:
ConnectivityManagerconnManager=(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfonetInfo=connManager.getActiveNetworkInfo();
if(netInfo!=null&&netInfo.isConnected()){
//Connect
}else{
//displaydefaultscreen
}
Whenthereareproblemsaccessingthenetworkthataffectthenormalbehaviorofyourapplication,lettheuserknowthisbydisplayingamessage.Whenperforminglongnetworkoperations,theusershouldalsobeabletouseyourapplication.Checkthatyourapplicationcontinuesworkingproperlyevenwhileperforminglongnetworkoperations.Yourapplication’sdatashouldmaintainitsconsistency.Ifyourapplicationsendsorreceivesanykindofinformationtoorfromyourserver,thisinformationshouldbecorrectlysynchronized.Checkthatyourapplicationandservercanrecoverfromanetworkfailureandmaintaintheconsistencyofyourapplication’sdata.Tomitigatenetworkfailures,yourapplicationcancachesomeoftheinformation.Checkthemanagementofthecachedinformationanditsusagewhenthereisnonetworkaccess.Agoodpolicyistochangethebehaviorofyourapplicationdependingonthetypeofnetworkaccess,forexample,itshouldbeabletodetectwhetherthedeviceisconnectedtoaWi-Fior3Gnetworkandworkaccordingly.Youshouldtestwhetheryourapplicationfollowsthedefinedpolicyandwhetheritisabletoreacttochangesintheconnectiontype.Theconnectiontypecanbecheckedusingthefollowingcode:
booleanwifiConnected=netInfo.getType()==
ConnectivityManager.TYPE_WIFI;
booleanmobileConnected=netInfo.getType()==
ConnectivityManager.TYPE_MOBILE;
Ifthereisanetworkfailure,yourapplicationshouldretryafterawhile.Youshouldcheckwhichbehaviorisappropriateforyourapplicationandwhetheritiscapableofrecoveringfromfailures.
MediaavailabilityIfyourapplicationdependsonexternalmedia,yourcodeshouldchecktheavailabilityofthatmedia.Whiledesigningyourtests,youshouldevaluatewhetheryourapplicationbehavescorrectlyifthemediaisnotavailable.
Forexample,ifyourapplicationworkswithanexternalstorage,youcancheckitsstatebyusingtheEnvironment.getExternalStorageStatemethod,asitwasshowninChapter5,PreservingDataPrivacy.Totesttheexternalstorageavailability,youcanconfiguretheAVDtorunontheemulatorfromAndroidStudio,asitisshowninthefollowingscreenshot:
ChangeinorientationIfadevicesupportsmultipleorientations,yourapplicationshouldbepreparedforthesame.Youhavetodecidewhetheryourapplicationwillblocktheorientationchangesornot.Ifyourapplicationsupportsorientationchanges,considerthefollowingsuggestions:
Whenthereisanorientationchange,thecurrentactivityisdestroyedandrestarted.Checkthattheactivitystateismaintained.Forexample,ifyouractivitycontainsaninputfieldthattheusercanedit,itscontenthastobepreservedwhenthedeviceorientationchanges.YourUIshouldalsoadapttothedevice’scurrentorientation.ThepositionanddistributionofyourUIelementsaredifferentonaportraitorientationthanonalandscapeone.YoushouldcheckthatthedesignofyourUIisperfectlydisplayedinboththeorientations.
YoucanchangetheemulatororientationbypressingCtrl+F11inWindowsorLinux,orFn+Ctrl+F11inMacOS.Tochecktheorientationchanges,youcanoverridetheonConfigurationChangedmethodofyouractivities,shownasfollows:
@Override
publicvoidonConfigurationChanged(ConfigurationnewConfig){
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
…
}elseif(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
…
}
}
ServiceandcontentprovidertestingInAndroid,wecantesttheUI,activities,services,andcontentproviders.InChapter9,UnitandFunctionalTests,activitytestingwasexplained.Butyoushouldnotforgetaboutservicestestingandcontentproviderstesting.TheclassesintheAndroidtestingAPIusedtoevaluateservicesandcontentprovidersarelistedinthefollowingfigure:
TheAndroidTestCaseclassanditssubclassesbelongtotheandroid.testpackage.ItrepresentsatestcasetobeusedintheAndroidenvironment.Sincethisclassisgeneric,youshoulduseoneofitssubclasses.TheProviderTestCase2classisusedtotestcontentproviders.TheServiceTestCaseclassisusedtotestservices.
DeveloperoptionsTheAndroidsystemprovidesasetofon-devicedeveloperoptionsthatwillhelpyoutestyourapplication.TheseoptionsareavailableintheSettingsmenuofanyAndroiddevice.OnAndroid4.2andhigher,thedeveloperoptionsarehidden.ClickontheAboutphoneoptionintheSettingsmenuandclickontheBuildnumberseventimestomakethemavailable.ThefollowingscreenshotshowstheDeveloperoptionsinAndroid’sSettingsmenu:
TheDeveloperoptionsareorganizedintosevencategories,describedasfollows:
General:Thisoptionisnotpresentinanycategory.Forexample,youcangetabugreportbyselectingtheTakebugreportoption.Debugging:Thiscategoryincludesusefultoolstodebugyourapplication.Forexample,whenyouwanttotestyourapplicationonarealdevice,youshouldchecktheUSBdebuggingoptioncontainedinthiscategory.Youcanalsoselectadebugapp(Selectdebugapp)orallowmocklocations(Allowmocklocations).Input:Thiscategorycontainstwotools.TheseareShowtouchestoprovideavisualfeedbackfortouchesonthescreen,andPointerlocationtooverlaythetouchdataonthescreen.Drawing:Thiscategoryincludesoptionstochangethegraphicalbehavioroftheapplicationandthesystemitself,suchasShowsurfaceupdates,Showlayoutbounds,ForceRTLlayoutdirection,andSimulatesecondarydisplays.Youmaywanttodisableanimationsthattakeplacewhenanapplicationisopened.Todoso,youcansettoAnimationoffthefollowingoptions:Windowanimationscale,Transitionanimationscale,andAnimatordurationscale.Hardwareacceleratedrendering:Inthissection,youcanchangethebehavioroftheGraphicsProcessingUnit(GPU).TheoptionsavailableareForceGPUrendering,ShowGPUviewupdates,Showhardwarelayersupdates,DebugGPUoverdraw,Debugnon-rectangularclipoperation,Force4xMSAA,andDisableHWoverlays.Monitoring:Thiscategorycontainsoptionsthatallowyoutotrackpossible
problemsormalfunctions.TheoptionsavailableareStrictmodeenabled,ShowCPUusage,ProfileGPUrendering,andEnableOpenGLtraces.Apps:Thiscategoryincludesoptionstomanagethebehaviorofapplicationswhentheyarerunninginthebackground.ActivatingDon’tkeepactivitieswilldestroyeveryactivitywhentheuserleavesit.Thebackgroundprocesslimitallowsyoutocontrolthenumberofprocessesthatcanbeexecutedinthebackground.IfyouactivatetheoptionShowallANRs,applicationswilldisplayadialogwhentheydon’trespond.
GettinghelpIfyouwanttoaccesstheAndroidStudiodocumentation,youcandoitthroughtheIntelliJIDEAwebhelp.YoucangotoHelp|OnlineDocumentation,oraccessthewebpagehttp://www.jetbrains.com/idea/documentation/.YoucanalsogotoHelp|HelpTopicstodirectlyopenthedocumentationcontentstree,orvisitthewebpagehttp://www.jetbrains.com/idea/webhelp/intellij-idea.html.
Android’sofficialdocumentationisprovidedbyGoogleandisavailableathttp://developer.android.com/.TheAndroiddocumentationincludeseverykindofguidetolearnhowtoprogramAndroidapplications.Italsoincludesdesignguidelinesandeventipsondistributingandpromotingyourapplication.
Someoftheimportantreferencesofallthepreviouschaptersarelistedasfollows:
Chapter1,IntroductiontoSoftwareSecurity:
Glossaryoftermsathttp://www.sans.org/security-resources/glossary-of-terms/
Chapter2,SecurityinAndroidApplications:
Contentprovidersathttp://developer.android.com/guide/topics/providers/content-providers.htmlIntentfiltersathttp://developer.android.com/guide/components/intents-filters.html
Chapter3,MonitoringYourApplication:
DDMSathttp://developer.android.com/tools/debugging/ddms.html
Chapter4,MitigatingVulnerabilities:
ThePatternclassathttp://developer.android.com/reference/java/util/regex/Pattern.htmlStoringdataathttp://developer.android.com/training/articles/security-tips.html#StoringData
Chapter5,PreservingDataPrivacy:
Cipherathttp://developer.android.com/reference/javax/crypto/Cipher.htmlStorageoptionsathttp://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Chapter6,SecuringCommunications:
Usingcryptographyathttp://developer.android.com/training/articles/security-tips.html#CryptoSecuritywithHTTPSandSSLathttp://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.htmluiautomatorathttp://developer.android.com/tools/help/uiautomator/index.html
Chapter9,UnitandFunctionalTests:
Creatingunittestsathttp://developer.android.com/training/activity-testing/activity-unit-testing.htmlCreatingfunctionaltestsathttp://developer.android.com/training/activity-testing/activity-functional-testing.htmlViewAssertsathttp://developer.android.com/reference/android/test/ViewAsserts.htmlMoreAssertsathttp://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/EspressoAppiumathttp://appium.io/Calabashathttp://calaba.sh/MonkeyTalkathttp://www.cloudmonkeymobile.com/monkeytalkBot-botathttp://imaginea.github.io/bot-bot/Monkeyathttp://developer.android.com/tools/help/monkey.htmlWiresharkathttp://www.wireshark.org/Genymotionathttp://www.genymotion.com/
SummaryInthischapter,youlearnedaboutwhichpartsofourapplicationaremoreimportanttoevaluateandtest.WereviewedthedeveloperoptionsavailableinAndroidandhowtoaccessthem.Wealsolearnedhowtogetadditionalhelpusingtheofficialdocumentationandothersources.
IndexA
acceptancetests/Testingthebasicsaccesscontrol,softwaresecurity/SoftwaresecuritytermsAccountManagerclass
about/AccountManagerusing/AccountManager
activityabout/Intents
Activity.runOnUiThread()methodabout/UItestingandTouchUtils
ActivityInstrumentationTestCase2classabout/Thetestcaseclasses
activitylifecyclemethods/Instrumentationactivitytest
creating/Creatinganactivitytestunittest,creating/Creatingaunittestfunctionaltest,creating/Creatingafunctionaltestexecuting/Gettingtheresults
ActivityTestCaseclassabout/Thetestcaseclasses
ActivityUnitTestCaseclassabout/Thetestcaseclasses
addMonitormethod/InstrumentationAllocationTrackertab
displaying/AllocationTrackerAllpairstestingtechnique/TestingthebasicsAndroid
about/ThemobileenvironmentAndroidapplication
testing/TestinginAndroidAndroidapplicationpackage(APK)/PermissionsAndroidApplicationSandbox/AnoverviewofAndroidsecurityAndroidDebugBridge(adb)/SpoonAndroidinstrumentation
about/InstrumentationAndroidMock
about/AndroidMockURL/AndroidMock
AndroidSDKused,fortestingAndroidapplication/TestinginAndroid
Androidsecurity
overview/AnoverviewofAndroidsecurityfeatures/AnoverviewofAndroidsecurity
AndroidStudioabout/AndroidStudioURL,fordocumentation/Gettinghelphelp,obtaining/Gettinghelp
AndroidVirtualDevice(AVD)about/Theuiautomatorviewertool
APIabout/Permissions
appabout/Themobileenvironment
Appiumabout/AppiumURL,fordownloading/Appium,Calabash
applicationlayerabout/HTTPS
applicationsandboxing/AnoverviewofAndroidsecurityAssertclass
about/TheAssertclassandmethodViewAssertsclass/TheViewAssertsclassMoreAssertsclass/TheMoreAssertsclass
assertEqualsmethod/TheAssertclassandmethodassertFalsemethod/TheAssertclassandmethodassertmethod
about/TheAssertclassandmethodassertEqualsmethod/TheAssertclassandmethodassertTruemethod/TheAssertclassandmethodassertFalsemethod/TheAssertclassandmethodassertNullmethod/TheAssertclassandmethodassertNotNullmethod/TheAssertclassandmethodassertSamemethod/TheAssertclassandmethodassertNotSamemethod/TheAssertclassandmethodfailmethod/TheAssertclassandmethod
assertNotNullmethod/TheAssertclassandmethodassertNotSamemethod/TheAssertclassandmethodassertNullmethod/TheAssertclassandmethodassertSamemethod/TheAssertclassandmethodassertTruemethod/TheAssertclassandmethodasymmetriccryptography,softwaresecurity/Softwaresecuritytermsasymmetricencryption
about/Encryptionauthentication,softwaresecurity/Softwaresecuritytermsauthenticationfactors
knowledgefactor/Theknowledgefactorpossessionfactor/Thepossessionfactorinherencefactor/Theinherencefactor
availability,softwaresecurity/Softwaresecurityterms
Bbasispathtesting/Testingthebasicsbiometricauthentication
about/Theinherencefactorbiometricidentifiers
physiologicalcharacteristics/Theinherencefactorbehavioralcharacteristics/Theinherencefactor
black-boxtestingabout/TestingtheUI
black-boxtestsabout/Testingthebasics
black-boxtests,techniquesequivalencepartitioning/Testingthebasicsboundaryvalueanalysis/Testingthebasicsstatetransitiontesting/Testingthebasicsallpairstesting/Testingthebasicssyntaxtesting/Testingthebasics
bot-botabout/Bot-botserver/Bot-botrecorder/Bot-botrunner/Bot-botURL,fordownloading/Bot-bot
bot-botrecorderabout/Bot-bot
bot-botrunnerabout/Bot-bot
bot-botserverabout/Bot-bot
boundaryvalueanalysistechnique/Testingthebasicsbroadcastmessages,types
normal/Intentsordered/Intentssticky/Intents
broadcastreceiversabout/Intents
bruteforce,softwaresecurity/Softwaresecurityterms
CCalabash
about/Calabashcategories,developeroptions
General/DeveloperoptionsDebugging/DeveloperoptionsInput/DeveloperoptionsDrawing/DeveloperoptionsHardwareacceleratedrendering/DeveloperoptionsMonitoring/DeveloperoptionsApps/Developeroptions
Cause-effectgraphingtechnique/Testingthebasicscertificate
about/Serverandclientcertificatescreating/Serverandclientcertificatesusing/Serverandclientcertificates
certificate.crtfile/KeytoolintheterminalCertificateAuthority(CA)/CodeexamplesusingHTTPScertificates
about/AnoverviewofAndroidsecurityCipher,softwaresecurity/Softwaresecuritytermscodeinjection,softwaresecurity/Softwaresecuritytermsconfidentiality,softwaresecurity/SoftwaresecuritytermsConsole
about/DebuggingandDDMScontentprovider
testing/Serviceandcontentprovidertestingcontentproviders
about/ContentprovidersURL,forofficialdocumentation/Contentproviderssecuring/Securingthecontentproviderssecuring,precautions/Securingthecontentproviders
controlflowtesting/Testingthebasicscrack,softwaresecurity/Softwaresecuritytermscryptographickeys
about/Thepossessionfactor
D.dbfile
about/Thedatabasestoragedangerouspermissionlevel
about/Permissionsdata
storing,encryptionused/Usingencryptiontostoredatadatabasestorage
about/ThedatabasestorageDataEncryptionStandard(DES)
about/SSLandTLSdataflowtesting/Testingthebasicsdataprivacy
about/DataprivacyDDMS
about/DebuggingandDDMSdebugger
about/DebuggingandDDMSdebugging
about/DebuggingandDDMSdecryption,softwaresecurity/SoftwaresecuritytermsDenial-of-service(DoS)/Softwaresecuritytermsdeveloperoptions
about/Developeroptionscategories/Developeroptions
DeviceViewabout/Spoon
Dictionaryattack/SoftwaresecuritytermsDistributeddenial-of-service(DDoS)/SoftwaresecuritytermsdoFinalmethod
about/Encryption
Eelectroniccommerce(e-commerce)/SoftwaresecuritytermsEmulatorControltab
about/EmulatorControlTelephonyStatus/EmulatorControlTelephonyActions/EmulatorControlLocationControls/EmulatorControl
encryption/Softwaresecuritytermsabout/Encryptionsymmetricencryption/Encryptionasymmetricencryption/Encryptionkey,generating/Generatingakeyused,forstoringdata/Usingencryptiontostoredata
encryptionmethodsusing/Theencryptionmethods
Equivalencepartitioningtechnique/TestingthebasicsEspresso
about/Espressoreferencelink/Espresso
exclusivetime/Methodprofilingexpect-run-verifypattern/Mockitoexternalstorage
about/Filesintheexternalstoragepublicfiles/Filesintheexternalstorageprivatefiles/Filesintheexternalstorage
Ffabrication,threat/Threatfailmethod/TheAssertclassandmethodfeatures,Androidsecurity
application-definedpermissions/AnoverviewofAndroidsecurityinterprocesscommunication/AnoverviewofAndroidsecuritysupportforsecurenetworking/AnoverviewofAndroidsecuritysupportforcryptography/AnoverviewofAndroidsecurityencryptedfilesystem/AnoverviewofAndroidsecurityapplicationsigning/AnoverviewofAndroidsecurity
FESTreferencelink/FESTAndroid
FESTAndroidabout/FESTAndroidURL/FESTAndroid
FileExplorertababout/FileExplorer
FTPabout/HTTPS
functionaltestcreating/Creatingafunctionaltestsettingup/ThefunctionaltestsetupUItestmethod,implementing/TheUItestactivityIntenttestmethod,implementing/TheactivityIntentteststatemanagementtestmethod,implementing/Thestatemanagementtest
functionaltestingabout/Testingactivitiestools,using/Toolsforfunctionaltesting
Ggarbagecollector(GC)
about/HeapGenymotion
about/GenymotionURL/Genymotion
getAccountsByNamemethodabout/AccountManager
getActivity()methodabout/Instrumentation,Theunittestsetup
getContentResolver().query()methodabout/Contentproviders
getContentResolver().query()method,parameterscontentURI/Contentprovidersprojection/Contentprovidersselection/Contentprovidersselectionarguments/Contentproviderssortorder/Contentproviders
getInstrumentation()methodabout/Instrumentation
getPreferences()methodabout/Sharedpreferences
getSharedPreferences()methodabout/Sharedpreferences
getTargetContextmethod/InstrumentationgetUiDevice()method
about/TheUiDeviceclassGraphicsProcessingUnit(GPU)/Developeroptions
Hhashfunction/SoftwaresecuritytermsHeaptab
displaying/Heaphelp,AndroidStudio
obtaining/GettinghelpHijackattack/SoftwaresecuritytermsHTTP
versus,HTTPS/HTTPSHTTPS
about/HTTPSversus,HTTP/HTTPSSSL/SSLandTLSTLS/SSLandTLScertificate,creating/ServerandclientcertificatesKeytool/KeytoolintheterminalAndroidStudio/AndroidStudioexamples/CodeexamplesusingHTTPS
HypertextTransferProtocolSecure(HTTPS)/Softwaresecurityterms
Iinclusivetime/Methodprofilinginherencefactor
about/Theknowledgefactor,Theinherencefactorinitmethod/Encryptioninputvalidation
about/InputvalidationSQLinjection/SQLinjection
instrumentationabout/Instrumentation
InstrumentationclassURL,fordocumentation/InstrumentationaddMonitormethod/Instrumentationactivitylifecyclemethods/InstrumentationgetTargetContextmethod/InstrumentationstartActivitySyncmethod/InstrumentationwaitForIdleSyncmethod/Instrumentation
InstrumentationTestCaseclassabout/Thetestcaseclasses
integrationtests/Testingthebasicsintegrity,softwaresecurity/Softwaresecuritytermsintents
about/IntentsURL,forofficialdocumentation/Intents
Intentssecuring/SecuringIntentsvulnerabilities/SecuringIntents
Intentspoofingabout/SecuringIntents
interapplicationcommunicationabout/Interapplicationcommunication,Interapplicationcommunicationintents/Intentscontentproviders/ContentprovidersIntents,securing/SecuringIntentscontentproviders,securing/Securingthecontentproviders
interception,threat/Threatinternalstorage
about/FilesintheinternalstorageInternationalMobileStationEquipmentIdentity(IMEI)
about/DataprivacyInternetAssignedNumbersAuthority(IANA)
about/Inputvalidationinternetlayer
about/HTTPSinterruption,threat/Threat
JJavaDevelopmentKit(JDK)
about/ServerandclientcertificatesJUnit
about/TestinginAndroidJVM
about/TestinginAndroidAndroidapplication,testingon/TestinginAndroid
Kkey
generating,forencryption/GeneratingakeyKeyGeneratorclass/GeneratingakeyKeytool
about/Serverandclientcertificates,Keytoolintheterminalkeytoolcommand
-genkeyparameter/Keytoolintheterminal-keyalgparameter/Keytoolintheterminal-aliasparameter/Keytoolintheterminal-keystoreparameter/Keytoolintheterminal-storepassparameter/Keytoolintheterminal-validityparameter/Keytoolintheterminal-keysizeparameter/Keytoolintheterminal
knowledgefactorusername/password/Theknowledgefactorpattern/TheknowledgefactorPIN/Theknowledgefactor
Llinklayer
about/HTTPSLogCat
about/DebuggingandDDMSloginimplementations
about/Loginimplementations
MMan-in-the-middleattack/SoftwaresecuritytermsMD5,softwaresecurity/SoftwaresecuritytermsMediaAccessControl(MAC)/HTTPSmediaavailability
testing/Mediaavailabilitymethodprofilingtool
about/Methodprofilingmobileenvironment
about/Themobileenvironmentmock()method/MockitoMockito
about/MockitoURL/Mockito
mockobjectclassesabout/ThemockobjectclassesMockApplicationclass/ThemockobjectclassesMockContextclass/ThemockobjectclassesMockContentProviderclass/ThemockobjectclassesMockCursorclass/ThemockobjectclassesMockDialogInterfaceclass/ThemockobjectclassesMockPackageManagerclass/ThemockobjectclassesMockResourcesclass/ThemockobjectclassesMockContentResolverclass/Themockobjectclasses
modeflag,internalstorageMODE_PRIVATE/FilesintheinternalstorageMODE_APPEND/FilesintheinternalstorageMODE_WORLD_READABLE/FilesintheinternalstorageMODE_WORLD_WRITEABLE/Filesintheinternalstorage
modification,threat/ThreatMonkey
about/Monkeybasicconfigurationoptions/Monkeyoperationalconstraints/Monkeyeventtypes/Monkeydebuggingoptions/MonkeyURL,forparameters/Monkey
MonkeyTalkabout/MonkeyTalkURL,fordownloading/MonkeyTalk
MoreAssertsclass/TheAssertclassandmethodabout/TheMoreAssertsclassassertContainsRegex()method/TheMoreAssertsclass
assertContentsInAnyOrder()method/TheMoreAssertsclassassertContentsInOrder()method/TheMoreAssertsclassassertEmpty()method/TheMoreAssertsclassassertEquals()method/TheMoreAssertsclassassertMatchesRegex()method/TheMoreAssertsclassURL/TheMoreAssertsclass
multifactorauthenticationabout/Multifactorauthentication
MyPrefsFilefile/SharedpreferencesMyReadablePrefsFilefile/SharedpreferencesMyWriteablePrefsFilefile/Sharedpreferencesmy_keystore.jksfile/Keytoolintheterminal
Nnetworkaccess
testing/NetworkaccessNetworkStatisticstab
displaying/NetworkStatisticsnormalbroadcast
about/Intentsnormalpermissionlevel
about/Permissions
OonCreatemethod/InstrumentationopenFileOutput()method
about/Filesintheinternalstorageopensourcesoftware(OSS)
about/HTTPSoperatingmode,sharedpreferences
MODE_PRIVATE/SharedpreferencesMODE_WORLD_READABLE/Sharedpreferences
operatingsystem(OS)about/Themobileenvironment
orderedbroadcastabout/Intents
orientationchangestesting/Changeinorientation
OSImodelabout/HTTPSversus,TCP/IPmodel/HTTPS
P-pparameter/Monkeypassword,softwaresecurity/Softwaresecuritytermspattern
about/TheknowledgefactorPatternclass
DOMAIN_NAMEpattern/InputvalidationEMAIL_ADDRESSpattern/InputvalidationIP_ADDRESSpattern/InputvalidationPHONEpattern/InputvalidationTOP_LEVEL_DOMAINpattern/InputvalidationWEB_URLpattern/Inputvalidation
PBKDF2algorithm/Usingencryptiontostoredatapermissionlevel
normal/Permissionsdangerous/Permissionssignature/PermissionssignatureOrSystem/Permissions
permissionsabout/Permissions,Permissions
phishing,softwaresecurity/Softwaresecuritytermsphysicallayer
about/HTTPSPIN
about/Theknowledgefactorpossessionfactor
about/Thepossessionfactorprivatefiles
about/Filesintheexternalstoragepublicfiles
about/Filesintheexternalstorage
Rregularexpressions
URL,fordocumentation/InputvalidationresourceIdmethod/TheUItestprojectrisk,softwaresecurity
about/Softwaresecurityterms,RiskRobolectric
about/RobolectricURL/Robolectric
Robotiumabout/Robotiumreferencelink/Robotium
SScreenshotfeature
about/SpoonSecretKeySpecclass/Generatingakeysecurecode-design,principles
securedefaults/Securecode-designprinciplesleastprivileges/Securecode-designprinciplesclarity/Securecode-designprinciplessmallsurfacearea/Securecode-designprinciplesstrongdefense/Securecode-designprinciplesfailingsecurely/Securecode-designprinciplesthird-partycompanies,nottrusting/Securecode-designprinciplessimplicity/Securecode-designprinciplesAddressvulnerabilities/Securecode-designprinciples
SecureRandomclass/Generatingakeysecuritytesting
about/Testingthebasicswhite-boxtests/Testingthebasicsblack-boxtests/Testingthebasics
sensitivedataabout/Dataprivacy
serviceabout/Intents
servicestesting/Serviceandcontentprovidertesting
setUp()methodabout/Thetestcasemethods
SHA1,softwaresecurity/Softwaresecuritytermssharedpreferences
about/SharedpreferencessignatureOrSystempermissionlevel
about/Permissionssignaturepermissionlevel
about/Permissionssmartphone
about/Themobileenvironmentvulnerabilities/Themobileenvironment
SMTPabout/HTTPS
sniffingattack,softwaresecurity/Softwaresecuritytermsspoofingattack/SoftwaresecuritytermsSpoon
about/Spoon
URL,fordownloading/Spoonspoon-client.jarlibrary
about/SpoonSQL
about/ContentprovidersSQLinjection
about/SQLinjectionSSL
about/HTTPS,SSLandTLSSSL3.0
about/SSLandTLSSSLconnection
establishing/SSLandTLSSSLHandshakeException
about/CodeexamplesusingHTTPSstartActivitySyncmethod/InstrumentationStatementcoverage/TestingthebasicsStatetransitiontestingtechnique/Testingthebasicsstickybroadcast
about/Intentsstorageoptions
sharedpreferences/Dataprivacy,Sharedpreferencesinternalstorage/Dataprivacy,Filesintheinternalstorageexternalstorage/Dataprivacy,Filesintheexternalstoragedatabasestorage/Dataprivacy,Thedatabasestorage
symmetriccryptography/Softwaresecuritytermssymmetricencryption
about/EncryptionSyntaxtestingtechnique/TestingthebasicsSystemInformationtab
about/SystemInformationsystemtests/Testingthebasics
TTCP/IPmodel
about/HTTPSphysicallayer/HTTPSlinklayer/HTTPSinternetlayer/HTTPStransportlayer/HTTPSapplicationlayer/HTTPSversus,OSImodel/HTTPS
tcpdump/WiresharktearDown()method
about/Thetestcasemethodsterms,softwaresecurity
accesscontrol/Softwaresecuritytermsasymmetriccryptography/Softwaresecuritytermsauthentication/Softwaresecuritytermsauthorization/Softwaresecuritytermsavailability/Softwaresecuritytermsbruteforce/SoftwaresecuritytermsCipher/Softwaresecuritytermscodeinjection/Softwaresecuritytermsconfidentiality/Softwaresecuritytermscrack/Softwaresecuritytermsdecryption/SoftwaresecuritytermsDenial-of-service(DoS)/SoftwaresecuritytermsDistributeddenial-of-service(DDoS)/SoftwaresecuritytermsDictionaryattack/Softwaresecuritytermsencryption/Softwaresecuritytermshashfunction/SoftwaresecuritytermsHijackattack/SoftwaresecuritytermsHypertextTransferProtocolSecure(HTTPS)/SoftwaresecuritytermsIntegrity/SoftwaresecuritytermsMD5/SoftwaresecuritytermsMan-in-the-middleattack/Softwaresecuritytermspasswords/Softwaresecuritytermsphishing/Softwaresecuritytermsrisk/SoftwaresecuritytermsSHA1/SoftwaresecuritytermsSniffingattack/Softwaresecuritytermsspoofingattack/Softwaresecuritytermssymmetriccryptography/Softwaresecuritytermsthreat/Softwaresecuritytermsvulnerability/Softwaresecurityterms
TestCaseclassabout/ThetestcaseclassessetUp()method/ThetestcasemethodstearDown()method/Thetestcasemethods
testcaseclassesabout/ThetestcaseclassesTestCaseclass/ThetestcaseclassesInstrumentationTestCaseclass/ThetestcaseclassesActivityTestCaseclass/ThetestcaseclassesActivityInstrumentationTestCase2class/ThetestcaseclassesActivityUnitTestCaseclass/Thetestcaseclasses
testcasemethodsabout/Thetestcasemethods
testing,AndroidapplicationonJVM/TestinginAndroidAndroidSDK,using/TestinginAndroid
testing,contentproviderabout/Serviceandcontentprovidertesting
testing,mediaavailabilityabout/Mediaavailability
testing,networkaccessabout/Networkaccess
testing,orientationchangesabout/Changeinorientation
testing,servicesabout/Serviceandcontentprovidertesting
testingactivitiesfunctionaltesting/Testingactivitiesunittesting/Testingactivitiestestcaseclasses/Thetestcaseclassesinstrumentation/Instrumentationtestcasemethods/ThetestcasemethodsAssertclass/TheAssertclassandmethodassertmethod/TheAssertclassandmethodUItesting/UItestingandTouchUtilsTouchUtils/UItestingandTouchUtilsmockobjectclasses/Themockobjectclasses
testinglevelsunittests/Testingthebasicsintegrationtests/Testingthebasicsvalidationtests/Testingthebasicssystemtests/Testingthebasicsacceptancetests/Testingthebasics
TestView
about/SpoonThreadstab
about/Threadsthreat
about/Softwaresecurityterms,Threatinterception/Threatinterruption/Threatmodification/Threatfabrication/Threat
three-factorauthenticationabout/Multifactorauthentication
Time-basedOne-TimePassword(TOTP)about/Thepossessionfactor
TLSabout/HTTPS,SSLandTLS
toolsGenymotion/Genymotion
tools,functionaltestingRobotium/Toolsforfunctionaltesting,RobotiumEspresso/Toolsforfunctionaltesting,EspressoAppium/Toolsforfunctionaltesting,AppiumCalabash/Toolsforfunctionaltesting,CalabashMonkeyTalk/Toolsforfunctionaltesting,MonkeyTalkBot-bot/ToolsforfunctionaltestingMonkey/Toolsforfunctionaltesting,MonkeyWireshark/Toolsforfunctionaltesting,Wiresharkbot-bot/Bot-bot
tools,unittestingSpoon/Toolsforunittesting,SpoonMockito/Toolsforunittesting,MockitoAndroidMock/Toolsforunittesting,AndroidMockFESTAndroid/Toolsforunittesting,FESTAndroidRobolectric/Toolsforunittesting,Robolectric
TouchUtilsabout/UItestingandTouchUtils
TouchUtilsclassclickViewmethod/UItestingandTouchUtilsdragmethod/UItestingandTouchUtilsdragQuarterScreenDownmethod/UItestingandTouchUtilsdragViewBymethod/UItestingandTouchUtilsdragViewTomethod/UItestingandTouchUtilsdragViewToTopmethod/UItestingandTouchUtilslongClickViewmethod/UItestingandTouchUtilsscrollToTopmethod/UItestingandTouchUtils
scrollToBottommethod/UItestingandTouchUtilsTrafficStatsclass
about/NetworkStatisticstransportlayer
about/HTTPSTrustManagerclass/CodeexamplesusingHTTPStwo-factorauthentication
about/Multifactorauthentication
U@UiThreadTest()method
about/UItestingandTouchUtilsuiautomator.jarlibrary
about/TheuiautomatorAPIuiautomatorAPI
about/TestingtheUI,TheuiautomatorAPIUiDeviceclass/TheUiDeviceclassUiSelectorclass/TheUiSelectorclassUiObjectclass/TheUiObjectclassUiCollectionclass/TheUiCollectionclassUiScrollableclass/TheUiScrollableclass
uiautomatorviewertoolabout/Theuiautomatorviewertool
UiCollectionclassabout/TheUiCollectionclassgetChildByDescription(UiSelectorchildPattern,Stringtext)method/TheUiCollectionclassgetChildByInstance(UiSelectorchildPattern,intinstance)method/TheUiCollectionclassgetChildByText(UiSelectorchildPattern,Stringtext)method/TheUiCollectionclassgetChildCount(UiSelectorchildPattern)method/TheUiCollectionclass
UiDeviceclassabout/TheUiDeviceclassclick(intx,inty)method/TheUiDeviceclassgetDisplaySizeDp()method/TheUiDeviceclasspressBack()method/TheUiDeviceclasspressHome()method/TheUiDeviceclasssleep()method/TheUiDeviceclasstakeScreenshot(Filestorepath)method/TheUiDeviceclasswakeUp()method/TheUiDeviceclass
UiObjectclassabout/TheUiObjectclassclick()method/TheUiObjectclassexists()method/TheUiObjectclassgetText()method/TheUiObjectclassisChecked()method/TheUiObjectclasssetText(Stringtext)method/TheUiObjectclass
UiScrollableclassabout/TheUiScrollableclassscrollBackward()method/TheUiScrollableclassscrollForward()method/TheUiScrollableclass
scrollToBeginning()method/TheUiScrollableclassscrollToEnd()method/TheUiScrollableclass
UiSelectorclassabout/TheUiSelectorclasschecked(booleanval)method/TheUiSelectorclasschildSelector(UiSelectorselector)method/TheUiSelectorclassclassName(StringclassName)method/TheUiSelectorclassresourceID(Stringid)method/TheUiSelectorclasstext(Stringtext)method/TheUiSelectorclass
UItestcasesexecuting/RunningUItestcases
UItestingabout/TestingtheUI,UItestingandTouchUtilswhite-boxtesting/TestingtheUIblack-boxtesting/TestingtheUIuiautomatorAPI/TheuiautomatorAPIuiautomatorviewertool/Theuiautomatorviewertool
UItestprojectcreating/TheUItestproject
UIthreadabout/Threads
unauthorizedIntentreceiptabout/SecuringIntents
unittestcreating/Creatingaunittestsettingup/Theunittestsetupclocktestmethod,implementing/Theclocktestlayouttestmethod,implementing/ThelayouttestactivityIntenttestmethod,implementing/TheactivityIntenttest
unittestingabout/Testingactivitiestools,using/Toolsforunittesting
unittests/TestingthebasicsunknownCA
solving/CodeexamplesusingHTTPSuser’sdataandcredentials
handling/Handlingauser’sdataandcredentialshandling,considerations/Handlingauser’sdataandcredentials
userID(UID)/AnoverviewofAndroidsecurityuserinterface(UI)
about/Threadsusername/password
about/Theknowledgefactor
V-vparameter/Monkeyvalidationtests/Testingthebasicsvalues,methodprofilingtool
exclusivetime/Methodprofilinginclusivetime/Methodprofiling
verify()method/MockitoViewAssertsclass/TheAssertclassandmethod
about/TheViewAssertsclassURL/TheViewAssertsclassassertBottomAligned()method/TheViewAssertsclassassertLeftAligned()method/TheViewAssertsclassassertRightAligned()method/TheViewAssertsclassassertTopAligned()method/TheViewAssertsclassassertGroupContains()method/TheViewAssertsclassassertGroupNotContains()method/TheViewAssertsclassassertHasScreenCoordinates()method/TheViewAssertsclassassertHorizontalCenterAligned()method/TheViewAssertsclassassertVerticalCenterAligned()method/TheViewAssertsclassassertOffScreenAbove()method/TheViewAssertsclassassertOffScreenBelow()method/TheViewAssertsclassassertOnScreen()method/TheViewAssertsclass
VirtualBoxURL,fordownloading/Genymotion
vulnerabilities,IntentsunauthorizedIntentreceipt/SecuringIntentsIntentspoofing/SecuringIntents
vulnerabilities,smartphone/Themobileenvironmentvulnerability
about/Softwaresecurityterms,Vulnerabilityimproperauthentication/Vulnerabilitybufferoverflow/Vulnerabilitycross-sitescripting(XSS)/VulnerabilityInputvalidation/VulnerabilitySQLinjection/Vulnerability
WwaitForIdleSyncmethod/Instrumentationwhen()method/Mockitowhite-boxtesting
about/TestingtheUIwhite-boxtests
about/Testingthebasicswhite-boxtests,techniques
controlflowtesting/Testingthebasicsdataflowtesting/Testingthebasicsbasispathtesting/Testingthebasicsstatementcoverage/Testingthebasics
WiresharkURL/HTTPSabout/WiresharkURL,fordownloading/Wireshark
XX.509certificate
version/Serverandclientcertificatesserialnumber/Serverandclientcertificatessignaturealgorithm/Serverandclientcertificatesissuer/Serverandclientcertificatesvalidity/Serverandclientcertificatessubject/Serverandclientcertificatessubjectpublickey/Serverandclientcertificates
Top Related