Understanding of Android storage system. - Medium
文章推薦指數: 80 %
This makes internal storage a good place for internal app data that the user doesn't need to directly access. The system provides a private directory on the ...
GetstartedOpeninappMohammodBabulSigninGetstarted5FollowersAboutGetstartedOpeninappMohammodBabulJul31,2018·8minreadUnderstandingofAndroidstoragesystem.Androidprovidesseveraloptionsforyoutosaveyourappdata.Thesolutionyouchoosedependsonyourspecificneeds,suchashowmuchspaceyourdatarequires,whatkindofdatayouneedtostore,andwhetherthedatashouldbeprivatetoyourapporaccessibletootherappsandtheuser.Thereare4typeofstoragethatandroidprovide.Internalfilestorage:Storeapp-privatefilesonthedevicefilesystem.Externalfilestorage:Storefilesonthesharedexternalfilesystem.Thisisusuallyforshareduserfiles,suchasphotos.Sharedpreferences:Storeprivateprimitivedatainkey-valuepairs.Databases:Storestructureddatainaprivatedatabase.FileProvide:IfyouwanttosharefileswithotherappsInternalstorageBydefault,filessavedtotheinternalstorageareprivatetoyourapp,andotherappscannotaccessthem(norcantheuser,unlesstheyhaverootaccess).Thismakesinternalstorageagoodplaceforinternalappdatathattheuserdoesn’tneedtodirectlyaccess.Thesystemprovidesaprivatedirectoryonthefilesystemforeachappwhereyoucanorganizeanyfilesyourappneeds.Whentheuseruninstallsyourapp,thefilessavedontheinternalstorageareremoved.Becauseofthisbehavior,youshouldnotuseinternalstoragetosaveanythingtheuserexpectstopersistindependentlyofyourapp.Forexample,ifyourappallowsuserstocapturephotos,theuserwouldexpectthattheycanaccessthosephotosevenaftertheyuninstallyourapp.Soyoushouldinsteadsavethosetypesoffilestothepublicexternalstorage.WriteafileWhensavingafiletointernalstorage,youcanacquiretheappropriatedirectoryasaFilebycallingoneoftwomethods:getFilesDir()ReturnsaFilerepresentinganinternaldirectoryforyourapp.getCacheDir()ReturnsaFilerepresentinganinternaldirectoryforyourapp'stemporarycachefiles.Besuretodeleteeachfileonceitisnolongerneededandimplementareasonablesizelimitfortheamountofmemoryyouuseatanygiventime,suchas1MB.Caution:Ifthesystemrunslowonstorage,itmaydeleteyourcachefileswithoutwarning.Tocreateanewfileinoneofthesedirectories,youcanusetheFile()constructor,passingtheFileprovidedbyoneoftheabovemethodsthatspecifiesyourinternalstoragedirectory.Forexample:Filefile=newFile(context.getFilesDir(),filename);Alternatively,youcancallopenFileOutput()togetaFileOutputStreamthatwritestoafileinyourinternaldirectory.Forexample,here'showtowritesometexttoafile:Stringfilename="myfile";StringfileContents="Helloworld!";FileOutputStreamoutputStream;try{outputStream=openFileOutput(filename,Context.MODE_PRIVATE);outputStream.write(fileContents.getBytes());outputStream.close();}catch(Exceptione){e.printStackTrace();}InternalcachefilesIfyou’dliketokeepsomedatatemporarily,ratherthanstoreitpersistently,youshouldusethespecialcachedirectorytosavethedata.Eachapphasaprivatecachedirectoryspecificallyforthesekindsoffiles.Whenthedeviceislowoninternalstoragespace,Androidmaydeletethesecachefilestorecoverspace.However,youshouldnotrelyonthesystemtocleanupthesefilesforyou.Youshouldalwaysmaintainthecachefilesyourselfandstaywithinareasonablelimitofspaceconsumed,suchas1MB.Whentheuseruninstallsyourapp,thesefilesareremoved.WriteacachefileIfyouinsteadneedtocachesomefiles,youshouldusecreateTempFile().Forexample,thefollowingmethodextractsthefilenamefromaURLandcreatesafilewiththatnameinyourapp'sinternalcachedirectory:privateFilegetTempFile(Contextcontext,Stringurl){Filefile;try{StringfileName=Uri.parse(url).getLastPathSegment();file=File.createTempFile(fileName,null,context.getCacheDir());}catch(IOExceptione){//Errorwhilecreatingfile}returnfile;}ExternalstorageEveryAndroiddevicesupportsashared“externalstorage”spacethatyoucanusetosavefiles.Thisspaceiscalledexternalbecauseit’snotaguaranteedtobeaccessible—itisastoragespacethatuserscanmounttoacomputerasanexternalstoragedevice,anditmightevenbephysicallyremovable(suchasanSDcard).Filessavedtotheexternalstorageareworld-readableandcanbemodifiedbytheuserwhentheyenableUSBmassstoragetotransferfilesonacomputer.Sobeforeyouattempttoaccessafileinexternalstorageinyourapp,youshouldcheckfortheavailabilityoftheexternalstoragedirectoriesaswellasthefilesyouaretryingtoaccess.Mostoften,youshoulduseexternalstorageforuserdatathatshouldbeaccessibletootherappsandsavedeveniftheuseruninstallsyourapp,suchascapturedphotosordownloadedfiles.Thesystemprovidesstandardpublicdirectoriesforthesekindsoffiles,sotheuserhasonelocationforalltheirphotos,ringtones,music,andsuch.SaveafileonexternalstorageUsingtheexternalstorageisgreatforfilesthatyouwanttosharewithotherappsorallowtheusertoaccesswithacomputer.Afteryourequeststoragepermissionsandverifythatstorageisavailable,youcansavetwodifferenttypesoffiles:Publicfiles:Filesthatshouldbefreelyavailabletootherappsandtotheuser.Whentheuseruninstallsyourapp,thesefilesshouldremainavailabletotheuser.Forexample,photoscapturedbyyourapporotherdownloadedfilesshouldbesavedaspublicfiles.Privatefiles:Filesthatrightfullybelongtoyourappandwillbedeletedwhentheuseruninstallsyourapp.Althoughthesefilesaretechnicallyaccessiblebytheuserandotherappsbecausetheyareontheexternalstorage,theydon’tprovidevaluetotheuseroutsideofyourapp.Caution:TheexternalstoragemightbecomeunavailableiftheuserremovestheSDcardorconnectsthedevicetoacomputer.AndthefilesarestillvisibletotheuserandotherappsthathavetheREAD_EXTERNAL_STORAGEpermission.Soifyourapp'sfunctionalitydependsonthesefilesoryouneedtocompletelyrestrictaccess,youshouldinsteadwriteyourfilestotheinternalstorage.RequestexternalstoragepermissionsTowritetothepublicexternalstorage,youmustrequesttheWRITE_EXTERNAL_STORAGEpermissioninyourmanifestfile:
延伸文章資訊
- 1Data Storage on Android - Mobile Security Testing Guide
In general sensitive data stored locally on the device should always be at least encrypted, and a...
- 2Understanding of Android storage system. - Medium
This makes internal storage a good place for internal app data that the user doesn't need to dire...
- 3Access Private Data on Android - Margaret Maynard-Reid
- 4Data and file storage overview | Android Developers
- 5store data without using database in android - Stack Overflow