Android Internal vs External Storage | COBE

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

Android defines two permissions related to storage: READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE . As you can see, permissions are only ... SigninDevelopmentDesignLibrariesGetintouchTamingFileStorageonAndroid—Part1LukaKordićFollowApr20,2020·7minreadComparinginternalandexternalstorage.IntroducingScopedstorage.Welcometothefirstpartofatwo-partseriesaboutworkingwithfilestorageinAndroid!IfyouwanttoskiptothesecondpartwhereItalkaboutMediaStoreandStorageAccessFramework,clickhere:TamingFileStorageonAndroid—Part2TinkeringwithMediaStoreAPIandStorageAccessFrameworkmedium.cobeisfresh.comAvastmajorityofappsaredoingsomeformofdatamanagement.Whetherit’sjustloadingaprofileimage,sharingimagesorvideo/audiofilesthroughmessagingorsimplystoringdata.WorkingwithfilesonAndroidcanbedaunting.Especiallyifyou’renewtoAndroid,orjusthaven’tworkedwithitinawhile.WhenitcomestosavingdataonAndroid,wecanchoosefromafewoptions:SharedPreferences—mostcommonlyusedforstoringapppreferences,askey-valuepairsDatabases(Room)—forstoringstructureddatainaprivatedatabaseFilestorage—forstoringallkindsofmedia/documentstothefilesystemIfyouarewonderingwhichoftheseoptionsisforyou,therearefoursimplequestionsintheofficialdocumentationthatyoucangothroughtofigureoutwhattypeofstorageyouneed.Inthisarticlethough,IamgoingtofocusonstoringdatatoadiskusingsomeoftheAPIsprovidedbyAndroid.Topicswearegoingtocoverinclude:CategoriesofphysicalstoragelocationsPermissionsandaccesstostorageScopedstorageWorkingwithmediacontentWorkingwithdocumentsandfilesInternalstoragevsexternalstorageAndroidsystemprovidesuswithtwotypesofphysicalstoragelocations: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.Thankyouforreadingandmakesuretocheckthesecondpartofthispost.:)TamingFileStorageonAndroid—Part2TinkeringwithMediaStoreAPIandStorageAccessFrameworkmedium.cobeisfresh.comLukaKordićisanAndroiddeveloperatCOBEOsijek.HemostlyusesKotlininhisdaytodaydevelopment,butJavaisalsoanoption.Whenhe’snotwritingAndroidapps,helikestolearnnewthingsfromthecomputerscienceworld.Hereallyenjoyssports.Inhissparetimeheplaysfootball,butalsolikesrunning,climbingandbasketball.Whennotworkingwithsoftwareorplayingsports,helikestoplayvideogames.Previouslypublishedoncobeisfresh.com.Likewhatyouread?Hitlikeandrecommendus!Tolearnmore,checkoutmorearticlesfromourteam:DevelopingAndroidappswithKotlinandCleanArchitectureKeepyourcodebasecleanmedium.cobeisfresh.comHowtoImplementDay/NightModeinYourAndroidAppFindouttheeasiestwaytodoityourself.medium.cobeisfresh.comYour5StepAutomationStarterPackThingstowatchoutforwhenstartingtheprocessofautomationmedium.cobeisfresh.comCOBEYouhaveanideaforaweboramobileapp?Follow225Publicdomain.AndroidAndroidAppDevelopmentFileManagementProgramming225 claps225WrittenbyLukaKordićFollowAndroiddeveloper@cobe_techOsijek,CroatiaFollowCOBEFollowYouhaveanideaforaweboramobileapp?Wehavetheknow-howandthenow-tech.Checkourworkathttp://cobe.tech/.FollowWrittenbyLukaKordićFollowAndroiddeveloper@cobe_techOsijek,CroatiaCOBEFollowYouhaveanideaforaweboramobileapp?Wehavetheknow-howandthenow-tech.Checkourworkathttp://cobe.tech/.MoreFromMediumHackTheBoxWriteup — ZettaFaisalHusainiFirebaseCrashlytics:HowtodebugcrasheswithoutuploadingdsymfileNishaRaniZurbFoundation6CompatibilityandAccessibilityKristoferKrauseAWS&ELASTICSEARCH—CHOOSINGTHERIGHTOPTIONMehmetUğurGüralWeakLinksvsStrongLinksinSoftwareEngineeringTeamsdr.maxTheBeginningStagesofLearningPythonThroughPygamePeterVissHackTheBoxWriteup — LaCasaDePapelFaisalHusainiSavingdatatoLocalStorageinFlutterBalaKowsalyainKick-Starting:Flutter



請為這篇文章評分?