If internal storage doesn't provide enough space to store app-specific files, consider using external storage instead. The system provides directories within ...
Platform
AndroidStudio
GooglePlay
Jetpack
Kotlin
Docs
Games
Language
English
BahasaIndonesia
Español–AméricaLatina
Português–Brasil
中文–简体
日本語
한국어
Signin
Documentation
Overview
Guides
Reference
Samples
Design&Quality
Platform
AndroidStudio
GooglePlay
Jetpack
Kotlin
Docs
Overview
Guides
Reference
Samples
Design&Quality
Games
AppBasics
Introduction
BuildyourfirstappOverviewCreateanAndroidprojectRunyourappBuildasimpleuserinterfaceStartanotheractivity
Appfundamentals
AppresourcesOverviewHandleconfigurationchanges
LocalizationLocalizeyourappTestyourappwithpseudolocalesUnicodeandinternationalizationsupportLanguageandlocaleresolutionComplexXMLresources
ResourcetypesOverviewAnimationColorstatelistDrawableLayoutMenuStringStyleFontMoretypes
AppmanifestfileOverview
Devices
DevicecompatibilityOverviewScreencompatibilityoverviewSupportdifferentpixeldensitiesSupportdisplaycutoutsDeclarerestrictedscreensupport
MultipleAPKsupportOverviewCreatemultipleAPKsfordifferentAPIlevelsCreatemultipleAPKsfordifferentscreensizesCreatemultipleAPKsfordifferentGLtexturesCreatemultipleAPKswithseveraldimensionsSupportdifferentlanguagesandculturesSupportdifferentplatformversionsFiltersonGooglePlay
Tablets,largescreens,andfoldablesGetstartedwithlargescreens
BuildresponsiveUIsSupportdifferentscreensizesNavigationforresponsiveUIsMigrateyourUItoresponsivelayoutsActivityembeddingMulti-windowsupportInputcompatibilityonlargescreens
BuildforfoldablesLearnaboutfoldablesMakeyourappfoldawareTestyourapponfoldables
WearGetstartedPrinciplesofWearOSdevelopmentUpgradetothelatestversionofWearOSWearOSversusmobiledevelopmentSetupJetpackComposeonWearOSUseJetpackComposeonWearOSWearOSdeveloperpathwayOngoingActivitiesWearOSuserinterfaceTilesExposedatatocomplications
GettingstartedCreateandrunawearableappDebugaWearOSappCaptureWearUIscreenshotsAppearinRecentsandAppResume
OverlaysOverviewUsetheWearUIlibraryHandledifferentwatchshapesScreenoptionsCreatelistsNavigationExitfullscreenactivitiesonWearShowconfirmationsPlayingaudioonwearablesWetmodeKeepyourappvisibleonWearAuthenticationStandaloneapp
NotificationsNotificationsonWearOSBridgingoptionsfornotifications
HandlingdataSendandsyncdataonWearOSNetworkaccessandsynconWearOSAccesstheWearableDataLayerTransferassetsSendandreceivemessagesHandledatalayereventsSyncdataitemswiththeDataLayerAPIRequestpermissionsDetectlocation
UserinputPhysicalbuttonsRotaryinputCreateinputmethodeditorsinWearVoice
WatchFaceStudioWatchFaceStudioKeyboardshortcutsManageaWatchFaceStudioprojectCreateawatchfacewithWatchFaceStudioBuildcomplicationsinWatchFaceStudioTagexpressionsLanguagesettingsAlways-oninWatchFaceStudioGyroeffectsBuildanduploadfromWatchFaceStudioTestyourwatchfaceFAQ
HealthservicesOverviewActivedataandexercisePassivedataupdatesUsesyntheticdataprovidersHealthPlatformAPI
DesignIntroductionDesignprinciplesGettingstartedInteractiontypesNotificationsComplicationsTilesOverlaysOngoingactivitiesConfirmationoverlayDisconnectionindicatorsPermissionmessagesSelectioncontrolsLaunchandlatencyNavigationPermissionsSigninHardwarebuttonsColorTypographyIconsDownloads
ComponentsWearMaterialThemingButtonsChipsTogglechipsCardsListsCurvedtextsSwipetodismissScrollindicatorsPickersPageviewersSlidersProgressindicator
CreatingwatchfacesOverviewDesignwatchfacesBuildawatchfaceserviceDrawwatchfacesWatchfacecomplicationsAddingcomplicationstoawatchfaceCreatinginteractivewatchfacesProvideconfigurationactivitiesAddresscommonissuesImproveperformacewithhardwareaccelerationOptimizeperformanceandbatterylifeWearappqualityPackageWearOSappsDistributetoWearOSCreateWearOSappsforChinaWearOSreleasenotes
AndroidTVOverview
BuildTVAppsOverviewGetstartedwithTVappsAndroidXTVlibrariesHandleTVhardwareManageTVcontrollersBuildTVlayoutsOn-screenkeyboardCreateTVnavigationBestpracticesfordrivingengagementonGoogleTV
BuildTVplaybackappsOverviewCreateacatalogbrowserProvideacardviewBuildadetailsviewUseLeanbacktransportcontrolsPlaybackcontrolsonTVDisplayaNowPlayingcardAddaguidedstepIntroducefirst-timeuserstoyourappEnablebackgroundplaybackAudiocapabilitiesManageframerates
HelpusersfindcontentonTVOverview
RecommendTVcontentOverviewChannelsonthehomescreenVideoprogramattributesAudioprogramattributesGameprogramattributes
WatchNextAddprogramsAttributesGuidelinesforappdevelopersGuidelinesforTVprovidersPreviewvideosRecommendationsinAndroidNandearlierMakeTVappssearchableSearchwithinTVApps
BuildTVgamesOverviewUseStreamProtectforlatency-sensitivestreamingapps
BuildTVinputservicesOverviewDevelopaTVinputserviceWorkwithchanneldataManageTVuserinteractionSupporttime-shiftingSupportcontentrecordingTVAppschecklist
TVAccessibilityAccessibilitybestpracticesTalkBackevaluationexamplesAdoptsystemcaptionsettingsCustomviewaccessibilitysupportCustomviewaccessibilitysampleAndroid12DeveloperPreviewforTV
AndroidforCarsOverview
BuildmediaappsforcarsBuildmediaappsforcarsAddsupportforAndroidAutoAddsupportforAndroidAutomotiveOSBuildmessagingappsforAndroidAuto
Buildnavigation,parking,andchargingappsforcarsUsingtheAndroidforCarsAppLibraryBuildparkingandchargingappsforcarsBuildnavigationappsforcarsAddsupportforAndroidAutoTestAndroidappsforcarsGooglePlayservicesNotificationsonAndroidAutomotiveOS
AndroidThingsOverviewPlatformdifferencesGoogleservices
SupportedhardwareOverviewNXPi.MX7DRaspberryPi3
AdvancedsetupOverviewManuallyflashanimageRecoveradeviceConnectingtoWi-Fiwithadb
Buildapps
CreateaThingsappOverviewCreateaprojectConnectthehardwareInteractwithperipheralsIntegrateperipheraldrivers
CommunicatewithwirelessdevicesBluetoothLoWPAN
ConfiguredevicesSettingsUpdates
InteractwithperipheralsOverviewGPIOPWMI2CSPIUARTNativePIOCLItoolIntegratenativecode
Builduser-spacedriversOverviewLocationInputSensorsLoWPANSamples
ManagedevicesOverviewCreateaproductConfigureaproduct
CreateabuildOverviewManageapps
PushanupdateOverviewAutomaticupdatesMonitoranalytics
TermsConsoleTermsofServiceSDKLicenseAgreementAndroidThingsConsole
ChromeOSdevicesOverviewBuildingappsforChromeOSOptimizingAppsforChromeOSPreparingyourdevelopmentenvironmentAppManifestCompatibilityforChromebooksChromeOSDeviceSupportforAppsAppRenderingDifferencesonChromebooksWindowmanagementAdaptingGamesonChromeOSSmoothanimationonChromeOSTestCasesforAndroidAppsonChromeOS
Apparchitecture
Introduction
Guidetoapparchitecture
ArchitectureComponents
UIlayerlibraries
ViewbindingOverviewMigratefromKotlinsyntheticstoviewbinding
DatabindinglibraryOverviewGetstartedLayoutsandbindingexpressionsWorkwithobservabledataobjectsGeneratedbindingclassesBindingadaptersBindlayoutviewstoArchitectureComponentsTwo-waydatabinding
Lifecycle-awarecomponentsHandlelifecyclesViewModelLiveDataSaveUIstatesSavedStatemoduleforViewModelUseKotlincoroutineswithlifecycle-awarecomponents
PagingLibraryOverviewLoadanddisplaypageddataPagefromnetworkanddatabaseTransformdatastreamsManageandpresentloadingstatesTestyourPagingimplementationMigratetoPaging3
Paging2OverviewDisplaypagedlistsLoadpageddata
DatalayerlibrariesDataStore
WorkManagerOverviewGettingStarted
How-ToGuidesDefiningyourWorkRequestsWorkstatesManagingworkObservingintermediateWorkerprogressChainingworktogetherTestingWorkerimplementationIntegrationtestswithWorkManagerDebuggingWorkManager
AdvancedConceptsConfigurationandInitialization
ThreadinginWorkManagerOverviewThreadinginWorkerThreadinginCoroutineWorkerThreadinginRxWorkerThreadinginListenableWorkerSupportforlong-runningworkersMigratingfromFirebaseJobDispatcherMigratingfromGCMNetworkManager
Appentrypoints
ActivitiesIntroductiontoactivitiesTheactivitylifecycleActivitystatechangesTestyouractivitiesTasksandbackstackProcessesandapplifecycleParcelablesandbundlesLoadersRecentsscreenRestrictionsonstartingactivitiesfromthebackground
AppshortcutsOverviewCreateshortcutsAddcapabilitiesManageshortcutsBestpracticesforshortcuts
AppnavigationPrinciplesofnavigationDesignfordifferentformfactorsHandleconfigurationchanges
NavigationcomponentOverviewGettingstartedCreatedestinationsDesignnavigationgraphsNestedgraphsGlobalactionsNavigatetoadestinationConditionalnavigationPassdatabetweendestinationsCreateadeeplinkforadestinationAnimatetransitionsbetweendestinationsUpdateUIcomponentswithNavigationUIKotlinDSLInteractprogrammaticallyNavigatewithfeaturemodulesBestpracticesformulti-moduleprojectsTestnavigationAddnewdestinationtypesMigratetotheNavigationcomponent
FragmentsOverviewCreateafragmentFragmentmanagerFragmenttransactionsAnimatetransitionsbetweenfragmentsFragmentlifecycleSavingstatewithfragmentsCommunicatewithfragmentsWorkingwiththeappbarDisplayingdialogswithDialogFragmentDebugyourfragmentsTestyourfragments
ApplinksOverviewEnablinglinkstoappcontentVerifyapplinksCreateapplinksforinstantappsCreateswipeviewswithtabsusingViewPagerCreateswipeviewswithtabsusingViewPager2Providecustombacknavigation
DependencyinjectionOverviewManualdependencyinjectionDependencyinjectionwithHiltHiltinmulti-moduleappsHiltandJetpackintegrationsHilttestingguideHiltandDaggerannotationscheatsheet
DaggerDaggerbasicsUsingDaggerinAndroidappsUsingDaggerinmulti-moduleapps
AppStartup
Coretopics
AppcompatibilityOverviewCompatibilityframeworktoolsRestrictionsonnon-SDKinterfaces
InteractwithotherappsOverviewSendingtheusertoanotherappGettingaresultfromanactivityAllowingotherappstostartyouractivity
PackagevisibilityOverviewKnowwhichpackagesarevisibleautomaticallyDeclarepackagevisibilityneedsFulfillcommonusecasesTestpackagevisibility
IntentsandintentfiltersOverviewCommonintents
UserinterfaceOverview
LayoutsOverviewBuildaresponsiveUIwithConstraintLayout
AddmotiontoyourlayoutwithMotionLayoutOverviewCarouselwithMotionLayoutMotionLayoutexamples
MotionLayoutXMLreferenceOverviewCreatealistwithRecyclerViewAdvancedRecyclerViewcustomizationCreateacard-basedlayoutCreateatwopanelayout
ImprovinglayoutperformanceOverviewOptimizinglayouthierarchiesRe-usinglayoutswithDelayedloadingofviewsLinearlayoutAdapterviewRelativelayout
CustomviewcomponentsOverviewCreatingacustomviewclassImplementingcustomdrawingMakingtheviewinteractiveOptimizingtheviewDesigningforfoldables
LookandfeelMaterialdesignStylesandthemesDarkthemeRoundedcornersAdaptiveiconsAddafloatingactionbuttonCreateshadowsandclipviews
TextAutosizingTextViewsDownloadablefontsFontsinXML
EmojiSupportmodernemojiEmojicompatibilityMagnifierwidgetSpansButtonsCheckboxesRadiobuttonsTogglebuttonsSpinnersPickersTooltips
NotificationsOverviewCreateanotificationCreateanexpandablenotificationDisplaytime-sensitivenotificationsStartanactivityfromanotificationCreateagroupofnotificationsCreateandmanagenotificationchannelsModifyanotificationBadgeCreateacustomnotification
SplashscreensOverviewMigrateyourexistingsplashscreenConversationsBubbles
AddtheappbarOverviewSetuptheappbarAddandhandleactionsAddanupactionUseactionviewsandactionproviders
ControlthesystemUIvisibilityOverviewDimthesystembarsHidethestatusbarHidethenavigationbarEnablefullscreenmodeRespondtoUIvisibilitychanges
Supportingswipe-to-refreshOverviewAddingswipe-to-refreshtoyourappRespondingtoarefreshgestureToastsoverview
Pop-upmessagesoverviewOverviewBuildanddisplayapop-upmessageAddanactiontoamessageDialogsMenus
SettingsOverviewOrganizeyoursettingsCustomizeyoursettingsUsesavedvaluesBuildahierarchyincodeHandleotherformfactorsPreferencecomponentsandattributes
SearchOverviewCreatingasearchinterfaceAddingrecentquerysuggestionsAddingcustomsuggestionsSearchableconfiguration
AddingsearchfunctionalityOverviewSettingupthesearchinterfaceStoringandsearchingfordataRemainingbackwardcompatibleCopyandpasteDraganddropPicture-in-picturesupport
Creatingbackward-compatibleUIsOverviewAbstractingthenewAPIsProxyingtothenewAPIsCreatinganimplementationwitholderAPIsUsingtheversion-awarecomponentDevicecontrol
HomechannelsformobileappsOverviewMediaHomeBooksMediaHomeVideo
AppwidgetsOverviewCreateasimplewidgetEnhanceyourwidgetCreateanadvancedwidgetUsewidgetcollectionsProvideflexiblewidgetlayoutsEnablewidgetconfigurationBuildanappwidgethost
Animations&transitionsOverviewIntroductiontoanimationsPropertyanimationoverviewAnimatedrawablegraphicsRevealorhideaviewusinganimationMoveaviewusinganimationMoveaviewusingaflinganimationEnlargeaviewusingazoomanimationAnimatemovementusingspringphysicsAutoanimatelayoutupdatesAnimatelayoutchangesusingatransitionCreateacustomtransitionanimationStartanactivityusingananimationSlidebetweenfragmentsusingViewPagerSlidebetweenfragmentsusingViewPager2MigratefromViewPagertoViewPager2Additionalresources
Images&graphicsOverviewDrawablesoverviewVectordrawablesoverviewHandlingbitmapsSelectingcolorswiththepaletteAPIReducingimagedownloadsizesHardwareaccelerationOpenGLES
DisplayinggraphicswithOpenGLESOverviewBuildinganOpenGLESenvironmentDefiningshapesDrawingshapesApplyingprojectionandcameraviewsAddingmotionRespondingtotouchevents
RenderingOverviewReducingoverdrawPerformanceandviewhierarchiesAnalyzingwithprofileGPUrenderingEnhancinggraphicswithwidecolorcontent
Audio&videoAudio&videooverviewMediacontrolsSupportedmediaformatsMediacodecs
MediaapparchitectureMediaapparchitectureoverviewUsingamediasession
BuildinganaudioappAudioappoverviewBuildingamediabrowserserviceBuildingamediabrowserclientMediasessioncallbacksUsingthemediacontrollertestapp
BuildingavideoappVideoappoverviewBuildingavideoplayeractivityMediasessioncallbacksCompatiblemediatranscodingRespondingtomediabuttonsHandlingchangesinaudiooutputManageaudiofocus
TheGoogleAssistantTheGoogleAssistantandmediaappsMediaappsonGoogleAssistantdrivingmode
RoutingbetweendevicesRoutingoverviewMediaRouteroverviewMediaRouteProvideroverviewControlamplitudewithVolumeShaperMediaPlayeroverviewMediaRecorderoverviewExoPlayerSharingaudioinputCapturevideoandaudioplaybackFramerateBestpracticesforsharingvideoAdditionalResourcesforMedia
ServicesOverviewForegroundservicesBoundservicesAIDLoverview
BackgroundtasksOverviewBackgroundthreadsBackgroundoptimizations
BroadcastsOverviewImplicitBroadcastExceptions
ManagedeviceawakestateOverviewKeepthedeviceawakeSchedulealarms
PermissionsOverviewEvaluatewhetheryourappneedspermissionsDeclareapppermissionsRequestapppermissionsExplainaccesstomoresensitiveinformationApppermissionsbestpracticesPermissionsusedonlyindefaulthandlersRestrictinteractionswithotherappsDefinecustompermissions
Appdata&filesOverviewStorageoverviewSavetoapp-specificstorage
SavetosharedstorageOverviewMediaDocumentsandotherfilesDatasetsManageallfilesonastoragedeviceSavekey-valuedata
SavedatainalocaldatabaseOverviewDefinedatausingentitiesAccessdatausingDAOsDefinerelationshipsbetweenobjectsWriteasynchronousDAOqueriesCreateviewsintoadatabasePrepopulateyourdatabaseMigrateyourdatabaseTestanddebugyourdatabaseReferencecomplexdataMigratefromSQLitetoRoomSavedatausingSQLiteStorageusecasesandbestpractices
SharingsimpledataOverviewSendingsimpledatatootherappsReceivingsimpledatafromotherapps
SharingfilesOverviewSettingupfilesharingSharingafileRequestingasharedfileRetrievingfileinformation
SharingfileswithNFCOverviewSendingfilestoanotherdeviceReceivingfilesfromanotherdevice
PrintingfilesOverviewPrintingphotosPrintingHTMLdocumentsPrintingcustomdocuments
ContentprovidersOverviewContentproviderbasicsCreatingacontentproviderOpenfilesusingstorageaccessframeworkCreateacustomdocumentproviderAppinstalllocation
Userdata&identityOverviewAddsign-inworkflowShowabiometricauthenticationdialog
AutofillframeworkOverviewOptimizeyourappforautofillBuildautofillservicesIntegrateautofillwithkeyboardsIdentifydeveloper-ownedappsReviewhowyourappcollectsandsharesuserdataAuditdataaccessGetauser-resettableadvertisingIDCalendarprovideroverview
ContactsproviderOverviewRetrievingalistofcontactsRetrievingdetailsforacontactModifyingcontactsusingintentsDisplayingthequickcontactbadgeAccounttransfer
DatabackupOverviewBackupuserdataBackupkey-valuepairsTestbackupandrestoreBestpracticesforuniqueidentifiers
RememberandauthenticateusersOverviewRememberyouruserAuthenticatetoOAuth2servicesCreateacustomaccounttype
UserlocationOverviewRequestlocationpermissionsGetthelastknownlocationChangelocationsettingsRequestlocationupdatesAccesslocationinthebackgroundCreateandmonitorgeofencesDetectwhenusersstartanactivityOptimizelocationforbatteryTestlocationworkflowsMigratetolocationandcontextAPIsAddmaps
Touch&inputOverviewInputevents
UsingtouchgesturesOverviewDetectcommongesturesTracktouchandpointermovementsAnimateascrollgestureSupportnavigationgesturesImplementedge-to-edgeHandlemulti-touchgesturesDragandscaleManagetoucheventsinaViewGroup
HandlingkeyboardinputOverviewSpecifyingtheinputmethodtypeHandlinginputmethodvisibilitySupportingkeyboardnavigationHandlingkeyboardactions
SupportinggamecontrollersOverviewHandlingcontrolleractionsSupportingcontrollersacrossAndroidversionsSupportingmultiplegamecontrollers
InputmethodeditorsCreatinganinputmethodImagekeyboardReceiverichcontentSpellingchecker
CameraXOverviewCameraXarchitectureConfigurationPreviewImageanalysisImagecaptureVideocaptureExtensionsAPITransformoutputUsecaserotationsCameraXdevices
Camera2OverviewCameracapturesessionsandrequestsCameraenumerationUsemultiplecamerastreamssimultaneouslyCamerapreviewonlargescreensMulti-CameraAPIExtensionsAPI
CameraOverviewTakingphotosRecordingvideosControllingthecameraCameraAPI
SensorsOverviewSensorsoverviewMotionsensorsPositionsensorsEnvironmentsensorsRawGNSSmeasurements
ConnectivityOverview
PerformingnetworkoperationsOverviewConnecttothenetworkManagenetworkusageReadingnetworkstateOptimizenetworkdatausageParseXMLdata
TransmitnetworkdatausingVolleyOverviewSendasimplerequestSetupRequestQueueMakeastandardrequestImplementacustomrequest
PerformnetworkoperationsusingCronetOverviewSendasimplerequestCronetrequestlifecycle
Reference
org.chromium.netOverviewCallbackException
CronetEngineOverview
CronetEngine.BuilderOverviewLibraryLoaderCronetExceptionInlineExecutionProhibitedExceptionNetworkExceptionQuicExceptionUploadDataProviderUploadDataProvidersUploadDataSink
UrlRequestOverviewBuilderCallbackStatusStatusListener
UrlResponseInfoOverviewHeaderBlockEnhanceyourappswith5GBuildclient-serverapplicationswithgRPC
TransferringdatawithoutdrainingthebatteryOverviewOptimizedownloadsforefficientnetworkaccessMinimizetheeffectofregularupdatesAvoidredundantdownloadsModifypatternsbasedontheconnectivitytype
ReducenetworkbatterydrainOverviewCollectingnetworktrafficdataAnalyzingdatatrafficOptimizeuser-initiatednetworkuseOptimizeapp-initiatednetworkuseOptimizeserver-initiatednetworkuseOptimizinggeneralnetworkuse
TransferdatausingSyncAdaptersOverviewCreateaStubAuthenticatorCreateaStubContentProviderCreateaSyncAdapterRunaSyncAdapter
BluetoothOverviewSetupBluetoothFindBluetoothdevicesConnectBluetoothdevicesTransferBluetoothdataBluetoothpermissionsBluetoothprofilesCompaniondevicepairing
BluetoothLowEnergyOverviewFindBLEdevicesConnecttoaGATTserverTransferBLEdata
NFCOverviewNFCbasicsAdvancedNFCHost-basedcardemulationoverview
TelecomOverviewBuildacallingappPreventcallerIDspoofingTelephonyIDs
Wi-FiWi-FiscanningoverviewWi-Fipeer-to-peerWi-FiAwareoverviewWi-FilocationwithRTTLocalOnlyHotspot
Wi-FiinfrastructureWi-FiinfrastructureoverviewWi-FisuggestionAPIforinternetconnectivityWi-FiNetworkRequestAPIforpeer-to-peerconnectivityPasspointSavenetworksandPasspointconfigurations
USBOverviewAccessoryoverviewHostoverviewVPNSessioninitiationprotocoloverview
DiscoverandconnectOverviewUsenetworkservicediscoveryCreateP2PconnectionswithWi-FiUseWi-FiP2PforservicediscoveryWi-FiEasyConnectOpenMobileAPIreadersupport
RenderscriptOverviewAdvancedRenderScriptMigratefromRenderScript
RuntimeAPIreferenceOverviewNumericaltypesObjecttypesConversionfunctionsMathematicalconstantsandfunctionsVectormathfunctionsMatrixfunctionsQuaternionfunctionsAtomicupdatefunctionsTimefunctionsandtypesAllocationdataaccessfunctionsObjectcharacteristicsfunctionsKernelinvocationfunctionsandtypesInput/outputfunctionsDebuggingfunctionsGraphicsfunctionsandtypesIndex
Web-basedcontentOverviewBuildingwebappsinWebViewManagingWebViewobjectsLoadlocalcontentDarkenwebcontentUserprivacyinWebViewcrashreportingMigratingtoWebViewinAndroid4.4SupportingdifferentscreensinwebappsDebuggingwebappsBestpracticesforwebapps
AndroidAppBundlesOverviewConfigurethebasemoduleBuildandtestyourappbundleAddcodetransparencyTheappbundleformatFrequentlyaskedquestions
GooglePlayGooglePlayBillingPlayCoreLibrary
PlayAssetDeliveryOverviewIntegrateassetdelivery(Kotlin&Java)Integrateassetdelivery(native)Integrateassetdelivery(Unity)TargettexturecompressionformatsTestassetdelivery
PlayFeatureDeliveryOverviewConfigureinstall-timedeliveryConfigureconditionaldeliveryConfigureon-demanddeliveryOn-demanddeliverybestpracticesConfigureinstantdeliveryAdditionalresources
In-appreviewsOverviewIntegrateusingKotlinorJavaIntegrateusingnativecodeIntegrateusingUnityTestin-appreviews
In-appupdatesOverviewSupportin-appupdates(KotlinorJava)Supportin-appupdates(Native)Supportin-appupdates(Unity)Testin-appupdates
GooglePlayInstantOverviewofGooglePlayInstant
GetstartedwithinstantappsCreateaninstant-enabledappbundleUXbestpracticesforapps
GetstartedwithinstantgamesOverviewUnitypluginUXbestpracticesforgamesMigratetoAndroidAppBundlesImplementclouddeliveryofassetsSupportGooglePlayGamesServicesInstantPlaygamesInstantPlaygameschecklistReducethesizeofyourinstantapporgameAddadstoyourinstantapporgameProvidemultipleentrypoints
IntegratewithFirebaseAddGoogleAnalyticsforFirebasetoyourinstantappUseFirebaseDynamicLinkswithinstantappsTechnicalrequirementschecklistGooglePlayInstantpolicy
ResourcesReferenceCodesamplesSDKreleasenotesInstantAppIntents
SupportKnownissuesStackOverflowPlayDeveloperAPI
PlayInstallReferrerOverview
PlayInstallReferrerLibraryOverviewReferenceReleasenotesPlayInstallReferrerAPIPlayIntegrityAPI
ApplicationLicensingOverviewLicensingOverviewSettingUpforLicensingAddingServer-SideVerificationAddingClient-SideVerificationLicensingReferenceAPKExpansionFiles
AppActions
SlicesOverviewGettingStartedSlicetemplates
On-devicesearch
Games
ToolsAndroidStudio
AndroidGameDevelopmentExtensionforVisualStudioOverviewQuickstartConfigureaprojectDebuggerMeasureappperformanceSamplesReleasenotesAndroidNDK
AndroidGPUInspectorOverviewQuickstart
SystemprofilingOverviewViewasystemprofile
AnalyzeasystemprofileFrameprocessingtimesMemoryefficiencyTexturememorybandwidthusageVertexmemorybandwidthusageThreadscheduling
GPUperformancecountersArmMaliQualcommAdrenoImaginationPowerVR
FrameprofilingOverview
AnalyzeaframeprofileMostexpensiverenderpassesVertexformatsShaderperformance
FrameProfilerUIPerformancepaneCommandspaneFramebufferpaneGeometrypaneReportpaneShaderpaneMemorypaneStatepaneTexturespaneTexturepanePipelineviewpaneSupportedVulkanextensionsTroubleshoot
CustomizeorportgameenginesOverview
GettingstartedIntegrateGameActivityConfiguregraphicsUnderstandAndroidgameloops
ProcessinputeventsAddtouchsupportSupporttextinput
SupportgamecontrollersOverviewUsethegamecontrollerlibraryUsecustomcontrollerdevicemappingsAddmousesupportSupportsensorinput
AchieveproperframepacingOverview
FramepacinginOpenGLESIntegrateUpdateyourbuildsettingsAddframepacingfunctionsVerifyframepacingimprovement
FramepacinginVulkanIntegrateUpdateyourbuildsettingsAddframepacingfunctionsVerifyframepacingimprovementReference
IntegrateAndroidPerformanceTunerOverviewRunthedemoappEnabletheAPIUpdateyourbuildsettingsDefineannotations,fidelityparameters,andsettingsAddframetimingfunctionsAddloadingtimerecordingfunctionsValidate,package,andpublishtheAPKTroubleshootcommonerrorsAdvancedusageReference
OutputaudioOverviewUpdatebuildsettingsUseOboeCodesamplesFullOboeguide
ManagememoryOverviewDebugnativememoryuseDeliverassetsDetectanddiagnosecrashes
UseprebuiltorturnkeygameenginesOverview
DevelopwithDefoldInstallandconfigureprojectsforAndroidSupportmultipleformfactorsandscreensizesExporttoAndroid
DevelopwithGodotInstallandconfigureprojectsforAndroidGodotrendereroptionsSupportmultipleformfactorsandscreensizesExporttoAndroid
DevelopwithUnityOverviewCreateanAndroidAppBundlewithUnityIntegratePlayAssetDeliveryUnityLightinginMobileGames
UseAndroidPerformanceTunerOverviewEnabletheAPIIntegratethepluginInitializethelibraryandverifyoperationDefineannotations,fidelityparameters,andqualitylevelsAddloadingtimerecordingfunctionsRunthemonitorappReviewandpublishTroubleshootcommonerrorsReferenceDevelopwithUnrealRequestinguserpermissionsSecureyourgame
Gamebestpractices
MaximizedeviceavailabilitySupport64-bitarchitecturesDevelopgamesforallscreensSign-in,savegames,andmorewithPlayGamesServices
ArtassetsGeometrybestpractices
OpenGLandVulkanDeviceorientationefficientlyinVulkanVertexdatamanagement
GameModeOverviewOptimizewithGameModeAPIGameModeinterventions
OptimizeCPU,memory,andgraphicstoolsAndroidPerformanceTuner
GuidesImprovegameperformanceReducegamesize
DistributeOverviewReleasewithGooglePlayInstantPlayasyoudownload
Bestpractices
TestingOverviewFundamentalsoftestingSetupproject
BuildingeffectiveunittestsOverviewBuildinglocalunittestsBuildinginstrumentedunittests
AutomatingUItestsOverviewTestingUIforasingleappTestingUIformultipleapps
TestingappcomponentintegrationsOverviewTestingyourserviceTestingyourcontentproviderTestingUIperformance
EspressoOverviewSetupinstructionsBasicsRecipesMultiprocessAccessibilitycheckingListsIntentsWebIdlingresourceCheatsheetAdditionalresourcesUIAutomatorAppCrawlerJUnit4RulesAndroidJUnitRunnerReleasenotesAdditionalresources
PerformanceOverviewPerformanceclass
AndroidVitalsOverviewStuckPartialWakeLocksExcessiveWakeupsExcessiveBackgroundWi-FiScansExcessiveBackgroundNetworkUsageANRsCrashesSlowRenderingFrozenFramesPermissionDenialsAppStartupTimeAppStandbyBucketsAppHibernationProcessesandThreadsOverviewBetterPerformancethroughThreading
OptimizingforBatteryLifeOverviewOptimizeforDozeandAppStandbyMonitorthebatterylevelandchargingstateMonitorconnectivitystatusandconnectionmeteringDetermineandmonitorthedockingstateandtypePowermanagementrestrictionsProfilebatteryusagewithBatterystatsandBatteryHistorianAnalyzepowerusewithBatteryHistorianTestingpower-relatedissuesReduceyourappsize
ManagememoryOverviewofMemoryManagemementMemoryAllocationamongProcessesManageYourApp'sMemory
SystemtracingOverviewCaptureatracefromthecommandlineCaptureatraceonadeviceNavigateareportDefinecustomeventsCustomtraceeventsinnativecodeInspectGPUrenderingDesigningforSeamlessnessKeepingYourAppResponsivePerformanceTipsSMPPrimerforAndroidVerifyingAppBehaviorontheAndroidRuntime(ART)
AccessibilityOverview
BuildandtestappsforaccessibilityMakeappsmoreaccessiblePrinciplesforimprovingappaccessibilityTestyourapp'saccessibility
AdvancedtopicsMakecustomviewsmoreaccessibleCreateyourownaccessibilityserviceAdditionalresources
PrivacyPrivacybestpractices
SecurityAppsecuritybestpracticesSecuritytipsSecuritywithdataSecuritywithdataacrossadditionalAndroidversionsSecuritywithHTTPSandSSLNetworksecurityconfigurationUpdatingyoursecurityprovidertoprotectagainstSSLexploits
ProtectingagainstsecuritythreatswithSafetyNetOverviewSafetyNetAttestationAPISafetyNetSafeBrowsingAPISafetyNetreCAPTCHAAPISafetyNetVerifyAppsAPICryptographyAndroidKeystoreSystemVerifyinghardware-backedkeypairswithkeyattestationAndroidProtectedConfirmationSupportingDirectBootRunningembeddedDEXcodeAppsecurityimprovementprogram
BuildforBillionsOverviewConnectivityDevicecapabilityDatacostBatteryconsumptionUIandcontent
BuildforEnterpriseOverviewDeveloperguideWorkprofilesSetupmanagedconfigurations
AppfeedbackSendappfeedbacktoEMMsTestappfeedbackWorkcontactsDevicemanagementpolicies
DevicemanagementOverviewBuildadevicepolicycontroller
DedicateddevicesOverviewLocktaskmodeMultipleusersCookbookDevicecontrolNetworkingandtelephonySecuritySystemupdatesNetworkactivitylogging
AndroidversionsOverviewAndroid12Android11Android10Android9Android8.0Android7.0Deviceadministration
AndroidDevelopers
Docs
Guides
Accessapp-specificfiles
Inmanycases,yourappcreatesfilesthatotherappsdon'tneedtoaccess,or
shouldn'taccess.Thesystemprovidesthefollowinglocationsforstoringsuch
app-specificfiles:
Internalstoragedirectories:Thesedirectoriesincludebothadedicated
locationforstoringpersistentfiles,andanotherlocationforstoring
cachedata.Thesystempreventsotherappsfromaccessingtheselocations,and
onAndroid 10(APIlevel29)andhigher,theselocationsareencrypted.These
characteristicsmaketheselocationsagoodplacetostoresensitivedatathat
onlyyourappitselfcanaccess.
Externalstoragedirectories:Thesedirectoriesincludebothadedicated
locationforstoringpersistentfiles,andanotherlocationforstoring
cachedata.Althoughit'spossibleforanotherapptoaccessthesedirectories
ifthatapphastheproperpermissions,thefilesstoredinthesedirectories
aremeantforuseonlybyyourapp.Ifyouspecificallyintendtocreatefiles
thatotherappsshouldbeabletoaccess,yourappshouldstorethesefilesin
thesharedstoragepartofexternalstorage
instead.
Whentheuseruninstallsyourapp,thefilessavedinapp-specificstorageare
removed.Becauseofthisbehavior,youshouldn'tusethisstoragetosave
anythingthattheuserexpectstopersistindependentlyofyourapp.For
example,ifyourappallowsuserstocapturephotos,theuserwouldexpectthat
theycanaccessthosephotosevenaftertheyuninstallyourapp.Soyoushould
insteadusesharedstoragetosavethosetypesoffilestotheappropriate
mediacollection.
Note:Tofurtherprotectapp-specificfiles,usetheSecurity
librarythat'spartofAndroid
Jetpacktoencryptthesefilesatrest.Theencryptionkeyis
specifictoyourapp.
Thefollowingsectionsdescribehowtostoreandaccessfileswithin
app-specificdirectories.
Accessfrominternalstorage
Foreachapp,thesystemprovidesdirectorieswithininternalstoragewherean
appcanorganizeitsfiles.Onedirectoryisdesignedforyourapp's
persistentfiles,andanothercontainsyourapp's
cachedfiles.Yourappdoesn'trequireanysystem
permissionstoreadandwritetofilesinthesedirectories.
Otherappscannotaccessfilesstoredwithininternalstorage.Thismakes
internalstorageagoodplaceforappdatathatotherappsshouldn'taccess.
Keepinmind,however,thatthesedirectoriestendtobesmall.Beforewriting
app-specificfilestointernalstorage,yourappshouldquerythefree
spaceonthedevice.
Accesspersistentfiles
Yourapp'sordinary,persistentfilesresideinadirectorythatyoucan
accessusingthefilesDir
propertyofacontextobject.Theframeworkprovidesseveralmethodstohelpyou
accessandstorefilesinthisdirectory.
Accessandstorefiles
YoucanusetheFileAPItoaccessandstorefiles.
Tohelpmaintainyourapp'sperformance,don'topenandclosethesame
filemultipletimes.
ThefollowingcodesnippetdemonstrateshowtousetheFileAPI:
Kotlin
valfile=File(context.filesDir,filename)
Java
Filefile=newFile(context.getFilesDir(),filename);
Storeafileusingastream
AsanalternativetousingtheFileAPI,youcancall
openFileOutput()
togetaFileOutputStreamthatwrites
toafilewithinthefilesDirdirectory.
Thefollowingcodesnippetshowshowtowritesometexttoafile:
Kotlin
valfilename="myfile"
valfileContents="Helloworld!"
context.openFileOutput(filename,Context.MODE_PRIVATE).use{
it.write(fileContents.toByteArray())
}
Java
Stringfilename="myfile";
StringfileContents="Helloworld!";
try(FileOutputStreamfos=context.openFileOutput(filename,Context.MODE_PRIVATE)){
fos.write(fileContents.toByteArray());
}
Caution:OndevicesthatrunAndroid7.0(APIlevel24)orhigher,unlessyou
passtheContext.MODE_PRIVATEfilemodeintoopenFileOutput(),a
SecurityExceptionoccurs.
Toallowotherappstoaccessfilesstoredin
thisdirectorywithininternalstorage,usea
FileProviderwiththe
FLAG_GRANT_READ_URI_PERMISSION
attribute.
Accessafileusingastream
Toreadafileasastream,use
openFileInput():
Kotlin
context.openFileInput(filename).bufferedReader().useLines{lines->
lines.fold(""){some,text->
"$some\n$text"
}
}
Java
FileInputStreamfis=context.openFileInput(filename);
InputStreamReaderinputStreamReader=
newInputStreamReader(fis,StandardCharsets.UTF_8);
StringBuilderstringBuilder=newStringBuilder();
try(BufferedReaderreader=newBufferedReader(inputStreamReader)){
Stringline=reader.readLine();
while(line!=null){
stringBuilder.append(line).append('\n');
line=reader.readLine();
}
}catch(IOExceptione){
//Erroroccurredwhenopeningrawfileforreading.
}finally{
Stringcontents=stringBuilder.toString();
}
Note:Ifyouneedtoaccessafileasastreamatinstalltime,savethefilein
yourproject's/res/rawdirectory.Youcanopenthesefileswith
openRawResource(),
passinginthefilenameprefixedwithR.rawastheresourceID.Thismethod
returnsanInputStreamthatyoucanuseto
readthefile.Youcannotwritetotheoriginalfile.
Viewlistoffiles
YoucangetanarraycontainingthenamesofallfileswithinthefilesDir
directorybycalling
fileList(),asshownin
thefollowingcodesnippet:
Kotlin
varfiles:Array=context.fileList()
Java
Arrayfiles=context.fileList();
Createnesteddirectories
Youcanalsocreatenesteddirectories,oropenaninnerdirectory,bycalling
getDir()inKotlin-based
codeorbypassingtherootdirectoryandanewdirectorynameintoaFile
constructorinJava-basedcode:
Kotlin
context.getDir(dirName,Context.MODE_PRIVATE)
Java
Filedirectory=context.getFilesDir();
Filefile=newFile(directory,filename);
Note:filesDirisalwaysanancestordirectoryofthisnewdirectory.
Createcachefiles
Ifyouneedtostoresensitivedataonlytemporarily,youshouldusetheapp's
designatedcachedirectorywithininternalstoragetosavethedata.Asisthe
caseforallapp-specificstorage,thefilesstoredinthisdirectoryare
removedwhentheuseruninstallsyourapp,althoughthefilesinthisdirectory
mightberemovedsooner.
Note:Thiscachedirectoryisdesignedtostoreasmallamountofyourapp's
sensitivedata.Todeterminehowmuchcachespaceiscurrentlyavailablefor
yourapp,call
getCacheQuotaBytes().
Tocreateacachedfile,call
File.createTempFile():
Kotlin
File.createTempFile(filename,null,context.cacheDir)
Java
File.createTempFile(filename,null,context.getCacheDir());
Yourappaccessesafileinthisdirectoryusingthe
cacheDirpropertyofa
contextobjectandtheFileAPI:
Kotlin
valcacheFile=File(context.cacheDir,filename)
Java
FilecacheFile=newFile(context.getCacheDir(),filename);
Caution:Whenthedeviceislowoninternalstoragespace,Androidmaydelete
thesecachefilestorecoverspace.Socheckfortheexistenceofyourcache
filesbeforereadingthem.
Removecachefiles
EventhoughAndroidsometimesdeletescachefilesonitsown,youshouldn'trely
onthesystemtocleanupthesefilesforyou.Youshouldalwaysmaintainyour
app'scachefileswithininternalstorage.
Toremoveafilefromthecachedirectorywithininternalstorage,useoneof
thefollowingmethods:
Thedelete()methodonaFileobject
thatrepresentsthefile:
Kotlin
cacheFile.delete()
Java
cacheFile.delete();
The
deleteFile()
methodoftheapp'scontext,passinginthenameofthefile:
Kotlin
context.deleteFile(cacheFileName)
Java
context.deleteFile(cacheFileName);
Accessfromexternalstorage
Ifinternalstoragedoesn'tprovideenoughspacetostoreapp-specificfiles,
considerusingexternalstorageinstead.Thesystemprovidesdirectorieswithin
externalstoragewhereanappcanorganizefilesthatprovidevaluetotheuser
onlywithinyourapp.Onedirectoryisdesignedforyourapp'spersistent
files,andanothercontainsyourapp'scached
files.
OnAndroid4.4(APIlevel19)orhigher,yourappdoesn'tneedtorequestany
storage-relatedpermissionstoaccessapp-specificdirectorieswithinexternal
storage.Thefilesstoredinthesedirectoriesareremovedwhenyourappis
uninstalled.
Caution:Thefilesinthesedirectoriesaren'tguaranteedtobeaccessible,such
aswhenaremovableSDcardistakenoutofthedevice.Ifyourapp's
functionalitydependsonthesefiles,youshouldinsteadstorethefileswithin
internalstorage.
OndevicesthatrunAndroid9(APIlevel28)orlower,yourappcanaccessthe
app-specificfilesthatbelongtootherapps,providedthatyourapphasthe
appropriatestoragepermissions.Togiveusersmorecontrolovertheirfilesand
tolimitfileclutter,appsthattargetAndroid 10(APIlevel29)andhigheraregiven
scopedaccessintoexternalstorage,orscoped
storage,bydefault.Whenscoped
storageisenabled,appscannotaccesstheapp-specificdirectoriesthatbelong
tootherapps.
Verifythatstorageisavailable
Becauseexternalstorageresidesonaphysicalvolumethattheusermightbe
abletoremove,verifythatthevolumeisaccessiblebeforetryingtoread
app-specificdatafrom,orwriteapp-specificdatato,externalstorage.
Youcanquerythevolume'sstatebycalling
Environment.getExternalStorageState().
Ifthereturnedstateis
MEDIA_MOUNTED,then
youcanreadandwriteapp-specificfileswithinexternalstorage.Ifit's
MEDIA_MOUNTED_READ_ONLY,
youcanonlyreadthesefiles.
Forexample,thefollowingmethodsareusefultodeterminethestorage
availability:
Kotlin
//Checksifavolumecontainingexternalstorageisavailable
//forreadandwrite.
funisExternalStorageWritable():Boolean{
returnEnvironment.getExternalStorageState()==Environment.MEDIA_MOUNTED
}
//Checksifavolumecontainingexternalstorageisavailabletoatleastread.
funisExternalStorageReadable():Boolean{
returnEnvironment.getExternalStorageState()in
setOf(Environment.MEDIA_MOUNTED,Environment.MEDIA_MOUNTED_READ_ONLY)
}
Java
//Checksifavolumecontainingexternalstorageisavailable
//forreadandwrite.
privatebooleanisExternalStorageWritable(){
returnEnvironment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
//Checksifavolumecontainingexternalstorageisavailabletoatleastread.
privatebooleanisExternalStorageReadable(){
returnEnvironment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)||
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
Ondeviceswithoutremovableexternalstorage,usethefollowingcommandto
enableavirtualvolumefortestingyourexternalstorageavailabilitylogic:
adbshellsmset-virtual-disktrue
Selectaphysicalstoragelocation
Sometimes,adevicethatallocatesapartitionofitsinternalmemoryas
externalstoragealsoprovidesanSDcardslot.Thismeansthatthedevicehas
multiplephysicalvolumesthatcouldcontainexternalstorage,soyouneedto
selectwhichonetouseforyourapp-specificstorage.
Toaccessthedifferentlocations,call
ContextCompat.getExternalFilesDirs().
Asshowninthecodesnippet,thefirstelementinthereturnedarrayis
consideredtheprimaryexternalstoragevolume.Usethisvolumeunlessit'sfull
orunavailable.
Kotlin
valexternalStorageVolumes:Array=
ContextCompat.getExternalFilesDirs(applicationContext,null)
valprimaryExternalStorage=externalStorageVolumes[0]
Java
File[]externalStorageVolumes=
ContextCompat.getExternalFilesDirs(getApplicationContext(),null);
FileprimaryExternalStorage=externalStorageVolumes[0];
Note:IfyourappisusedonadevicethatrunsAndroid4.3(APIlevel18)or
lower,thenthearraycontainsjustoneelement,whichrepresentstheprimary
externalstoragevolume.
Accesspersistentfiles
Toaccessapp-specificfilesfromexternalstorage,call
getExternalFilesDir().
Tohelpmaintainyourapp'sperformance,don'topenandclosethesame
filemultipletimes.
ThefollowingcodesnippetdemonstrateshowtocallgetExternalFilesDir():
Kotlin
valappSpecificExternalDir=File(context.getExternalFilesDir(null),filename)
Java
FileappSpecificExternalDir=newFile(context.getExternalFilesDir(null),filename);
Note:OnAndroid11(APIlevel30)andhigher,appscannotcreatetheirown
app-specificdirectoryonexternalstorage.
Createcachefiles
Toaddanapp-specificfiletothecachewithinexternalstorage,geta
referencetothe
externalCacheDir:
Kotlin
valexternalCacheFile=File(context.externalCacheDir,filename)
Java
FileexternalCacheFile=newFile(context.getExternalCacheDir(),filename);
Removecachefiles
Toremoveafilefromtheexternalcachedirectory,usethe
delete()methodonaFileobjectthat
representsthefile:
Kotlin
externalCacheFile.delete()
Java
externalCacheFile.delete();
Mediacontent
Ifyourappworkswithmediafilesthatprovidevaluetotheuseronlywithin
yourapp,it'sbesttostoretheminapp-specificdirectorieswithinexternal
storage,asdemonstratedinthefollowingcodesnippet:
Kotlin
fungetAppSpecificAlbumStorageDir(context:Context,albumName:String):File?{
//Getthepicturesdirectorythat'sinsidetheapp-specificdirectoryon
//externalstorage.
valfile=File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES),albumName)
if(!file?.mkdirs()){
Log.e(LOG_TAG,"Directorynotcreated")
}
returnfile
}
Java
@Nullable
FilegetAppSpecificAlbumStorageDir(Contextcontext,StringalbumName){
//Getthepicturesdirectorythat'sinsidetheapp-specificdirectoryon
//externalstorage.
Filefile=newFile(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES),albumName);
if(file==null||!file.mkdirs()){
Log.e(LOG_TAG,"Directorynotcreated");
}
returnfile;
}
It'simportantthatyouusedirectorynamesprovidedbyAPIconstantslike
DIRECTORY_PICTURES.
Thesedirectorynamesensurethatthefilesaretreatedproperlybythesystem.
Ifnoneofthepre-definedsub-directory
namessuityourfiles,youcan
insteadpassnullintogetExternalFilesDir().Thisreturnstheroot
app-specificdirectorywithinexternalstorage.
Queryfreespace
Manyusersdon'thavemuchstoragespaceavailableontheirdevices,soyourapp
shouldconsumespacethoughtfully.
Ifyouknowaheadoftimehowmuchdatayou'restoring,youcanfindouthow
muchspacethedevicecanprovideyourappbycalling
getAllocatableBytes().
ThereturnvalueofgetAllocatableBytes()mightbelargerthanthecurrent
amountoffreespaceonthedevice.Thisisbecausethesystemhasidentified
filesthatitcanremovefromotherapps'cachedirectories.
Ifthere'senoughspacetosaveyourapp'sdata,call
allocateBytes().
Otherwise,yourappcanrequesttheusertoremovesome
filesfromthedeviceorremoveallcache
filesfromthedevice.
Thefollowingcodesnippetshowsanexampleofhowyourappcanqueryfreespace
onthedevice:
Kotlin
//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{
//Torequestthattheuserremoveallappcachefilesinstead,set
//"action"toACTION_CLEAR_APP_CACHE.
action=ACTION_MANAGE_STORAGE
}
}
Java
//Appneeds10MBwithininternalstorage.
privatestaticfinallongNUM_BYTES_NEEDED_FOR_MY_APP=1024*1024*10L;
StorageManagerstorageManager=
getApplicationContext().getSystemService(StorageManager.class);
UUIDappSpecificInternalDirUuid=storageManager.getUuidForPath(getFilesDir());
longavailableBytes=
storageManager.getAllocatableBytes(appSpecificInternalDirUuid);
if(availableBytes>=NUM_BYTES_NEEDED_FOR_MY_APP){
storageManager.allocateBytes(
appSpecificInternalDirUuid,NUM_BYTES_NEEDED_FOR_MY_APP);
}else{
//Torequestthattheuserremoveallappcachefilesinstead,set
//"action"toACTION_CLEAR_APP_CACHE.
IntentstorageIntent=newIntent();
storageIntent.setAction(ACTION_MANAGE_STORAGE);
}
Note:Youaren'trequiredtochecktheamountofavailablespacebeforeyousave
yourfile.Youcaninsteadtrywritingthefilerightaway,thencatchan
IOExceptionifoneoccurs.Youmayneedto
dothisifyoudon'tknowexactlyhowmuchspaceyouneed.Forexample,ifyou
changethefile'sencodingbeforeyousaveitbyconvertingaPNGimagetoJPEG,
youdon'tknowthefile'ssizebeforehand.
Createastoragemanagementactivity
Yourappcandeclareandcreateacustomactivitythat,whenlaunched,allows
theusertomanagethedatathatyourapphasstoredontheuser'sdevice.You
declarethiscustom"managespace"activityusingthe
android:manageSpaceActivity
attributeinthemanifestfile.Filemanagerappscaninvokethis
activity
evenwhenyourappdoesn'texporttheactivity;thatis,whenyouractivitysets
android:exportedto
false.
Askusertoremovesomedevicefiles
Torequestthattheuserchoosefilesonthedevicetoremove,invokeanintent
thatincludesthe
ACTION_MANAGE_STORAGE
action.Thisintentdisplaysaprompttotheuser.Ifdesired,thispromptcan
showtheamountoffreespaceavailableonthedevice.Toshowthis
user-friendlyinformation,usetheresultofthefollowingcalculation:
StorageStatsManager.getFreeBytes()/StorageStatsManager.getTotalBytes()
Askusertoremoveallcachefiles
Alternatively,youcanrequestthattheuserclearthecachefilesfromall
appsonthedevice.Todoso,invokeanintentthatincludesthe
ACTION_CLEAR_APP_CACHE
intentaction.
Caution:TheACTION_CLEAR_APP_CACHEintentactioncansubstantiallyaffect
devicebatterylifeandmightremovealargenumberoffilesfromthedevice.
Additionalresources
Formoreinformationaboutsavingfilestothedevice'sstorage,consultthe
followingresources.
Videos
PreparingforScopedStorage(AndroidDevSummit
'19)
ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaisaregisteredtrademarkofOracleand/oritsaffiliates.
Lastupdated2021-11-11UTC.
[{
"type":"thumb-down",
"id":"missingTheInformationINeed",
"label":"MissingtheinformationIneed"
},{
"type":"thumb-down",
"id":"tooComplicatedTooManySteps",
"label":"Toocomplicated/toomanysteps"
},{
"type":"thumb-down",
"id":"outOfDate",
"label":"Outofdate"
},{
"type":"thumb-down",
"id":"samplesCodeIssue",
"label":"Samples/codeissue"
},{
"type":"thumb-down",
"id":"otherDown",
"label":"Other"
}]
[{
"type":"thumb-up",
"id":"easyToUnderstand",
"label":"Easytounderstand"
},{
"type":"thumb-up",
"id":"solvedMyProblem",
"label":"Solvedmyproblem"
},{
"type":"thumb-up",
"id":"otherUp",
"label":"Other"
}]
Twitter
Follow@AndroidDevonTwitter
YouTube
CheckoutAndroidDevelopersonYouTube
MoreAndroid
Android
AndroidforEnterprise
Security
Source
News
Blog
Podcasts
Discover
Gaming
MachineLearning
Privacy
5G
AndroidDevices
Largescreens
WearOS
AndroidTV
Androidforcars
AndroidThings
ChromeOSdevices
Releases
Android11
Android10
Pie
Oreo
Nougat
Marshmallow
Lollipop
KitKat
DocumentationandDownloads
AndroidStudioguide
Developersguides
APIreference
DownloadStudio
AndroidNDK
Support
Reportplatformbug
Reportdocumentationbug
GooglePlaysupport
Joinresearchstudies
Android
Chrome
Firebase
GoogleCloudPlatform
Allproducts
Privacy
License
Brandguidelines
Getnewsandtipsbyemail
Subscribe
Language
English
BahasaIndonesia
Español–AméricaLatina
Português–Brasil
中文–简体
日本語
한국어