9.0: Data storage · GitBook

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

All Android devices have two file storage areas: "internal" and "external" storage. These names come from the early days of Android, when most devices offered ... Introduction Unit1:Getstarted Lesson1:Buildyourfirstapp 1.0:IntroductiontoAndroid 1.1:YourfirstAndroidapp 1.2:LayoutsandresourcesfortheUI 1.3:Textandscrollingviews 1.4:Resourcestohelpyoulearn Lesson2:Activitiesandintents 2.1:Activitiesandintents 2.2:Activitylifecycleandstate 2.3:Implicitintents Lesson3:Testing,debugging,andusingsupportlibraries 3.1:TheAndroidStudiodebugger 3.2:Apptesting 3.3:TheAndroidSupportLibrary Unit2:Userexperience Lesson4:Userinteraction 4.1:Buttonsandclickableimages 4.2:Inputcontrols 4.3:Menusandpickers 4.4:Usernavigation 4.5:RecyclerView Lesson5:Delightfuluserexperience 5.1:Drawables,styles,andthemes 5.2:MaterialDesign 5.3:Resourcesforadaptivelayouts Lesson6:TestingyourUI 6.1:UItesting Unit3:Workinginthebackground Lesson7:Backgroundtasks 7.1:AsyncTaskandAsyncTaskLoader 7.2:Internetconnection 7.3:Broadcasts 7.4:Services Lesson8:AlarmsandSchedulers 8.1:Notifications 8.2:Alarms 8.3:Efficientdatatransfer Unit4:SavingUserData Lesson9:Preferencesandsettings 9.0:Datastorage 9.1:Sharedpreferences 9.2:Appsettings Lesson10:StoringdatawithRoom 10.0:SQLiteprimer 10.1:Room,LiveData,andViewModel Appendix Appendix:Utilities PublishedwithGitBook 9.0:Datastorage 9.0:Datastorage Contents: Sharedpreferences Files SQLitedatabase Roompersistencelibrary Otherstorageoptions Learnmore Androidprovidesseveraloptionsforyoutosavepersistentappdata.Thesolutionyouchoosedependsonyourspecificneeds,suchaswhetherthedatashouldbeprivatetoyourapporaccessibletootherapps(andtheuser)andhowmuchspaceyourdatarequires. Yourdatastorageoptionsincludethefollowing: Sharedpreferences:Storeprivateprimitivedatainkey-valuepairs.Thisiscoveredinthenextchapter. Internalstorage:Storeprivatedataonthedevicememory. Externalstorage:Storepublicdataonthesharedexternalstorage. SQLitedatabases:Storestructureddatainaprivatedatabase. Roompersistencelibrary:PartoftheAndroidArchitectureComponentlibraries.RoomcachesanSQLitedatabaselocally,andautomaticallysyncschangestoanetworkdatabase Cloudbackup:Backupyourappanduserdatainthecloud. Firebaserealtimedatabase:StoreandsyncdatawithaNoSQLclouddatabase.Dataissyncedacrossallclientsinrealtime,andremainsavailablewhenyourappgoesoffline. Customdatastore:ConfigurethePreferenceAPIstostorepreferencesinastoragelocationyouprovide. Sharedpreferences Usingsharedpreferencesisawaytoreadandwritekey-valuepairsofinformationpersistentlytoandfromafile.SharedPreferencesiscoveredinitsownchapter. Note:ThePreferenceAPIsareusedtocreateandstoreusersettingsforyourapp.AlthoughthePreferenceAPIsusesharedpreferencestostoretheirdata,theyarenotthesamething.Youwilllearnmoreaboutsettingsandpreferencesinalaterchapter. Files Androidusesafilesystemthat'ssimilartodisk-basedfilesystemsonotherplatformssuchasLinux.File-basedoperationsshouldbefamiliartoanyonewhohasusedLinuxfileI/Oorthejava.iopackage. AllAndroiddeviceshavetwofilestorageareas:"internal"and"external"storage.ThesenamescomefromtheearlydaysofAndroid,whenmostdevicesofferedbuilt-innon-volatilememory(internalstorage),plusaremovablestoragemediumsuchasamicroSDcard(externalstorage). Today,somedevicesdividethepermanentstoragespaceinto"internal"and"external"partitions,soevenwithoutaremovablestoragemedium,therearealwaystwostoragespacesandtheAPIbehavioristhesamewhethertheexternalstorageisremovableornot.Thefollowinglistssummarizethefactsabouteachstoragespace. Internalstorage Externalstorage Alwaysavailable. Notalwaysavailable,becausetheusercanmounttheexternalstorageasUSBstorageandinsomecasesremoveitfromthedevice. Onlyyourappcanaccessfiles.Specifically,yourapp'sinternalstoragedirectoryisspecifiedbyyourapp'spackagenameinaspeciallocationoftheAndroidfilesystem.Otherappscannotbrowseyourinternaldirectoriesanddonothavereadorwriteaccessunlessyouexplicitlysetthefilestobereadableorwritable. World-readable.Anyappcanread. Whentheuseruninstallsyourapp,thesystemremovesallyourapp'sfilesfrominternalstorage. Whentheuseruninstallsyourapp,thesystemremovesyourapp'sfilesfromhereonlyifyousavetheminthedirectoryfromgetExternalFilesDir(). Internalstorageisbestwhenyouwanttobesurethatneithertheusernorotherappscanaccessyourfiles. Externalstorageisthebestplaceforfilesthatdon'trequireaccessrestrictionsandforfilesthatyouwanttosharewithotherappsorallowtheusertoaccesswithacomputer. Internalstorage Youdon'tneedanypermissionstosavefilesontheinternalstorage.Yourappalwayshaspermissiontoreadandwritefilesinitsinternalstoragedirectory. Youcancreatefilesintwodifferentdirectories: Permanentstorage:getFilesDir() Temporarystorage:getCacheDir().Recommendedforsmall,temporaryfilestotalinglessthan1MB.Notethatthesystemmaydeletetemporaryfilesifitrunslowonmemory. Tocreateanewfileinoneofthesedirectories,youcanusetheFile()constructor,passingtheFileprovidedbyoneoftheabovemethodsthatspecifiesyourinternalstoragedirectory.Forexample: Filefile=newFile(context.getFilesDir(),filename); Alternatively,youcancallopenFileOutput()togetaFileOutputStreamthatwritestoafileinyourinternaldirectory.Forexample,here'showtowritesometexttoafile: Stringfilename="myfile"; Stringstring="Helloworld!"; FileOutputStreamoutputStream; try{ outputStream=openFileOutput(filename,Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close(); }catch(Exceptione){ e.printStackTrace(); } Or,ifyouneedtocachesomefiles,insteadusecreateTempFile().Forexample,thefollowingmethodextractsthefilenamefromaURLandcreatesafilewiththatnameinyourapp'sinternalcachedirectory: publicFilegetTempFile(Contextcontext,Stringurl){ Filefile; try{ StringfileName=Uri.parse(url).getLastPathSegment(); file=File.createTempFile(fileName,null,context.getCacheDir()); }catch(IOExceptione){ //Errorwhilecreatingfile } returnfile; } Externalstorage Useexternalstorageforfilesthatshouldbepermanentlystored,evenifyourappisuninstalled,andbeavailablefreelytootherusersandapps,suchaspictures,drawings,ordocumentsmadebyyourapp. Someprivatefilesthatareofnovaluetootherappscanalsobestoredonexternalstorage.Suchfilesmightbeadditionaldownloadedappresources,ortemporarymediafiles.Makesureyoudeletethosewhenyourappisuninstalled. Obtainpermissionsforexternalstorage Towritetotheexternalstorage,youmustrequesttheWRITE_EXTERNAL_STORAGEpermissioninyourAndroidmanifest.Thisimplicitlyincludespermissiontoread. ... Ifyourappneedstoreadtheexternalstorage(butnotwritetoit),thenyouwillneedtodeclaretheREAD_EXTERNAL_STORAGEpermission. ... Alwayscheckwhetherexternalstorageismounted Becausetheexternalstoragemaybeunavailable—suchaswhentheuserhasmountedthestoragetoaPCorhasremovedtheSDcardthatprovidestheexternalstorage—youshouldalwaysverifythatthevolumeisavailablebeforeaccessingit.YoucanquerytheexternalstoragestatebycallinggetExternalStorageState().IfthereturnedstateisequaltoMEDIA_MOUNTED,thenyoucanreadandwriteyourfiles.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; } Publicandprivateexternalstorage ExternalstorageisveryspecificallystructuredbytheAndroidsystemforvariouspurposes.Therearepublicandprivatedirectoriesspecifictoyourapp.Eachofthesefiletreeshasdirectoriesidentifiedbysystemconstants. Forexample,anyfilesthatyoustoreintothepublicringtonedirectoryDIRECTORY_RINGTONESareavailabletoallotherringtoneapps. Ontheotherhand,anyfilesyoustoreinaprivateringtonedirectoryDIRECTORY_RINGTONEScan,bydefault,onlybeseenbyyourappandaredeletedalongwithyourapp. Seelistofpublicdirectoriesforthefulllisting. Gettingfiledescriptors Toaccessapublicexternalstoragedirectory,getapathandcreateafilecallinggetExternalStoragePublicDirectory(). Filepath=Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); Filefile=newFile(path,"DemoPicture.jpg"); Toaccessaprivateexternalstoragedirectory,getapathandcreateafilecallinggetExternalFilesDir(). Filefile=newFile(getExternalFilesDir(null),"DemoFile.jpg"); Queryingstoragespace Ifyouknowaheadoftimehowmuchdatayou'resaving,youcanfindoutwhethersufficientspaceisavailablewithoutcausinganIOExceptionbycallinggetFreeSpace()orgetTotalSpace().Thesemethodsprovidethecurrentavailablespaceandthetotalspaceinthestoragevolume,respectively. Youaren'trequiredtochecktheamountofavailablespacebeforeyousaveyourfile.Youcaninsteadtrywritingthefilerightaway,thencatchanIOExceptionifoneoccurs.Youmayneedtodothisifyoudon'tknowexactlyhowmuchspaceyouneed. Deletingfiles Youshouldalwaysdeletefilesthatyounolongerneed.Themoststraightforwardwaytodeleteafileistohavetheopenedfilereferencecalldelete()onitself. myFile.delete(); Ifthefileissavedoninternalstorage,youcanalsoasktheContexttolocateanddeleteafilebycallingdeleteFile(): myContext.deleteFile(fileName); Asagoodcitizen,youshouldalsoregularlydeletecachedfilesthatyoucreatedwithgetCacheDir(). Interactingwithfiles:summary Onceyouhavethefiledescriptors,usestandardjava.iofileoperatorsorstreamstointeractwiththefiles.ThistopicisnotAndroid-specific,soit'snotcoveredhere. SQLitedatabase Savingdatatoadatabaseisidealforrepeatingorstructureddata,suchascontactinformation.AndroidprovidesanSQL-likedatabaseforthispurpose. TheSQLitePrimerchaptergivesyouanoverviewonusinganSQLitedatabase. Roompersistencelibrary TheRoompersistencelibraryprovidesanabstractionlayeroverSQLitetoallowfluentdatabaseaccesswhileharnessingthefullpowerofSQLite. Thelibraryhelpsyoucreateacacheofyourapp'sdataonadevicethat'srunningyourapp.Thiscache,whichservesasyourapp'ssinglesourceoftruth,allowsuserstoviewaconsistentcopyofkeyinformationwithinyourapp,regardlessofwhetherusershaveaninternetconnection. YouwilllearnmoreaboutRoomintheRoom,LiveData,andViewModelchapter.FormoreinformationseetheRoomtrainingguide. Otherstorageoptions Androidprovidesadditionalstorageoptionsthatarebeyondthescopeofthisintroductorycourse.Ifyou'dliketoexplorethem,seetheLearnMoresectionbelow. Networkconnection Youcanusethenetwork(whenit'savailable)tostoreandretrievedataonyourownweb-basedservices.Todonetworkoperations,useclassesinthefollowingpackages: java.net android.net Backingupappdata Usersofteninvestsignificanttimeandeffortcreatingdataandsettingpreferenceswithinapps.Preservingthatdataforusersiftheyreplaceabrokendeviceorupgradetoanewoneisanimportantpartofensuringagreatuserexperience. AutobackupforAndroid6.0(APIlevel23)andhigher ForappswhosetargetSDKversionisAndroid6.0(APIlevel23)andhigher,devicesrunningAndroid6.0andhigherautomaticallybackupappdatatothecloud.Thesystemperformsthisautomaticbackupfornearlyallappdatabydefault,anddoessowithoutyouwritinganyadditionalappcode. Whenauserinstallsyourapponanewdevice,orre-installsyourapponone(forexample,afterafactoryreset),thesystemautomaticallyrestorestheappdatafromthecloud.Theautomaticbackupfeaturepreservesthedatayourappcreatesonauserdevicebyuploadingittotheuser'sGoogleDriveaccountandencryptingit.Thereisnochargetoyouortheuserfordatastorage,andthesaveddatadoesnotcounttowardstheuser'spersonalGoogleDrivequota.Eachappcanstoreupto25MB.Onceitsbacked-updatareaches25MB,theappnolongersendsdatatothecloud.Ifthesystemperformsadatarestore,itusesthelastdatasnapshotthattheapphadsenttothecloud. Automaticbackupsoccurwhenthefollowingconditionsaremet: Thedeviceisidle. Thedeviceischarging. ThedeviceisconnectedtoaWi-Finetwork. Atleast24hourshaveelapsedsincethelastbackup. Youcancustomizeandconfigureautobackupforyourapp.SeeConfiguringAutoBackupforApps. BackupAPIforAndroid5.1(APIlevel22)andlower ForuserswithpreviousversionsofAndroid,youneedtousetheBackupAPItoimplementdatabackup.Insummary,thisrequiresyouto: RegisterfortheAndroidBackupServicetogetaBackupServiceKey. ConfigureyourManifesttousetheBackupService. CreateabackupagentbyextendingtheBackupAgentHelperclass. Requestbackupswhendatahaschanged. Moreinformationandsamplecode: UsingtheBackupAPI DataBackup Firebase Firebaseisamobileplatformthathelpsyoudevelopapps,growyouruserbase,andearnmoremoney.Firebaseismadeupofcomplementaryfeaturesthatyoucanmix-and-matchtofityourneeds. SomefeaturesareAnalytics,CloudMessaging,Notifications,andtheTestLab. Fordatamanagement,FirebaseoffersaRealtimeDatabase. StoreandsyncdatawithaNoSQLclouddatabase. Connectedappssharedata Hostedinthecloud DataisstoredasJSON Dataissynchronizedinrealtimetoeveryconnectedclient Dataremainsavailablewhenyourappgoesoffline SeetheFirebasehomeformoreinformation. Customdatastoreforpreferences Bydefault,thePreferenceclassstoresitsvaluesintotheSharedPreferencesinterface,whichistherecommendedwaytopersistuserpreferences.However,providingacustomdatastoretoyourpreferencescanbeusefulifyourappstoresthepreferencesinacloudorlocaldatabase,orifthepreferencesaredevice-specific. OndevicesrunningAndroid8.0(APIlevel26)orhigher,youcanachievethisbyprovidinganyPreferenceobjectwithyourimplementationofthePreferenceDataStoreinterface. SeeSettingupacustomdatastoreformoreinformation. Learnmore Files: Savefilesondevicestorage getExternalFilesDir()documentationandcodesamples getExternalStoragePublicDirectory()documentationandcodesamples java.io.Fileclass Oracle'sJavaI/OTutorial Backup: Databackupoverview BackupuserdatawithAutoBackup Backupkey-valuepairswithAndroidBackupService Sharedpreferences: Savekey-valuedata Sharedpreferencesguide SharedPreferencesreference Firebase: Firebasehome FirebaseRealtimeDatabase AddFirebasetoYourAndroidProject resultsmatching"" Noresultsmatching""



請為這篇文章評分?