Android Storage & Scoped Storage. Part-1 File storage basics

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

If internal storage doesn't provide enough space to store app-specific files, android provides external storage for an app to access its directories. GetstartedOpeninappKalaiselvanSigninGetstarted32FollowersAboutGetstartedOpeninappAndroidStorage&ScopedStoragePart-1FilestoragebasicsKalaiselvanJun19,2020·3minreadOverviewAndroidisbringinginlotofimprovementsinaccessingthedevicestorageforRead/Writeoperations.It’sallstartedwhenitintroducedruntimePermissions,whereanappmustaskforuser’spermissionsforaccessinganykindofsharedstoragedatainthedevice.Fromthenonandroidimposeslotofstrictmeasuresinaccessingthedatafromthedeviceonlyiftheappreallyneedsthosedataforperformingitswork.Storageinandroidsystemisclassifiedasfollows:App-specificstorageSharedstoragePreferencesDatabaseTounderstandthereasonforintroducingscopedstorageinandroid,weneedtohavesomebasicunderstandingofhowmediafilesanddocumentsareaccessed,editedorstoredintheinternalorexternalstoragebyanappandthepermissionsprovidedtotheappforaccessingthesharedfilesinthedevice.ApplicationStorageAppstoragecanbeclassifiedinto:InternalStorage(Filessavedhereareprotectedandaccessibleonlytotheappwhichcreated/storedit)ExternalStorage(Sometimesthisisapartofandroiddevicestorage,SDcards,etc.,)Fileswhicharestoredininternalstoragecannotbeaccessedbytheotherapplications.Onlytheappwhichcreatedthosefilescanaccessit.Thisprovidesoneformofsecurityforanapptostoreitssensitivefiles.Filesthatwerestoredinexternalstorageareaccessibletootherappsaswellprovidedthoseappshavedeclaredproperstoragepermissions.Althoughit’spossibleforotherappstoaccessthosefiles,thefilesstoredinthesedirectoriesaremeantforuseonlybytheparticularapp.Ifanappwantstostoresfilesinexternalstoragewhereothersappsshouldaccessthosefilesfortheiroperationthenthosefilesshouldbestoredinthesharedstorage.OneexampleforthisparticularusecaseisCameraapplication.Filescreated/editedbythecameraappshouldbeaccessibletoGalleryapp,Filemanagerapp,etc.,App-specificdirectoriesinInternalStorageAndroidOSprovidesconsiderableamountofspaceininternalstoragefortheapptoaccessitsdirectories.Usuallythesedirectoriescanbecalledfromacontextobject,Apppersistentdirectoryvalfile=File(context.filesDir,filename)2.AppcachedirectoryvalcacheFile=File(context.cacheDir,filename)App-specificdirectoriesinExternalStorageIfinternalstoragedoesn’tprovideenoughspacetostoreapp-specificfiles,androidprovidesexternalstorageforanapptoaccessitsdirectories.Likeinternalstorageappspecificdirectories,thesedirectoriescanalsobecalledfromacontextobject,Apppersistentdirectoryvalfile=File(context.filesDir,filename)2.AppcachedirectoryvalcacheFile=File(context.cacheDir,filename)ChoosingStoragelocationSometimes,adevicethatallocatesapartitionofitsinternalmemoryasanexternalstoragemightalsoprovidesanSDcardslot.Thismakesthedevicestohaveaprovisionforholdingmultiplestoragevolumes.Hencetoaccessdifferentstoragevolumes,wehavetocallthisparticularfunction,valexternalStorageVolumes:Array=ContextCompat.getExternalFilesDirs(applicationContext,null)valprimaryExternalStorage=externalStorageVolumes[0]Asshowninthecodesnippet,thefirstelementinthereturnedarrayisconsideredastheprimaryexternalstoragevolumeallocatedbythedevice.StorageAvailabilityMostoftenexternalstoragemayalsoreferstotheexternallymounteddisk(SDcard).Henceitisimportanttoverifythatparticularvolumeisaccessibleornotbeforetryingtoreadapp-specificdatafrom,orwriteapp-specificdatato,externalstorage.//Checksifavolumecontainingexternalstorageisavailable//forreadandwrite.funisExternalStorageWritable():Boolean{returnEnvironment.getExternalStorageState()==Environment.MEDIA_MOUNTED}//Checksifavolumecontainingexternalstorageisavailabletoatleastread.funisExternalStorageReadable():Boolean{returnEnvironment.getExternalStorageState()insetOf(Environment.MEDIA_MOUNTED,Environment.MEDIA_MOUNTED_READ_ONLY)}QueryFreespaceManytimesdevicesdon’thavemuchstoragespaceavailablehenceforththeappshouldconsumespacethoughtfully.Wecanquerythefreespaceavailabilityusingthebelowsnippetandperforestorageoperations,//Appneeds10MBwithininternalstorage.constvalNUM_BYTES_NEEDED_FOR_MY_APP=1024*1024*10L;valstorageManager=applicationContext.getSystemService()!!valappSpecificInternalDirUuid:UUID=storageManager.getUuidForPath(filesDir)valavailableBytes:Long=storageManager.getAllocatableBytes(appSpecificInternalDirUuid)if(availableBytes>=NUM_BYTES_NEEDED_FOR_MY_APP){storageManager.allocateBytes(appSpecificInternalDirUuid,NUM_BYTES_NEEDED_FOR_MY_APP)}else{valstorageIntent=Intent().apply{action=ACTION_MANAGE_STORAGE}//Displayprompttouser,requestingthattheychoosefilestoremove.}InthePart2ofthisseries,let’sbuildanappandexperimentallthetopicswehavecovered.WealsolookintoFileProviderAPIandexperimentit.Cheers……🍺🍺🍺KalaiselvanMobileapplicationengineer|Androidtutor|AviationEnthusiastsFollow11111 111AndroidKotlinAndroidStorageMorefromKalaiselvanFollowMobileapplicationengineer|Androidtutor|AviationEnthusiastsMoreFromMediumHowtoBuildMoreAccessibleAppsforAndroidByteoutSoftwareSecondweekwithOpenMRSRishabhAgarwalWritingcustomlintinAndroid:TheultimateteacherAlokBhartiOculusQuest2developmentusingUnrealEngine.GettingStarted:KavanBahramiTheimportanceofUSBSuperSpeedforAndroidDevelopmentFabienSanglardinAndroidDevelopersHowtoMakeanAndroidCustomViewEngineBaiinEngineBaiGoogleAdaptsAndroidtoChromebooksIanWilliamsinCrosXpertsActivity,Fragment,ViewModelandtheGameofLife-cycleUtkarshSonpatki



請為這篇文章評分?