Taming File Storage on Android — Part 1 - COBE

文章推薦指數: 80 %
投票人數:10人

Before Android 10, apps have private, app-specific storage. In addition to private storage, the system provides shared storage where all of the ... CLOSE‍ProjectsServicesAgencyStoriesContactENDEStoriesDevelopment5minreadPublishedAugust27,2021TamingFileStorageonAndroid  — Part1LukaAndroidDevelopmentWelcometothefirstpartofatwo-partseriesonworkingwithfilestorageinAndroid!Avastmajorityofappsaredoingsomeformofdatamanagement.Whetherit’sjustloadingaprofileimage,sharingimagesorvideo/audiofilesthroughmessagingorsimplystoringdata.WorkingwithfilesonAndroidcanbedaunting.Especiallyifyou’renewtoAndroid,orjusthaven’tworkedwithitinawhile.WhenitcomestosavingdataonAndroid,wecanchoosefromafewoptions:SharedPreferences — mostcommonlyusedforstoringapppreferences,askey-valuepairsDatabases(Room) — forstoringstructureddatainaprivatedatabaseFilestorage — forstoringallkindsofmedia/documentstothefilesystemIfyouarewonderingwhichoftheseoptionsisforyou,therearefoursimplequestionsintheofficialdocumentationthatyoucangothroughtofigureoutwhattypeofstorageyouneed.Inthisarticlethough,IamgoingtofocusonstoringdatatoadiskusingsomeoftheAPIsprovidedbyAndroid.Topicswearegoingtocoverinclude:CategoriesofphysicalstoragelocationsPermissionsandaccesstostorageScopedstorageWorkingwithmediacontentWorkingwithdocumentsandfiles‍InternalstoragevsexternalstorageAndroidsystemprovidesuswithtwotypesofphysicalstoragelocations:internalandexternalstorage.Themostsignificantdifferencebetweenthemisthattheinternalstorageissmallerthanexternalstorageonmostdevices.Also,theexternalstoragemightnotalwaysbeavailable,incontrasttointernal,whichisalwaysavailableonalldevices.Thesystemcreatesaninternalstoragedirectoryandnamesitwiththeapp’spackagename.Keepinginmindthattheinternalstorageisalwaysavailable,thismakesitareliableplacetostoredatathatyourappdependson.Furthermore,ifyouneedtosavesensitivedataordatathatonlyyourappcanhaveaccessto,gofortheinternalstorage.Twothingsareimportanttonotewhenworkingwithinternalstorage:AusercannotaccessthesefilesthroughthefilemanagerFilesinthisfolderwillbedeletedwhenanappisuninstalledToaccessandstoredatatoapp’sfilesintheinternalstorage,youcanuseFileAPI.Iwroteasimplemethodjustforanexample:funwriteToFile(fileName:String,contentToWrite:String){  valfile=File(context.filesDir,fileName)  file.writeText(contentToWrite) }Alternatively,youcancallopenFileOutput()methodtoobtainaninstanceofFileOutputStreamthatcanwritetoafileinthefilesDirdirectory.funwriteToFile(fileName:String,contentToWrite:String){context.openFileOutput(fileName,Context.MODE_PRIVATE).use{it.write(contentToWrite.toByteArray())}}Youwouldreadfromafileinthisdirectoryinalmostthesameway.YoucancreateaFileandcallreadText()methodoryoucanobtainaninstanceofFileInputStreambycallingopenFileInput().Here’sanexample:funreadFromFile(fileName:String):String{  context.openFileInput(fileName).bufferedReader().useLines{   it.fold(""){some,text->    return"$some\n$text"   }  }  return"Thefileisempty!" }Okay,butwhenshouldIuseexternalstorage?Well,asImentionedearlier,externalstorageisusuallylargerthaninternalstorage.So,thefirstthingthatcomestomindistouseitforstoringlargerfilesorapps.Andthatexactlyisthemostcommonusageoftheexternalstorage.Sinceinternalstoragehaslimitedspaceforapp-specificdata,it’sgenerallyagoodideatouseexternalstorageforallofthenon-sensitivedatayourappworkswith.Eveniftheyarenotsolarge.Generally,datayousavetothisstorageispersistentthroughappuninstallation.Thereisacasethough,wherefilesaregoingtoberemovedwhenanappisdeleted.Ifyoustoreapp-specificfilestotheexternalstoragebyusinggetExternalFilesDir(),youwilllosethefileswhentheappisuninstalled,sobeawareofthat.Additionally,datastoredinthisdirectorycanbeaccessedbyotherapplicationsiftheyhaveappropriatepermission.CaveatsWhenitcomestoworkingwithexternalstorage,therearefewthingsyoushoulddobeforestoringdatathere:Verifythatthestorageisavailable — therearecaseswhereareusercanremoveaphysicalvolumewheretheexternalstorageresides.Youcancheckthevolume’sstatebyinvokingEnvironment.getExternalStorageState()method.Itwillreturnastringrepresentingthestate.Forexample,ifthemethodreturnsMEDIA_MOUNTEDyoucansafelyreadandwriteapp-specificfileswithingexternalstorage.‍Selectwhichstoragetouseincasemoreofthemexist — sometimesdevicescanhavemultiplephysicalvolumesthatcouldcontainexternalstorage.Forexample,adevicecanallocateapartitionofitsinternalmemoryasexternalstorage,butcanalsoprovideexternalstorageonanSDcard.There’sahandymethodinContextCompatclass,calledgetExternalFilesDirs().ItreturnsanarrayofFile'swhosefirstelementisconsideredtheprimaryexternalstoragevolume.StoragepermissionsAndroiddefinestwopermissionsrelatedtostorage:READ_EXTERNAL_STORAGEandWRITE_EXTERNAL_STORAGE.Asyoucansee,permissionsareonlydefinedforaccessingexternalstorage.Thatmeansthateveryapp,bydefault,haspermissionstoaccessitsinternalstorage.Ontheotherhand,ifyourapphastoaccessexternalstorage,youareobligedtorequestpermissionforthat.Thatmeansifyou’retryingtoaccessmediaonexternalstoragebyusingMediaStoreAPIyouwillneedtorequestREAD_EXTERNAL_STORAGEpermission.However,fewexceptionstothisruleexist:Whenyouareaccessingapp-specificfilesonexternalstorageyoudon’tneedtorequestanypermission(onAndroid4.4andhigher)WithscopedstorageintroducedinAndroid10,younolongerneedtorequestpermissionwhenworkingwithmediafilesthatarecreatedbyyourappYoualsodon’tneedanypermissionsifyou’retryingtoobtainanydocumentsorothertypesofcontentwhenusingStorageAccessFramework.That’sbecauseauserisinvolvedintheprocessofselectingtheactualcontenttoworkwith.Whendefiningpermissions,youcansetaconditiontoonlyapplyitforsomeversions.Forexample:IntheexampleaboveIdefinedWRITE_EXTERNAL_STORAGEpermissiononlyforversion28andbelow.Thiscancomeinhandyinsituationswhereappsrunningnewerversionscanworkwithoutpermission,butappsonolderversionswillbreakwithoutit.IntroducingScopedstorageAndroidisfocusingonprivacymoreandmorewitheveryrelease.ApplicationSandboxingisacorepartofAndroid’sdesign,isolatingappsfromeachother.Followingthatprinciple,theAndroidteamintroducedScopedstorageinAndroid10.Astheteamsaid,“It’sawaytoensuretransparency,giveuserscontrolandsecurepersonaldata.”Fromtheofficialdocumentation:MorerecentversionsofAndroidrelymoreonafile’spurposethanitslocationfordetermininganapp’sabilitytoaccessthatfile.Thispurpose-basedstoragemodelimprovesuserprivacybecauseappsaregivenaccessonlytotheareasofthedevice’sfilesystemthattheyuse.WhyScopedstorage?BeforeAndroid10,appshaveprivate,app-specificstorage.Inadditiontoprivatestorage,thesystemprovidessharedstoragewherealloftheotherfilesarestored.Theproblemisthatappscanaccessallofthesefileswhengivenstoragepermission.Fromauser’sperspective,thisdoesn’tmakesense.Let’stakeanexamplewithanappthatneedstoprovideuserswithanabilitytoselectaprofileimage.Toallowtheapptoaccessimagesyouneedtoaskforstoragereadingpermission.Giventhepermission,yourappcannowaccessimagesbutalsoalltheotherfileswithinthesharedstorage.Thereisnoneedforyourapptobeabletoseeeveryfile,onlytoallowtheusertoselectanimage.Thisisoneofthemainreasonsscopedstoragehasbeenintroduced.ThechangesThismeansthatappsthattargetAndroid10andhigheraregivenscopedaccesstoexternalstorage,orscopedstorage,bydefault.Withthischange,appshaveunrestrictedaccesstoapp-specificstorageormediathattheappitselfhascreated.But,toreadotherapplications’mediafiles,youneedtorequestreadingpermission.ForaccessingMediaStore.Downloadscollectionfilesthatyourappdidn'tcreate,youmustuseStorageAccessFramework.Ifyourappisnotreadytoadoptscopedstorageyet,youhavetwooptionstoopt-outofusingit:YoucansettargetSdkVersiontotargetAndroid9orlowerIfyourapptargetsAndroid10,youcansetrequestLegacyExternalStorageflagtotrueinAndroidManifest.xml.KeepinmindthatthisflagisremovedinAndroid11YoucanreadmoreaboutAndroid11storageupdateshere.Makesuretocheckthesecondpartofthispost!😊Likewhatyoujustread?Goon,spreadthenews!LinkedInTwitterE-MailAbouttheauthorLukaKordićisanAndroiddeveloperatCOBE.HemostlyusesKotlininhisday-to-daydevelopment,butJavaisalsoanoption.Whenhe'snotwritingAndroidapps,helikestolearnnewthingsfromthecomputerscienceworld.Inhissparetimeheplaysfootball,butalsolikesrunning,climbingandbasketball.LukaAndroidDevelopmentWriteLukaWriteCOBERelatedStoriesThiswasinterestingtoyou?Checktheseout.DevelopmentNov9,2021HowtoStartTestingBluetoothApps:ABeginner'sGuideKatarinaQAEngineeringDevelopmentOct13,2021HowtoBuildaFreeDiscordBotWithNode.JSDamirWebDevelopmentDevelopmentSep27,2021Typescript:TipsandTricksforImprovingYourCodingskills[Part2]MihaelWebDevelopmentDevelopmentNov9,2021HowtoStartTestingBluetoothApps:ABeginner'sGuideKatarinaQAEngineeringDevelopmentOct13,2021HowtoBuildaFreeDiscordBotWithNode.JSDamirWebDevelopmentDevelopmentSep27,2021Typescript:TipsandTricksforImprovingYourCodingskills[Part2]MihaelWebDevelopmentDevelopmentSep21,2021Typescript:TipsandTricksforImprovingYourCodingSkills[Part1]MihaelWebDevelopment



請為這篇文章評分?