Storage Options | Android Developers

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

Use Shared Preferences for primitive data · Use internal device storage for private data · Use external storage for large data sets that are not private · Use ... Quicknav Quicknav Design Develop Distribute GooglePlayDeveloperConsole AndroidDevelopersBlog AboutAndroid Android.com AndroidDevelopers AndroidOpenSourceProject close GetStarted Style Patterns BuildingBlocks Downloads Videos Training APIGuides Reference Tools GettheSDK GoogleServices GooglePlay Publishing Promoting AppQuality Spotlight OpenDistribution Results Loading... Training APIGuides Reference Tools GoogleServices totop AppComponents AppFundamentals Activities Fragments Loaders TasksandBackStack Services BoundServices AIDL ContentProviders ContentProviderBasics CreatingaContentProvider CalendarProvider ContactsProvider IntentsandIntentFilters ProcessesandThreads Permissions AppWidgets AndroidManifest UserInterface Overview Layouts LinearLayout RelativeLayout ListView GridView InputControls Buttons TextFields Checkboxes RadioButtons ToggleButtons Spinners Pickers InputEvents Menus ActionBar Settings Dialogs Notifications Toasts Search CreatingaSearchInterface AddingRecentQuerySuggestions AddingCustomSuggestions SearchableConfiguration DragandDrop Accessibility MakingApplicationsAccessible AccessibilityDeveloperChecklist BuildingAccessibilityServices StylesandThemes CustomComponents AppResources Overview ProvidingResources AccessingResources HandlingRuntimeChanges Localization ResourceTypes Animation ColorStateList Drawable Layout Menu String Style MoreTypes AnimationandGraphics Overview PropertyAnimation ViewAnimation DrawableAnimation CanvasandDrawables OpenGL HardwareAcceleration Computation Renderscript AdvancedRenderscript RuntimeAPIReference MediaandCamera MediaPlayback SupportedMediaFormats AudioCapture JetPlayer Camera LocationandSensors LocationandMaps LocationStrategies SensorsOverview MotionSensors PositionSensors EnvironmentSensors Connectivity Bluetooth NFC NFCBasics AdvancedNFC Wi-FiDirect USB Accessory Host SIP TextandInput CopyandPaste CreatinganIME SpellingChecker DataStorage StorageOptions DataBackup AppInstallLocation Administration DevicePolicies WebApps Overview TargetingScreensfromWebApps BuildingWebAppsinWebView DebuggingWebApps BestPracticesforWebApps BestPractices BewährteVerfahren Prácticasrecomendadas Meilleurespratiques Bestpractice ベストプラクティス 最佳实践 最佳實務 Compatibility SupportingMultipleScreens DistributingtoSpecificScreens ScreenCompatibilityMode SupportingTabletsandHandsets StorageOptions Storagequickview UseSharedPreferencesforprimitivedata Useinternaldevicestorageforprivatedata Useexternalstorageforlargedatasetsthatarenotprivate UseSQLitedatabasesforstructuredstorage Inthisdocument UsingSharedPreferences UsingtheInternalStorage UsingtheExternalStorage UsingDatabases UsingaNetworkConnection Seealso ContentProvidersandContentResolvers Androidprovidesseveraloptionsforyoutosavepersistentapplicationdata.Thesolutionyou choosedependsonyourspecificneeds,suchaswhetherthedatashouldbeprivatetoyour applicationoraccessibletootherapplications(andtheuser)andhowmuchspaceyourdata requires. Yourdatastorageoptionsarethefollowing: SharedPreferences Storeprivateprimitivedatainkey-valuepairs. InternalStorage Storeprivatedataonthedevicememory. ExternalStorage Storepublicdataonthesharedexternalstorage. SQLiteDatabases Storestructureddatainaprivatedatabase. NetworkConnection Storedataonthewebwithyourownnetworkserver. Androidprovidesawayforyoutoexposeevenyourprivatedatatootherapplications —withacontent provider.Acontentproviderisanoptionalcomponentthatexposesread/writeaccessto yourapplicationdata,subjecttowhateverrestrictionsyouwanttoimpose.Formoreinformation aboutusingcontentproviders,seethe ContentProviders documentation. UsingSharedPreferences TheSharedPreferencesclassprovidesageneralframeworkthatallowsyou tosaveandretrievepersistentkey-valuepairsofprimitivedatatypes.YoucanuseSharedPreferencestosaveanyprimitivedata:booleans,floats,ints,longs,and strings.Thisdatawillpersistacrossusersessions(evenifyourapplicationiskilled). UserPreferences Sharedpreferencesarenotstrictlyforsaving"userpreferences,"suchaswhatringtonea userhaschosen.Ifyou'reinterestedincreatinguserpreferencesforyourapplication,seePreferenceActivity,whichprovidesanActivityframeworkforyoutocreate userpreferences,whichwillbeautomaticallypersisted(usingsharedpreferences). TogetaSharedPreferencesobjectforyourapplication,useoneof twomethods: getSharedPreferences()-Usethisifyouneedmultiplepreferencesfilesidentifiedbyname, whichyouspecifywiththefirstparameter. getPreferences()-Usethisifyouneed onlyonepreferencesfileforyourActivity.Becausethiswillbetheonlypreferencesfile foryourActivity,youdon'tsupplyaname. Towritevalues: Calledit()togetaSharedPreferences.Editor. AddvalueswithmethodssuchasputBoolean()andputString(). Committhenewvalueswithcommit() Toreadvalues,useSharedPreferencesmethodssuchasgetBoolean()andgetString(). Hereisanexamplethatsavesapreferenceforsilentkeypressmodeina calculator: publicclassCalcextendsActivity{ publicstaticfinalStringPREFS_NAME="MyPrefsFile"; @Override protectedvoidonCreate(Bundlestate){ super.onCreate(state); ... //Restorepreferences SharedPreferencessettings=getSharedPreferences(PREFS_NAME,0); booleansilent=settings.getBoolean("silentMode",false); setSilent(silent); } @Override protectedvoidonStop(){ super.onStop(); //WeneedanEditorobjecttomakepreferencechanges. //Allobjectsarefromandroid.context.Context SharedPreferencessettings=getSharedPreferences(PREFS_NAME,0); SharedPreferences.Editoreditor=settings.edit(); editor.putBoolean("silentMode",mSilentMode); //Committheedits! editor.commit(); } } UsingtheInternalStorage Youcansavefilesdirectlyonthedevice'sinternalstorage.Bydefault,filessaved totheinternalstorageareprivatetoyourapplicationandotherapplicationscannotaccess them(norcantheuser).Whentheuseruninstallsyourapplication,thesefilesareremoved. Tocreateandwriteaprivatefiletotheinternalstorage: CallopenFileOutput()withthe nameofthefileandtheoperatingmode.ThisreturnsaFileOutputStream. Writetothefilewithwrite(). Closethestreamwithclose(). Forexample: StringFILENAME="hello_file"; Stringstring="helloworld!"; FileOutputStreamfos=openFileOutput(FILENAME,Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); MODE_PRIVATEwillcreatethefile(orreplaceafileof thesamename)andmakeitprivatetoyourapplication.Othermodesavailableare:MODE_APPEND,MODE_WORLD_READABLE,andMODE_WORLD_WRITEABLE. Toreadafilefrominternalstorage: CallopenFileInput()andpassitthe nameofthefiletoread.ThisreturnsaFileInputStream. Readbytesfromthefilewithread(). Thenclosethestreamwithclose(). Tip:Ifyouwanttosaveastaticfileinyourapplicationat compiletime,savethefileinyourprojectres/raw/directory.Youcanopenitwith openRawResource(),passingtheR.raw.resourceID.ThismethodreturnsanInputStream thatyoucanusetoreadthefile(butyoucannotwritetotheoriginalfile). Savingcachefiles Ifyou'dliketocachesomedata,ratherthanstoreitpersistently,youshouldusegetCacheDir()toopenaFilethatrepresentstheinternaldirectorywhereyourapplicationshouldsave temporarycachefiles. Whenthedeviceis lowoninternalstoragespace,Androidmaydeletethesecachefilestorecoverspace.However,you shouldnotrelyonthesystemtocleanupthesefilesforyou.Youshouldalwaysmaintainthecache filesyourselfandstaywithinareasonablelimitofspaceconsumed,suchas1MB.Whentheuser uninstallsyourapplication,thesefilesareremoved. Otherusefulmethods getFilesDir() Getstheabsolutepathtothefilesystemdirectorywhereyourinternalfilesaresaved. getDir() Creates(oropensanexisting)directorywithinyourinternalstoragespace. deleteFile() Deletesafilesavedontheinternalstorage. fileList() Returnsanarrayoffilescurrentlysavedbyyourapplication. UsingtheExternalStorage EveryAndroid-compatibledevicesupportsashared"externalstorage"thatyoucanuseto savefiles.Thiscanbearemovablestoragemedia(suchasanSDcard)oraninternal (non-removable)storage.Filessavedtotheexternalstorageareworld-readableandcan bemodifiedbytheuserwhentheyenableUSBmassstoragetotransferfilesonacomputer. It'spossiblethatadeviceusingapartitionofthe internalstoragefortheexternalstoragemayalsoofferanSDcardslot.Inthiscase, theSDcardisnotpartoftheexternalstorageandyourappcannotaccessit(theextra storageisintendedonlyforuser-providedmediathatthesystemscans). Caution:Externalstoragecanbecomeunavailableiftheusermountsthe externalstorageonacomputerorremovesthemedia,andthere'snosecurityenforceduponfilesyou savetotheexternalstorage.Allapplicationscanreadandwritefilesplacedontheexternal storageandtheusercanremovethem. Checkingmediaavailability Beforeyoudoanyworkwiththeexternalstorage,youshouldalwayscallgetExternalStorageState()tocheckwhetherthemediaisavailable.The mediamightbemountedtoacomputer,missing,read-only,orinsomeotherstate.Forexample, here'showyoucanchecktheavailability: booleanmExternalStorageAvailable=false; booleanmExternalStorageWriteable=false; Stringstate=Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)){ //Wecanreadandwritethemedia mExternalStorageAvailable=mExternalStorageWriteable=true; }elseif(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){ //Wecanonlyreadthemedia mExternalStorageAvailable=true; mExternalStorageWriteable=false; }else{ //Somethingelseiswrong.Itmaybeoneofmanyotherstates,butallweneed //toknowiswecanneitherreadnorwrite mExternalStorageAvailable=mExternalStorageWriteable=false; } Thisexamplecheckswhethertheexternalstorageisavailabletoreadandwrite.The getExternalStorageState()methodreturnsotherstatesthatyou mightwanttocheck,suchaswhetherthemediaisbeingshared(connectedtoacomputer),ismissing entirely,hasbeenremovedbadly,etc.Youcanusethesetonotifytheuserwithmoreinformation whenyourapplicationneedstoaccessthemedia. Accessingfilesonexternalstorage Ifyou'reusingAPILevel8orgreater,usegetExternalFilesDir()toopenaFilethatrepresentstheexternalstoragedirectorywhereyoushouldsaveyour files.Thismethodtakesatypeparameterthatspecifiesthetypeofsubdirectoryyou want,suchasDIRECTORY_MUSICand DIRECTORY_RINGTONES(passnulltoreceive therootofyourapplication'sfiledirectory).Thismethodwillcreatethe appropriatedirectoryifnecessary.Byspecifyingthetypeofdirectory,you ensurethattheAndroid'smediascannerwillproperlycategorizeyourfilesinthesystem(for example,ringtonesareidentifiedasringtonesandnotmusic).Iftheuseruninstallsyour application,thisdirectoryandallitscontentswillbedeleted. Ifyou'reusingAPILevel7orlower,usegetExternalStorageDirectory(),toopenaFilerepresentingtherootoftheexternalstorage.Youshouldthenwriteyourdatainthe followingdirectory: /Android/data//files/ TheisyourJava-stylepackagename,suchas"com.example.android.app".Iftheuser'sdeviceisrunningAPILevel8orgreaterandthey uninstallyourapplication,thisdirectoryandallitscontentswillbedeleted. HidingyourfilesfromtheMediaScanner Includeanemptyfilenamed.nomediainyourexternalfilesdirectory(notethedot prefixinthefilename).ThiswillpreventAndroid'smediascannerfromreadingyourmedia filesandincludingtheminappslikeGalleryorMusic. Savingfilesthatshouldbeshared Ifyouwanttosavefilesthatarenotspecifictoyourapplicationandthatshouldnot bedeletedwhenyourapplicationisuninstalled,savethemtooneofthepublicdirectoriesonthe externalstorage.Thesedirectorieslayattherootoftheexternalstorage,suchasMusic/,Pictures/,Ringtones/,andothers. InAPILevel8orgreater,usegetExternalStoragePublicDirectory(),passingitthetypeofpublicdirectoryyouwant,suchas DIRECTORY_MUSIC,DIRECTORY_PICTURES, DIRECTORY_RINGTONES,orothers.Thismethodwillcreatethe appropriatedirectoryifnecessary. Ifyou'reusingAPILevel7orlower,usegetExternalStorageDirectory()toopenaFilethatrepresents therootoftheexternalstorage,thensaveyoursharedfilesinoneofthefollowing directories: Music/-Mediascannerclassifiesallmediafoundhereasusermusic. Podcasts/-Mediascannerclassifiesallmediafoundhereasapodcast. Ringtones/-Mediascannerclassifiesallmediafoundhereasaringtone. Alarms/-Mediascannerclassifiesallmediafoundhereasanalarmsound. Notifications/-Mediascannerclassifiesallmediafoundhereasanotification sound. Pictures/-Allphotos(excludingthosetakenwiththecamera). Movies/-Allmovies(excludingthosetakenwiththecamcorder). Download/-Miscellaneousdownloads. Savingcachefiles Ifyou'reusingAPILevel8orgreater,usegetExternalCacheDir()toopenaFilethatrepresentsthe externalstoragedirectorywhereyoushouldsavecachefiles.Iftheuseruninstallsyour application,thesefileswillbeautomaticallydeleted.However,duringthelifeofyour application,youshouldmanagethesecachefilesandremovethosethataren'tneededinorderto preservefilespace. Ifyou'reusingAPILevel7orlower,usegetExternalStorageDirectory()toopenaFilethatrepresents therootoftheexternalstorage,thenwriteyourcachedatainthefollowingdirectory: /Android/data//cache/ TheisyourJava-stylepackagename,suchas"com.example.android.app". UsingDatabases AndroidprovidesfullsupportforSQLitedatabases. Anydatabasesyoucreatewillbeaccessiblebynametoany classintheapplication,butnotoutsidetheapplication. TherecommendedmethodtocreateanewSQLitedatabaseistocreateasubclassofSQLiteOpenHelperandoverridetheonCreate()method,inwhichyou canexecuteaSQLitecommandtocreatetablesinthedatabase.Forexample: publicclassDictionaryOpenHelperextendsSQLiteOpenHelper{ privatestaticfinalintDATABASE_VERSION=2; privatestaticfinalStringDICTIONARY_TABLE_NAME="dictionary"; privatestaticfinalStringDICTIONARY_TABLE_CREATE= "CREATETABLE"+DICTIONARY_TABLE_NAME+"("+ KEY_WORD+"TEXT,"+ KEY_DEFINITION+"TEXT);"; DictionaryOpenHelper(Contextcontext){ super(context,DATABASE_NAME,null,DATABASE_VERSION); } @Override publicvoidonCreate(SQLiteDatabasedb){ db.execSQL(DICTIONARY_TABLE_CREATE); } } YoucanthengetaninstanceofyourSQLiteOpenHelper implementationusingtheconstructoryou'vedefined.Towritetoandreadfromthedatabase,call getWritableDatabase()andgetReadableDatabase(),respectively.Thesebothreturna SQLiteDatabaseobjectthatrepresentsthedatabaseand providesmethodsforSQLiteoperations. AndroiddoesnotimposeanylimitationsbeyondthestandardSQLiteconcepts.Wedorecommend includinganautoincrementvaluekeyfieldthatcanbeusedasauniqueIDto quicklyfindarecord.Thisisnotrequiredforprivatedata,butifyou implementacontentprovider, youmustincludeauniqueIDusingtheBaseColumns._ID constant. YoucanexecuteSQLitequeriesusingtheSQLiteDatabase query()methods,whichacceptvariousqueryparameters,suchasthetabletoquery, theprojection,selection,columns,grouping,andothers.Forcomplexqueries,suchas thosethatrequirecolumnaliases,youshoulduse SQLiteQueryBuilder,whichprovides severalconvienentmethodsforbuildingqueries. EverySQLitequerywillreturnaCursorthatpointstoalltherows foundbythequery.TheCursorisalwaysthemechanismwithwhich youcannavigateresultsfromadatabasequeryandreadrowsandcolumns. ForsampleappsthatdemonstratehowtouseSQLitedatabasesinAndroid,seethe NotePadand SearchableDictionary applications. Databasedebugging TheAndroidSDKincludesasqlite3databasetoolthatallowsyoutobrowse tablecontents,runSQLcommands,andperformotherusefulfunctionsonSQLite databases.SeeExaminingsqlite3 databasesfromaremoteshelltolearnhowtorunthistool. UsingaNetworkConnection Youcanusethenetwork(whenit'savailable)tostoreandretrievedataonyourownweb-based services.Todonetworkoperations,useclassesinthefollowingpackages: java.net.* android.net.* Previous Next Exceptasnoted,thiscontentis licensedunder CreativeCommonsAttribution2.5.Fordetailsand restrictions,seetheContent License. AboutAndroid  |  Legal  |  Support



請為這篇文章評分?