Understanding of Android storage system. - Medium

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

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:...Note:IfyourappusestheWRITE_EXTERNAL_STORAGEpermission,thenitimplicitlyhaspermissiontoreadtheexternalstorageaswell.Ifyourapponlyneedstoreadtheexternalstorage(butnotwritetoit),thenyouneedtodeclaretheREAD_EXTERNAL_STORAGEpermission:...VerifythatexternalstorageisavailableBecausetheexternalstoragemightbeunavailable—suchaswhentheuserhasmountedthestoragetoaPCorhasremovedtheSDcardthatprovidestheexternalstorage—youshouldalwaysverifythatthevolumeisavailablebeforeaccessingit.YoucanquerytheexternalstoragestatebycallinggetExternalStorageState().IfthereturnedstateisMEDIA_MOUNTED,thenyoucanreadandwriteyourfiles.Ifit'sMEDIA_MOUNTED_READ_ONLY,youcanonlyreadthefiles.Forexample,thefollowingmethodsareusefultodeterminethestorageavailability:/*Checksifexternalstorageisavailableforreadandwrite*/publicbooleanisExternalStorageWritable(){Stringstate=Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(state)){returntrue;}returnfalse;}/*Checksifexternalstorageisavailabletoatleastread*/publicbooleanisExternalStorageReadable(){Stringstate=Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(state)||Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){returntrue;}returnfalse;}SavetoapublicdirectoryIfyouwanttosavepublicfilesontheexternalstorage,usethegetExternalStoragePublicDirectory()methodtogetaFilerepresentingtheappropriatedirectoryontheexternalstorage.Themethodtakesanargumentspecifyingthetypeoffileyouwanttosavesothattheycanbelogicallyorganizedwithotherpublicfiles,suchasDIRECTORY_MUSICorDIRECTORY_PICTURES.Forexample:publicFilegetPublicAlbumStorageDir(StringalbumName){//Getthedirectoryfortheuser'spublicpicturesdirectory.Filefile=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),albumName);if(!file.mkdirs()){Log.e(LOG_TAG,"Directorynotcreated");}returnfile;}SharedpreferencesIfyoudon’tneedtostorealotofdataanditdoesn’trequirestructure,youshoulduseSharedPreferences.TheSharedPreferencesAPIsallowyoutoreadandwritepersistentkey-valuepairsofprimitivedatatypes:booleans,floats,ints,longs,andstrings.Thekey-valuepairsarewrittentoXMLfilesthatpersistacrossusersessions,evenifyourappiskilled.Youcanmanuallyspecifyanameforthefileoruseper-activityfilestosaveyourdata.TheAPIname“sharedpreferences”isabitmisleadingbecausetheAPIisnotstrictlyforsaving“userpreferences,”suchaswhatringtoneauserhaschosen.YoucanuseSharedPreferencestosaveanykindofsimpledata,suchastheuser'shighscore.However,ifyoudowanttosaveuserpreferencesforyourapp,thenyoushouldreadhowtocreateasettingsUI,whichusesPreferenceActivitytobuildasettingsscreenandautomaticallypersisttheuser'ssettings.WritetosharedpreferencesTowritetoasharedpreferencesfile,createaSharedPreferences.Editorbycallingedit()onyourSharedPreferences.PassthekeysandvaluesyouwanttowritewithmethodssuchasputInt()andputString().Thencallapply()orcommit()tosavethechanges.Forexample:SharedPreferencessharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editoreditor=sharedPref.edit();editor.putInt(getString(R.string.saved_high_score_key),newHighScore);editor.commit();apply()changesthein-memorySharedPreferencesobjectimmediatelybutwritestheupdatestodiskasynchronously.Alternatively,youcanusecommit()towritethedatatodisksynchronously.Butbecausecommit()issynchronous,youshouldavoidcallingitfromyourmainthreadbecauseitcouldpauseyourUIrendering.ReadfromsharedpreferencesToretrievevaluesfromasharedpreferencesfile,callmethodssuchasgetInt()andgetString(),providingthekeyforthevalueyouwant,andoptionallyadefaultvaluetoreturnifthekeyisn'tpresent.Forexample:SharedPreferencessharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);intdefaultValue=getResources().getInteger(R.integer.saved_high_score_default_key);inthighScore=sharedPref.getInt(getString(R.string.saved_high_score_key),defaultValue)DatabasesAndroidprovidesfullsupportforSQLitedatabases.Anydatabaseyoucreateisaccessibleonlybyyourapp.However,insteadofusingSQLiteAPIsdirectly,werecommendthatyoucreateandinteractwithyourdatabaseswiththeRoompersistencelibrary.TheRoomlibraryprovidesanobject-mappingabstractionlayerthatallowsfluentdatabaseaccesswhileharnessingthefullpowerofSQLite.AlthoughyoucanstillsavedatadirectlywithSQLite,theSQLiteAPIsarefairlylow-levelandrequireagreatdealoftimeandefforttouse.Forexample:Thereisnocompile-timeverificationofrawSQLqueries.Asyourschemachanges,youneedtoupdatetheaffectedSQLqueriesmanually.Thisprocesscanbetimeconsuminganderrorprone.YouneedtowritelotsofboilerplatecodetoconvertbetweenSQLqueriesandJavadataobjects.TheRoompersistencelibrarytakescareoftheseconcernsforyouwhileprovidinganabstractionlayeroverSQLite.ForsampleappsthatdemonstratehowtouseRoom,seethefollowingonGitHub:AndroidArchitectureComponentsBasicSampleRoom&RxJavaSampleRoomMigrationSampleMohammodBabulFollow101101 101AndroidStorageSharedpreferencesAndroidSqliteDatabaseMorefromMohammodBabulFollowMoreFromMediumAddapullrequestlinktoAsanausingGitHubactions.HosunYooinInEngineeringOnePerson’sLazyisAnotherPerson’sEfficiencyJesseBermanHowtorootBlubooX2rumakashBriefLaravelUpdatesAjuChackoChoreographyandOrchestrationIsraelFermínMontillaTheafternoonIbuiltaNEOkeysolverandhelpedreuniteaNEOownerwithhisfundsJamTechDevelopingMagento2ModuleAjithkranatungaPontemNetworkDigestPontemNetwork



請為這篇文章評分?