Android Development — Working with Internal Storage and ...

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

Internal Storage: Internal storage is a closed non-shareable space which is always available on your device. It holds dedicated directories for ... SigninProAndroidDevSubmitArchiveAboutEventsdroidconAndroidDevelopment — WorkingwithInternalStorageandExternalStorage.HarshalDevFollowMay12,2020·8minread“Whensomeonediscoversthatyouarewritingatextbook,onequestionwillbeasked.“Whyareyouwritingabook?”andthequestionisfairlyeasytoanswer.Youarewritingabookbecauseyouarenotentirelysatisfiedwiththeavailabletexts.”—GeorgeCasellaThisarticleisnotabook,howeverit’sexistenceisjustifiedbysimilarcircumstances.TheofficialAndroiddocumentationcarriesnopagesdedicatedspecificallytothetopicsofInternalandExternalstorage.Thoughoneofit’spagesprovidesanOverviewoftheAndroidStorageModelandexplainsthedifferentwaysyoucanstoreyourapplication’sdata,itstillfailstoprovideanyexactdefinitionsofInternalorExternalstorageandtouchesuponthesetopicsonlyverybriefly.Thismightleavenewdevelopersconfusedandwonderingabouttheexactnatureofthesetwostorageentities.ThescopeofthisarticleislimitedtodevelopingaperspectiveaboutInternalandExternalstorageanddemonstratingafewtechniquesforinteractingwiththemviacodesnippets.Holdon,areyouastudent?Areyoutiredofusinganotebooktokeeptrackofyourclassesanddeadlines?Worrynot!TryClassroomAid,I’vebuiltthisappspecificallyforyouandit’saonestopsolutionformanagingallyourclassroomrelatedactivities!ClassroomAidOverviewTheAndroidStorageModelisconfusing.Thereisnothingsimpleorstraightforwardaboutit,especiallyifyouarenewtoapplicationdevelopmentandtheonlyexperiencethatyoupossesswithfilesandfilesystemscomesfromworkingwithsimpleAPIsprovidedbyyourprogramminglanguageofchoice.However,thestoragemodelonAndroidwasn’talwaysthiscomplex.BackintheancientdaysAndroidapplicationscoulddowhatevertheywanted,theycouldaccessexternalstoragefreelywithouthavingtoaskforreadorwritepermissions.Butovertheyears,asuserprivacyhasbecomeaconcern,themodelhasevolvedincomplexity.Firstthingsfirst,whatisExternalStorage?AndhowisitdifferentfromInternalstorage?Strictlyfromthepointofviewofadeveloper,tryingtofindtheexactlocationsofInternalorExternalstorageonyourdevice’sdiskisanexerciseinfutility,becauseasadeveloperyoudonotneedhardcodedpaths(e.g/sdcardor/data)totheirlocationsinordertobeabletousethem.Iunderstandthataslearnersweareallobsessedwithdefinitions,butunfortunatelyIwouldliketotakethismomenttodisappointyouwithsomefacts.TheofficialAndroiddocumentationonstorage,providesnoclarificationabouttheterm‘Internalstorage’anditonlyreferencesexternalstoragewhentalkingaboutremovablevolumesasbeingapartofit.However,ifyoureadthe‘Note’providedonthedocumentationofthisnowdeprecatedmethodgetExternalStorageDirectory(),youmightbegintogainsomeideaaboutexternalstorage.DefinitionsForthepurposeofbeingabletoworkwithInternalandExternalstorageonAndroid,Iconsiderthefollowingsuperficialdefinitionssufficient:InternalStorage:Internalstorageisaclosednon-shareablespacewhichisalwaysavailableonyourdevice.Itholdsdedicateddirectoriesforeachapplicationwhichcanbeusedbytheapplicationstostoresensitiveandrelevantdata.Thus,thesededicateddirectoriesareonlyaccessibletotheirownerapplicationsandarecompletelyinaccessibletousersorforeignapplications.Also,becauseeachofthesedirectoriesareassociatedwithanapplication,iftheuseruninstallsanapplication,it’sdedicateddirectoryalongwithallit’scontentsareremovedfromthedevice.Note:Onrooteddevices,thesedirectoriesareaccessibletotheuser,sotheyaren’tcompletelysecure.Soavoidstoringuser/databasepasswordsonXMLfileshere.ExternalStorage:Externalstorageisanopensharedspacewhichmightnotalwaysbeavailableonyourdevice.Itholdsdatathatissharedamongandisaccessibleto,allapplicationsonthedevice.Itiscomposedofthespaceprovidedbythedevice’sbuilt-insharedstoragealongwiththespaceprovidedbyanymountedremovablevolumes(suchasanSDcard).Onsomedevices,thereisnobuilt-inexternalstorageandthusexternalstorageisprovidedbyamountedremovablevolume.Insuchascenario,iftheuserunmountstheremovablevolume,theexternalstorageisnolongeravailable.Thereforeitisanunreliablestoragespacewhichisnotalwaysguaranteedtobeavailableunlikeinternalstorage.Keepinmindthatthedefinitionsprovidedabovearenotcomplete,theyareonlymeanttoprovideaperspectiveforworkingwithExternalandInternalstorage.IfyoureallywishtobeAliceinWonderlandandarereadytodivedowntherabbitholeinsearchofthelocationsofInternalandExternalStorageonyourdevice,thenIwouldsuggestyoutocurbyourcuriosityifyouaren’tawareofwhatemulatedfilesystemsare,becausedivingdownthisrabbitholecouldleadtoalotofconfusionandcoulddistorttheviewthattheabovetwodefinitionshaveattemptedtocreate.Onereasonforthis?Asthisarticlepointsout,thelocationofexternalstoragehaschangedovertheyearsandcontinuestochangeoverdifferentdevices.Butifyoucontinuetoinsist,Iwouldpointyoutotwomoreplacesbesidesthatarticle:TheStorageSituation:InternalStorageBackin2014,Iwroteaseriesofblogpoststotrytoclearupconfusionaroundwhereyoucanreadandwritefilesin…commonsware.comhttps://developer.android.com/studio/debug/device-file-explorerExternalStorageThePastBeforeAndroidO(API29),themethodgetExternalStorageDirectory()wasnotdeprecatedandlifewaseasier,mostdeveloperssimplydefinedexternalstorageasthedirectorytreereturnedbythismethod.HenceallyouhadtodotocreateafileonexternalstoragewasopenaByteStream/CharacterStreamtothelocationreturnedbythismethodandwriteyourbytes/characterstoitjustasyoudowhencreatingafilewithJava(Althoughthiswasdiscouragedasitpollutedtheuser’srootnamespaceandinsteadyouwereadvisedtowritetoadirectorysuchas‘Downloads’underthisdirectorytreeusinggetExternalStoragePublicDirectory()method).BeforeAndroidKitKat(4.4)youonlyneededpermissiontowritetothispath,howeverafterKitKatyoualsoneededpermissiontoreadfromthispath.Thesepermissionshadtobeexplicitlygrantedbytheuser.Regardless,lifewasstillaloteasier.BelowisanexamplecodethatIonceusedforcreatingafileunderthe‘Downloads’directoryonexternalstorage,thiswouldstillworkondevicesrunningversionsofAndroidbelowAndroidO.ThePresentIfyou’vetakenthetimetoclickonthedocumentationforthegetExternalStorageDirectory()method,youareawareofthefactthatbeyondAndroidO,directaccesstoexternalstorageisnolongersupportedandthepathreturnedbythismethodisnolongeraccessible.Sohowarewesupposedtointeractwithexternalstoragenow?Theansweris:UseaContentProvider.Acontentprovidermanagesaccesstoasharedrepositoryofdata.Externalstorageisasharedrepositoryofdata.Henceitisnaturalthataccesstoitisnowmanagedbyacontentprovider.Buthere’sanothercatch,dependingonthetypeofdatapresentinexternalstoragewehavetwodifferentcontentprovidersmanagingaccess:MediaProvider:Managesaccesstoshareablemediafilessuchasaudio,videoandimagefiles.DocumentsProvider:ManagesaccesstoothertypesofshareablefileasPDFfilesorEUPBformatfiles.Theseprovidersworkunderdifferentframeworks,theDocumentsProviderispartoftheStorageAccessFrameworkandtheMediaProvidercommunicatesthroughtheMediaStoreAPI.YoucanuseaContentResolverobjecttocommunicatewiththeMediaStoreabstraction,howeverforcommunicatingwithaDocumentsProvideryouneedtofollowthestepsmentionedhereandissueanIntentthatcontainsastoragerelatedintentaction.TherearethreeusecasesundertheStorageAccessFrameworkandeachactioncorrespondstooneofthoseusecases.BelowisanexampleshowingyouhowtocreateafileusingtheDocumentsProvider.WhenyouissueanIntentwithanaction‘ACTION_CREATE_DOCUMENT’theDocumentsProvidershowsastandardUItotheuser,allowingthemtonavigatetoalocationonexternalstorageandreturnaURItothatlocation.ThenyoucanusetheURItoopenanOutputStreamtothelocationandwritetothatlocation.AWordonPermissionsYoumighthavenoticedthatIhavenottalkedaboutanypermissionsforwritingtoexternalstorageusingtheStorageAccessFramework,andthereasonisthatyoudonotneedany!BecausetheDocumentsProviderprovidesastandardUIthatiscontrolledbytheuser,permissionsareautomaticallygranted.WhentheuserselectsafileusingtheUI,thesystemissuesatemporaryURIpermissiongranttotheapplicationwhichallowstheapplicationtoperformread/writeoperationsonthefilebehindtheURI.WiththeMediaStorehowever,thesituationisabitdifferent.YouneedtorequestpermissionsforreadingandwritingifyourdevicerunsAndroid9orbelow.However,withAndroid10andabove,whetherpermissionsneedtoberequesteddependsonwhetheryourapplicationusesscopedstorage.Iknowthisisgettingcomplicated,soIwillnotdwellonthisanymore.Youshouldwatchthisvideoonscopedstorageforbetteraunderstanding.InternalStorageFrankly,withregardstoInternalstorage,nothinghaschangedandtheycontinuetobealotmoreeasiertousethanExternalstorage.Inordertoaccessyourapplication’sdedicateddirectoriesonInternalstorage,allyouneedtodoisusethemethods:getFilesDir()andgetCacheDir()Thesemethodsreturntheabsolutepathstoyourapplication’sdedicateddirectorieswhichyoucanthenusetoopenanOutputStreamorInputStream.Fromthispointon,everythingissameasworkingwithfilesinJava.Forwriting/readingto/fromInternalstorage,nopermissionsarerequired.However,keepinmindthatthefilesyousavetoInternalstoragethoughsecureandinaccessibletootherapplications,areremovedassoonastheuseruninstallsyourapplication.DedicatedDirectoriesonExternalStorageThismightsoundabitconfusing,buttherearealsodedicateddirectoriesforyourapplicationsonExternalStorage.Thesedirectoriesarenotaccess-restrictedanddatayoustoreherecanbeeasilyreadbyotherapplications.Thesemightbehandyforstoringnon-sensitivehighvolumedata,butkeepinmindthatthedatacontainedinthesedirectoriesisalsoremovedoncetheuseruninstallsyourapplication.Thededicateddirectoriesforyourapplicationoninternalstorageandexternalstoragearetogethercalledapp-specificdirectories,andyoucanreadmoreaboutthemhere.Dropapersonalmessageinmyinboxforpointingoutinaccuracies,typosorforprovidingconstructivecriticism.ProAndroidDevThelatestpostsfromAndroidProfessionalsandGoogleDeveloperExpertsFollow1401AndroidAppDevelopmentAndroidAndroidExternalStorageAndroidInternalStorageAndroidDev140 claps1401WrittenbyHarshalDevFollowFollowProAndroidDevFollowThelatestpostsfromAndroidProfessionalsandGoogleDeveloperExperts.FollowWrittenbyHarshalDevFollowProAndroidDevFollowThelatestpostsfromAndroidProfessionalsandGoogleDeveloperExperts.MoreFromMediumMiningFanficsonAO3 — Part1:DataCollectionSophiaZ.inNerdForTechTurninganArduinointoaproductivitybehemothTettraCoinsDockerimagetobuildK8sstackinGCPcloudRafaelDalsenterinFAUNPublicationFunctionalProgrammingintheRealWorldAnuZachariahinGridSolutionsCASESTUDY:PortfolioCloudBuyVersusBuild:TipsforEstablishingaCommonDataModel — RTInsightsRTInsightsTeaminRTInsightsAboutWatsonAssistantIntegrationsAdolfoCruzActivateyourcondaenvironment&openingyourJupyternotebookinabashscriptCameliaD.Brumar



請為這篇文章評分?