Android Internal vs External Storage | COBE
文章推薦指數: 80 %
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:
延伸文章資訊
- 1Use USB storage devices - Files by Google Help
Connect a USB storage device to your Android device. · On your Android device, open Files by Goog...
- 2Android Internal and External storage 讀寫檔案 ... - 隨意窩
http://blog.tonycube.com/2012/03/android-internal-and-external-storage.html1. 存在手機還是SDcardAndroid...
- 3External Storage Tutorial In Android Studio With Example
In this tutorial we gonna study about storage of data/files in android external storage or you ca...
- 4External Storage in Android with Example - GeeksforGeeks
External Storage in Android with Example · App-Specific storage: Store data files within internal...
- 5Android 的ExternalStorage | 只放拖鞋的鞋櫃
在Android 上要儲存檔案經常會用到Internal 或External Storage,對部分的應用程式來說,常見的需求是「把檔案存到SD card」。 從結論來說,Android ...