Taming File Storage on Android — Part 1 - COBE
文章推薦指數: 80 %
Before Android 10, apps have private, app-specific storage. In addition to private storage, the system provides shared storage where all of the ...
CLOSEProjectsServicesAgencyStoriesContactENDEStoriesDevelopment5minreadPublishedAugust27,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: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:
延伸文章資訊
- 1Storage Options | Android Developers
You can save files directly on the device's internal storage. By default, files saved to the inte...
- 2Android - Internal Storage - Tutorialspoint
Internal storage is the storage of the private data on the device memory. ... package com.example...
- 3Taming File Storage on Android — Part 1 - COBE
Before Android 10, apps have private, app-specific storage. In addition to private storage, the s...
- 4Where Android apps store data?
All apps (root or not) have a default data directory, which is /data/data/<package_name> . By def...
- 5Android list files in private app storage - Stack Overflow
Private folder on Internal/external storage on android - Stack ...