9.0: Data storage · GitBook
文章推薦指數: 80 %
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.
延伸文章資訊
- 1store data without using database in android - Stack Overflow
- 2How to store data locally in an Android app
Internal storage
- 3what's the difference between android internal storage and external ...
- 4Data and file storage overview | Android Developers
- 5Understanding of Android storage system. - Medium
This makes internal storage a good place for internal app data that the user doesn't need to dire...