Android includes support for high performance 2D and 3D graphics with the Open Graphics Library (OpenGL®), specifically, the OpenGL ES API.
Platform
AndroidStudio
GooglePlay
Jetpack
Kotlin
Docs
Games
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
Buildyourfirstapp
OverviewCreateanAndroidprojectRunyourappBuildasimpleuserinterfaceStartanotheractivity
Appfundamentals
Appresources
OverviewHandleconfigurationchanges
Localization
LocalizeyourappTestyourappwithpseudolocalesUnicodeandinternationalizationsupportLanguageandlocaleresolutionComplexXMLresources
Resourcetypes
OverviewAnimationColorstatelistDrawableLayoutMenuStringStyleFontMoretypes
Appmanifestfile
Overview
Devices
Devicecompatibility
OverviewScreencompatibilityoverviewSupportdifferentpixeldensitiesDeclarerestrictedscreensupport
MultipleAPKsupport
OverviewCreatemultipleAPKsfordifferentAPIlevelsCreatemultipleAPKsfordifferentscreensizesCreatemultipleAPKsfordifferentGLtexturesCreatemultipleAPKswithseveraldimensionsSupportdifferentlanguagesandculturesSupportdifferentplatformversionsFiltersonGooglePlay
Tablets,largescreens,andfoldables
GetstartedwithlargescreensLargescreencookbookMediaprojectionEnhancedletterboxing
BuildresponsiveUIs
SupportdifferentscreensizesNavigationforresponsiveUIsMigrateyourUItoresponsivelayoutsActivityembeddingMulti-windowsupportInputcompatibilityonlargescreens
Buildforfoldables
LearnaboutfoldablesMakeyourappfoldawareTestyourapponfoldables
Wear
GetstartedPrinciplesofWearOSdevelopmentUpgradetothelatestversionofWearOSWearOSversusmobiledevelopmentWearOSuserinterface
Gettingstarted
WearOSdeveloperpathwayCreateandrunawearableappDebugaWearOSappCaptureWearUIscreenshots
Overlays
OverviewStandaloneappsAuthenticationRequestpermissionsDetectlocationPlayingaudioonwearablesAppearinRecentsandAppResume
BuildingUIwithCompose
UseJetpackComposeonWearOSComposeperformanceNavigationButtonsCardsChipsDialogsListsPageindicatorsPickersPositionindicatorProgressindicatorSlidersSteppersSwipetodismissTogglechipsTimetext
BuildingUIwithViews
BuildView-basedUIsonWearOSHandledifferentwatchshapesScreenoptionsCreatelistsNavigationExitfullscreenactivitiesonWearShowconfirmationsKeepyourappvisibleonWear
Tilesandcomplications
TilesoverviewWatchfacecomplicationsExposedatatocomplications
Notifications
NotificationsonWearOSBridgingoptionsfornotificationsOngoingActivities
Handlingdata
SendandsyncdataonWearOSNetworkaccessandsynconWearOSAccesstheWearableDataLayerTransferassetsSendandreceivemessagesHandledatalayereventsSyncdataitemswiththeDataLayerAPI
Userinput
PhysicalbuttonsRotaryinputCreateinputmethodeditorsinWearVoice
Healthservices
OverviewActivedataandexercisePassivedataupdatesUsesyntheticdataprovidersEnhanceappcompatibility
Design
DesignprinciplesGettingstartedInteractiontypesScreenshapesNotificationsComplicationsTilesTilesdesignsystemOverlaysOngoingactivitiesConfirmationoverlayDisconnectionindicatorsPermissionmessagesSelectioncontrolsLaunchandlatencyNavigationPermissionsSigninHardwarebuttonsColorTypographyIconsDownloadsWearMaterialTheming
Creatingwatchfaces
OverviewDesignwatchfacesBuildawatchfaceserviceDrawwatchfacesAddingcomplicationstoawatchfaceCreatinginteractivewatchfacesProvideconfigurationactivitiesAddresscommonissuesImproveperformacewithhardwareaccelerationOptimizeperformanceandbatterylife
WatchFaceStudio
WatchFaceStudioKeyboardshortcutsManageaWatchFaceStudioprojectCreateawatchfacewithWatchFaceStudioBuildcomplicationsinWatchFaceStudioTagexpressionsLanguagesettingsAlways-oninWatchFaceStudioGyroeffectsBuildanduploadfromWatchFaceStudioTestyourwatchfaceFAQWearappqualityPackageWearOSappsDistributetoWearOSCreateWearOSappsforChinaWearOSreleasenotes
AndroidTV
Overview
BuildTVApps
OverviewGetstartedwithTVappsAndroidXTVlibrariesHandleTVhardwareManageTVcontrollersBuildTVlayoutsOn-screenkeyboardCreateTVnavigationBestpracticesfordrivingengagementonGoogleTV
BuildTVplaybackapps
Overview
UIguidance&LeanbackAPI
CreateacatalogbrowserProvideacardviewBuildadetailsviewUsetransportcontrolsPlaybackcontrolsonTVAmbientmodeAddaguidedstepIntroducefirst-timeuserstoyourappImplementamediasessionBackgroundplaybackinaNowPlayingcardAudiocapabilitiesMatchcontentframerate
HelpusersfindcontentonTV
Overview
RecommendTVcontent
OverviewChannelsonthehomescreenVideoprogramattributesAudioprogramattributesGameprogramattributes
WatchNext
AddprogramsAttributesGuidelinesforappdevelopersGuidelinesforTVprovidersPreviewvideosRecommendationsinAndroidNandearlierMakeTVappssearchableSearchwithinTVApps
BuildTVgames
OverviewUseStreamProtectforlatency-sensitivestreamingapps
BuildTVinputservices
OverviewDevelopaTVinputserviceWorkwithchanneldataManageTVuserinteractionSupporttime-shiftingSupportcontentrecordingTVAppschecklist
TVAccessibility
AccessibilitybestpracticesTalkBackevaluationexamplesAdoptsystemcaptionsettingsCustomviewaccessibilitysupportCustomviewaccessibilitysample
Releases
Android12forTV
Android13forTV(Beta)
OverviewWhat'snewforTV
AndroidforCars
Overview
Buildmediaappsforcars
BuildmediaappsforcarsAddsupportforAndroidAutoAddsupportforAndroidAutomotiveOSBuildmessagingappsforAndroidAuto
Buildnavigationandpointofinterestappsforcars
UsingtheAndroidforCarsAppLibraryBuildpointofinterestappsforcarsBuildnavigationappsforcarsAddsupportforAndroidAutoAddsupportforAndroidAutomotiveOSBuildvideoappsforAndroidAutomotiveOSTestAndroidappsforcarsDistributeAndroidappsforcarsGooglePlayservicesforcarsNotificationsonAndroidAutomotiveOS
ChromeOSdevices
OverviewBuildingappsforChromeOSOptimizingAppsforChromeOSPreparingyourdevelopmentenvironmentAppManifestCompatibilityforChromebooksChromeOSDeviceSupportforAppsAppRenderingDifferencesonChromebooksWindowmanagementAdaptingGamesonChromeOSSmoothanimationonChromeOSTestCasesforAndroidAppsonChromeOS
Apparchitecture
Introduction
Guidetoapparchitecture
Overview
UIlayer
OverviewUIeventsStateholdersandUIstateDomainlayerDatalayerLearningpathway
ArchitectureComponents
UIlayerlibraries
Viewbinding
OverviewMigratefromKotlinsyntheticstoviewbinding
Databindinglibrary
OverviewGetstartedLayoutsandbindingexpressionsWorkwithobservabledataobjectsGeneratedbindingclassesBindingadaptersBindlayoutviewstoArchitectureComponentsTwo-waydatabinding
Lifecycle-awarecomponents
HandlelifecyclesViewModelLiveDataSaveUIstatesSavedStatemoduleforViewModelUseKotlincoroutineswithlifecycle-awarecomponents
PagingLibrary
OverviewLoadanddisplaypageddataPagefromnetworkanddatabaseTransformdatastreamsManageandpresentloadingstatesTestyourPagingimplementationMigratetoPaging3
Paging2
OverviewDisplaypagedlistsLoadpageddata
Datalayerlibraries
DataStore
WorkManager
OverviewGettingStarted
How-ToGuides
DefiningyourWorkRequestsWorkstatesManagingworkObservingintermediateWorkerprogressChainingworktogetherTestingWorkerimplementationIntegrationtestswithWorkManagerDebuggingWorkManager
AdvancedConcepts
ConfigurationandInitialization
ThreadinginWorkManager
OverviewThreadinginWorkerThreadinginCoroutineWorkerThreadinginRxWorkerThreadinginListenableWorkerSupportforlong-runningworkersMigratingfromFirebaseJobDispatcherMigratingfromGCMNetworkManager
Appentrypoints
Activities
IntroductiontoactivitiesTheactivitylifecycleActivitystatechangesTestyouractivitiesTasksandbackstackProcessesandapplifecycleParcelablesandbundlesLoadersRecentsscreenRestrictionsonstartingactivitiesfromthebackground
Appshortcuts
OverviewCreateshortcutsAddcapabilitiesManageshortcutsBestpracticesforshortcuts
Appnavigation
PrinciplesofnavigationDesignfordifferentformfactorsHandleconfigurationchanges
Navigationcomponent
OverviewGettingstartedCreatedestinationsDesignnavigationgraphsNestedgraphsGlobalactionsNavigatetoadestinationSupportmultiplebackstacksConditionalnavigationPassdatabetweendestinationsCreateadeeplinkforadestinationAnimatetransitionsbetweendestinationsUpdateUIcomponentswithNavigationUIKotlinDSLInteractprogrammaticallyNavigatewithfeaturemodulesBestpracticesformulti-moduleprojectsTestnavigationAddnewdestinationtypesMigratetotheNavigationcomponent
Fragments
OverviewCreateafragmentFragmentmanagerFragmenttransactionsAnimatetransitionsbetweenfragmentsFragmentlifecycleSavingstatewithfragmentsCommunicatewithfragmentsWorkingwiththeappbarDisplayingdialogswithDialogFragmentDebugyourfragmentsTestyourfragments
Applinks
OverviewEnablinglinkstoappcontentVerifyapplinksCreateapplinksforinstantappsCreateswipeviewswithtabsusingViewPagerCreateswipeviewswithtabsusingViewPager2Providecustombacknavigation
Dependencyinjection
OverviewManualdependencyinjectionDependencyinjectionwithHiltHiltinmulti-moduleappsUseHiltwithotherJetpacklibrariesHilttestingguideHiltandDaggerannotationscheatsheet
Dagger
DaggerbasicsUsingDaggerinAndroidappsUsingDaggerinmulti-moduleapps
AppStartup
Coretopics
Appcompatibility
OverviewCompatibilityframeworktoolsRestrictionsonnon-SDKinterfaces
Interactwithotherapps
OverviewSendingtheusertoanotherappGettingaresultfromanactivityAllowingotherappstostartyouractivity
Packagevisibility
OverviewKnowwhichpackagesarevisibleautomaticallyDeclarepackagevisibilityneedsFulfillcommonusecasesTestpackagevisibility
Intentsandintentfilters
OverviewCommonintents
Userinterface
Overview
Layouts
OverviewBuildaresponsiveUIwithConstraintLayout
AddmotiontoyourlayoutwithMotionLayout
OverviewCarouselwithMotionLayoutMotionLayoutexamples
MotionLayoutXMLreference
OverviewCreatealistwithRecyclerViewAdvancedRecyclerViewcustomizationCreateacard-basedlayoutCreateatwopanelayout
Improvinglayoutperformance
OverviewOptimizinglayouthierarchiesRe-usinglayoutswithDelayedloadingofviewsLinearlayoutAdapterviewRelativelayout
Customviewcomponents
OverviewCreatingacustomviewclassImplementingcustomdrawingMakingtheviewinteractiveOptimizingtheviewDesigningforfoldables
Lookandfeel
MaterialdesignStylesandthemesDarkthemeRoundedcornersAdaptiveiconsAddafloatingactionbuttonCreateshadowsandclipviews
Text
AutosizingTextViewsDownloadablefontsFontsinXML
Emoji
SupportmodernemojiEmojicompatibilityMagnifierwidgetSpansButtonsCheckboxesRadiobuttonsTogglebuttonsSpinnersPickersTooltips
Notifications
OverviewCreateanotificationCreateanexpandablenotificationDisplaytime-sensitivenotificationsStartanactivityfromanotificationCreateagroupofnotificationsCreateandmanagenotificationchannelsModifyanotificationBadgeCreateacustomnotification
Splashscreens
OverviewMigrateyourexistingsplashscreenConversationsBubbles
Addtheappbar
OverviewSetuptheappbarAddandhandleactionsAddanupactionUseactionviewsandactionproviders
Windowinsets
OverviewDisplayedge-to-edgeImmersivemodeSupportdisplaycutoutsControlthesoftwarekeyboard
Supportingswipe-to-refresh
OverviewAddingswipe-to-refreshtoyourappRespondingtoarefreshgestureToastsoverview
Pop-upmessagesoverview
OverviewBuildanddisplayapop-upmessageAddanactiontoamessageDialogsMenus
Settings
OverviewOrganizeyoursettingsCustomizeyoursettingsUsesavedvaluesBuildahierarchyincodeHandleotherformfactorsPreferencecomponentsandattributes
Search
OverviewCreatingasearchinterfaceAddingrecentquerysuggestionsAddingcustomsuggestionsSearchableconfiguration
Addingsearchfunctionality
OverviewSettingupthesearchinterfaceStoringandsearchingfordataRemainingbackwardcompatibleReceiverichcontentCopyandpasteDraganddropPicture-in-picturesupport
Creatingbackward-compatibleUIs
OverviewAbstractingthenewAPIsProxyingtothenewAPIsCreatinganimplementationwitholderAPIsUsingtheversion-awarecomponentDevicecontrol
Homechannelsformobileapps
OverviewMediaHomeBooksMediaHomeVideoMediaHomeAudio
Appwidgets
OverviewCreateasimplewidgetEnhanceyourwidgetCreateanadvancedwidgetUsewidgetcollectionsProvideflexiblewidgetlayoutsEnablewidgetconfigurationBuildanappwidgethost
Animations&transitions
OverviewIntroductiontoanimationsPropertyanimationoverviewAnimatedrawablegraphicsRevealorhideaviewusinganimationMoveaviewusinganimationMoveaviewusingaflinganimationEnlargeaviewusingazoomanimationAnimatemovementusingspringphysicsAutoanimatelayoutupdatesAnimatelayoutchangesusingatransitionCreateacustomtransitionanimationStartanactivityusingananimationSlidebetweenfragmentsusingViewPagerSlidebetweenfragmentsusingViewPager2MigratefromViewPagertoViewPager2Additionalresources
Images&graphics
OverviewDrawablesoverviewVectordrawablesoverviewHandlingbitmapsSelectingcolorswiththepaletteAPIReducingimagedownloadsizesHardwareacceleration
DrawingwithAGSLshaders
OverviewDifferencesbetweenAGSLandGLSLUsingAGSLinyourAndroidappAGSLQuickReferenceOpenGLES
DisplayinggraphicswithOpenGLES
OverviewBuildinganOpenGLESenvironmentDefiningshapesDrawingshapesApplyingprojectionandcameraviewsAddingmotionRespondingtotouchevents
Rendering
OverviewReducingoverdrawPerformanceandviewhierarchiesAnalyzingwithprofileGPUrenderingEnhancinggraphicswithwidecolorcontent
Audio&video
Audio&videooverview
Media3
Overview
Gettingstarted
UseamediasessiontomanageplaybackPlaymediainthebackground
ExoPlayer
ExoPlayerandMedia3ExoPlayertoMedia3mappingsMigrationguideMediacontrolsSupportedmediaformatsMediacodecs
Mediaapparchitecture
MediaapparchitectureoverviewUsingamediasession
Buildinganaudioapp
AudioappoverviewBuildingamediabrowserserviceBuildingamediabrowserclientMediasessioncallbacksUsingthemediacontrollertestapp
Buildingavideoapp
VideoappoverviewBuildingavideoplayeractivityMediasessioncallbacksCompatiblemediatranscodingRespondingtomediabuttonsHandlingchangesinaudiooutputManageaudiofocus
TheGoogleAssistant
TheGoogleAssistantandmediaappsMediaappsonGoogleAssistantdrivingmode
Routingbetweendevices
RoutingoverviewMediaRouteroverviewMediaRouteProvideroverviewControlamplitudewithVolumeShaperMediaPlayeroverviewMediaRecorderoverviewExoPlayerSharingaudioinputCapturevideoandaudioplaybackFramerateBestpracticesforsharingvideoAdditionalResourcesforMedia
Services
OverviewForegroundservicesBoundservicesAIDLoverview
Backgroundtasks
OverviewBackgroundthreadsBackgroundoptimizations
Broadcasts
OverviewImplicitBroadcastExceptions
Managedeviceawakestate
OverviewKeepthedeviceawakeSchedulealarmsUsingaListenableFuture
Permissions
OverviewEvaluatewhetheryourappneedspermissionsDeclareapppermissionsRequestapppermissionsExplainaccesstomoresensitiveinformationApppermissionsbestpracticesPermissionsusedonlyindefaulthandlersRestrictinteractionswithotherappsDefinecustompermissions
Appdata&files
OverviewStorageoverviewSavetoapp-specificstorage
Savetosharedstorage
OverviewMediaDocumentsandotherfilesDatasetsManageallfilesonastoragedeviceSavekey-valuedata
Savedatainalocaldatabase
OverviewDefinedatausingentitiesAccessdatausingDAOsDefinerelationshipsbetweenobjectsWriteasynchronousDAOqueriesCreateviewsintoadatabasePrepopulateyourdatabaseMigrateyourdatabaseTestanddebugyourdatabaseReferencecomplexdataMigratefromSQLitetoRoomSavedatausingSQLiteStorageusecasesandbestpractices
Sharingsimpledata
OverviewSendingsimpledatatootherappsReceivingsimpledatafromotherapps
Sharingfiles
OverviewSettingupfilesharingSharingafileRequestingasharedfileRetrievingfileinformation
SharingfileswithNFC
OverviewSendingfilestoanotherdeviceReceivingfilesfromanotherdevice
Printingfiles
OverviewPrintingphotosPrintingHTMLdocumentsPrintingcustomdocuments
Contentproviders
OverviewContentproviderbasicsCreatingacontentproviderOpenfilesusingstorageaccessframeworkCreateacustomdocumentproviderAppinstalllocation
Userdata&identity
OverviewAddsign-inworkflowShowabiometricauthenticationdialog
Autofillframework
OverviewOptimizeyourappforautofillBuildautofillservicesIntegrateautofillwithkeyboardsIdentifydeveloper-ownedappsReviewhowyourappcollectsandsharesuserdataAuditdataaccessGetauser-resettableadvertisingIDCalendarprovideroverview
Contactsprovider
OverviewRetrievingalistofcontactsRetrievingdetailsforacontactModifyingcontactsusingintentsDisplayingthequickcontactbadgeAccounttransfer
Databackup
OverviewBackupuserdataBackupkey-valuepairsTestbackupandrestoreBestpracticesforuniqueidentifiers
Rememberandauthenticateusers
OverviewRememberyouruserAuthenticatetoOAuth2servicesCreateacustomaccounttype
Userlocation
OverviewRequestlocationpermissionsGetthelastknownlocationChangelocationsettingsRequestlocationupdatesAccesslocationinthebackgroundCreateandmonitorgeofencesDetectwhenusersstartanactivityOptimizelocationforbatteryTestlocationworkflowsMigratetolocationandcontextAPIsAddmaps
Touch&input
OverviewInputevents
Usingtouchgestures
OverviewDetectcommongesturesTracktouchandpointermovementsAnimateascrollgestureSupportnavigationgesturesHandlemulti-touchgesturesDragandscaleManagetoucheventsinaViewGroup
Handlingkeyboardinput
OverviewSpecifyingtheinputmethodtypeHandlinginputmethodvisibilitySupportingkeyboardnavigationHandlingkeyboardactions
Supportinggamecontrollers
OverviewHandlingcontrolleractionsSupportingcontrollersacrossAndroidversionsSupportingmultiplegamecontrollers
Inputmethodeditors
CreatinganinputmethodImagekeyboardSpellingchecker
Camera
Chooseacameralibrary
CameraX
OverviewArchitectureConfiguration
Usecases
PreviewImagecaptureImageanalysisVideocapture
Advancedtopics
ExtensionsAPITransformoutputRotationsDevices
Camera2
OverviewCameracapturesessionsandrequestsCameralensesandcapabilitiesUsemultiplecamerastreamssimultaneouslyCamerapreviewMulti-CameraAPIExtensionsAPI
Camera(deprecated)
OverviewTakephotosRecordvideosControlthecameraCameraAPI
Sensors
OverviewSensorsoverviewMotionsensorsPositionsensorsEnvironmentsensorsRawGNSSmeasurements
Connectivity
Overview
Performingnetworkoperations
OverviewConnecttothenetworkManagenetworkusageReadingnetworkstateOptimizenetworkaccessOptimizenetworkdatausageMonitorconnectivitystatusandconnectionmeteringParseXMLdata
PerformnetworkoperationsusingCronet
OverviewSendasimplerequestCronetrequestlifecycleUseCronetwithotherlibraries
Reference
org.chromium.net
OverviewCallbackException
CronetEngine
Overview
CronetEngine.Builder
OverviewLibraryLoaderCronetExceptionInlineExecutionProhibitedExceptionNetworkExceptionQuicExceptionUploadDataProviderUploadDataProvidersUploadDataSink
UrlRequest
OverviewBuilderCallbackStatusStatusListener
UrlResponseInfo
OverviewHeaderBlockEnhanceyourappswith5GBuildclient-serverapplicationswithgRPC
Transferringdatawithoutdrainingthebattery
OverviewOptimizedownloadsforefficientnetworkaccessMinimizetheeffectofregularupdatesAvoidunoptimizeddownloads
Reducenetworkbatterydrain
OverviewCollectingnetworktrafficdataAnalyzingdatatrafficOptimizenetworkaccessOptimizeuser-initiatednetworkuseOptimizeapp-initiatednetworkuseOptimizeserver-initiatednetworkuseOptimizinggeneralnetworkuse
TransferdatausingSyncAdapters
OverviewCreateaStubAuthenticatorCreateaStubContentProviderCreateaSyncAdapterRunaSyncAdapter
Bluetooth
OverviewSetupBluetoothFindBluetoothdevicesConnectBluetoothdevicesTransferBluetoothdataBluetoothpermissionsBluetoothprofilesCompaniondevicepairing
BluetoothLowEnergy
OverviewFindBLEdevicesConnecttoaGATTserverTransferBLEdata
NFC
OverviewNFCbasicsAdvancedNFCHost-basedcardemulationoverview
Telecom
OverviewBuildacallingappPreventcallerIDspoofingTelephonyIDs
Wi-Fi
Wi-FiscanningoverviewWi-Fipeer-to-peerWi-FiAwareoverviewWi-FilocationwithRTTLocalOnlyHotspot
Discoverandconnect
OverviewUsenetworkservicediscoveryCreateP2PconnectionswithWi-FiUseWi-FiP2PforservicediscoveryWi-FiEasyConnect
Wi-Fiinfrastructure
Wi-FiinfrastructureoverviewWi-FisuggestionAPIforinternetconnectivityWi-FiNetworkRequestAPIforpeer-to-peerconnectivityPasspointSavenetworksandPasspointconfigurations
USB
OverviewAccessoryoverviewHostoverviewUWBVPNSessioninitiationprotocoloverviewOpenMobileAPIreadersupport
Renderscript
OverviewAdvancedRenderScriptMigratefromRenderScript
RuntimeAPIreference
OverviewNumericaltypesObjecttypesConversionfunctionsMathematicalconstantsandfunctionsVectormathfunctionsMatrixfunctionsQuaternionfunctionsAtomicupdatefunctionsTimefunctionsandtypesAllocationdataaccessfunctionsObjectcharacteristicsfunctionsKernelinvocationfunctionsandtypesInput/outputfunctionsDebuggingfunctionsGraphicsfunctionsandtypesIndex
Web-basedcontent
OverviewBuildingwebappsinWebViewManagingWebViewobjectsLoadlocalcontentDarkenwebcontentUserprivacyinWebViewreportingSupportingdifferentscreensinwebappsDebuggingwebappsBestpracticesforwebappsTestingagainstfutureversionsofWebView
AndroidAppBundles
OverviewConfigurethebasemoduleBuildandtestyourappbundleAddcodetransparencyTheappbundleformatFrequentlyaskedquestions
GooglePlay
GooglePlayBillingGooglePlayCorelibraries
PlayPoints
OverviewCreateproductsandpromotionsDetectanddeliverproductsTestproducts
PlayAssetDelivery
OverviewIntegrateassetdelivery(Kotlin&Java)Integrateassetdelivery(native)Integrateassetdelivery(Unity)TargettexturecompressionformatsTestassetdelivery
PlayFeatureDelivery
OverviewConfigureinstall-timedeliveryConfigureconditionaldeliveryConfigureon-demanddeliveryOn-demanddeliverybestpracticesConfigureinstantdeliveryAdditionalresources
In-appreviews
OverviewIntegrateusingKotlinorJavaIntegrateusingnativecodeIntegrateusingUnityTestin-appreviews
In-appupdates
OverviewSupportin-appupdates(KotlinorJava)Supportin-appupdates(Native)Supportin-appupdates(Unity)Testin-appupdates
GooglePlayInstant
OverviewofGooglePlayInstant
Getstartedwithinstantapps
Createaninstant-enabledappbundleUXbestpracticesforapps
Getstartedwithinstantgames
OverviewUnitypluginUXbestpracticesforgamesMigratetoAndroidAppBundlesImplementclouddeliveryofassetsSupportGooglePlayGamesServicesInstantPlaygamesInstantPlaygameschecklistReducethesizeofyourinstantapporgameAddadstoyourinstantapporgameProvidemultipleentrypoints
IntegratewithFirebase
AddGoogleAnalyticsforFirebasetoyourinstantappUseFirebaseDynamicLinkswithinstantappsTechnicalrequirementschecklistGooglePlayInstantpolicy
Resources
ReferenceCodesamplesSDKreleasenotesInstantAppIntents
Support
KnownissuesStackOverflowPlayDeveloperAPI
PlayInstallReferrer
Overview
PlayInstallReferrerLibrary
OverviewReferenceReleasenotesPlayInstallReferrerAPIPlayIntegrityAPI
PlayRequirements
PlayPoliciesTargetAPILevelSupport64-bitarchitectures
ApplicationLicensing
OverviewLicensingOverviewSettingUpforLicensingAddingServer-SideVerificationAddingClient-SideVerificationLicensingReferenceAPKExpansionFiles
GoogleAssistant
Overview
Build
AppActionsoverviewImplementbuilt-inintentsCreateshortcuts.xmlPushdynamicshortcutstoAssistantReleasenotes
Test
GoogleAssistantplugin
Grow
OverviewIn-AppShortcutPromoSDK
Addmorefeatures
CustomintentsAndroidwidgetsForegroundappinvocationInlineinventoryWebinventoryAssistantsharingReadIt
Actions.xml
Actions.xmlmigrationguideActions.xmloverviewBuildAppActionsCreateactions.xmlWebinventoryAppActionstesttoolAndroidSlicesTroubleshootingSupport
Slices
OverviewGettingStartedSlicetemplates
On-devicesearch
Games
Develop
Overview
AndroidGameDevelopmentKit(AGDK)
OverviewLibrariesDownloadReleasenotesAndroidStudio
AndroidGameDevelopmentExtensionforVisualStudio
OverviewQuickstartConfigureaprojectDebuggerMeasureappperformanceModifybuild.gradlefilesforAndroidStudioSamplesReleasenotes
AndroidGPUInspector
OverviewQuickstartSupporteddevices
Systemprofiling
OverviewViewasystemprofileGPUperformancecounters
Analyzeasystemprofile
FrameprocessingtimesMemoryefficiencyTexturememorybandwidthusageVertexmemorybandwidthusageThreadscheduling
Frameprofiling
Overview
Analyzeaframeprofile
MostexpensiverenderpassesVertexformatsShaderperformance
FrameProfilerUI
PerformancepaneCommandspaneFramebufferpaneGeometrypaneReportpaneShaderpaneMemorypaneStatepaneTexturespaneTexturepanePipelineviewpaneSupportedVulkanextensionsTroubleshootAndroidPerformanceTuner
MemoryAdviceAPI
OverviewGetstarted
Improve
ImprovegameperformanceReducegamesize
Improvedeviceavailability
Support64-bitarchitecturesSupportallscreens
GameMode
OverviewOptimizewithGameModeAPIGameModeinterventions
VulkanandOpenGL
3DassetoptimizationVulkanPrerotationVertexdatamanagement
Distribute
Overview
GooglePlayGamesServices
OverviewGetstartedDownloads
SetupPlayConsole
SetupPlayGamesServicesEnablefeaturesCloudprojectmanagementPublish
Managefeatures
AchievementsLeaderboardsEventsSavedgamesFriendsSign-in
UsetheAPIs
Android
GetstartedSign-inEnableserver-sideaccessAnti-piracy
Addfeatures
AchievementsLeaderboardsFriendsSavedgamesEventsPlayerstatsTroubleshooting
Unity
OverviewGetstarted
Addfeatures
AchievementsLeaderboardsSavedgamesEventsFriendsPlayerstatsCAPI-comingsoon
PublishingAPI
OverviewGetstartedUploadimagesManagementAPI
Requirementsandguidelines
QualitychecklistBrandingguidelinesQuotaandratelimitsDatadisclosurerequirementsTermsofserviceSupport
GooglePlayGamesforPC
OverviewGetstarted
Setupyourgame
PCcompatibilityGraphicsconfiguration
Deviceinput
Setupinput
InputSDK
OverviewQuickstart
Continuity
OverviewContinuityrequirementsVerifyingrequirementsExistingidentitysolutionsUsetheemulatorTestonChromeOS
Publishanddeploy
PackageSubmitUpdateFAQGooglePlayInstantPlayasyoudownload
Health&fitnessapps
HealthConnect
Introduction
Platformoverview
ArchitectureDeveloperfunctionalityGetstarted
Dataanddatatypes
IntroductionDatatypesDifferentialchangesAPI
Commonworkflows
WritedataReaddataDeletedataAggregatedataWorkwithsessionsExceptionsFrequentlyaskedquestions
HealthConnectguidelines
HealthConnectpolicyrequirementFAQsUXdeveloperguidance
Migrate
HealthConnectAPIcomparisonguideFitAndroidAPItoHealthConnectmigrationguide
Bestpractices
Testing
TestappsonAndroid
Fundamentals
FundamentalsoftestingAndroidappsWhattotestinAndroidUsingtestdoublesinAndroid
Localtests
Buildlocaltests
Instrumentedtests
BuildinstrumentedtestsAutomateUItests
AndroidXtestlibraries
SetupprojectforAndroidXTestJUnit4ruleswithAndroidXTestAndroidJUnitRunner
Espresso
EspressoEspressobasicsEspressosetupinstructionsEspressocheatsheetEspressoidlingresourcesEspresso-IntentsEspressolistsMultiprocessEspressoEspressorecipesEspressoWebAccessibilitycheckingAdditionalResourcesforEspresso
Testingothercomponents
TestcontentprovidersTestyourserviceWriteautomatedtestswithUIAutomator
Performance
Overview
Inspectingperformance
OverviewAndroidStudioProfilers
Profilingandtracing
Systemtracing
Overview
Capturetrace
CaptureatraceinAndroidStudioCaptureatraceonadeviceCaptureatracefromthecommandlineNavigateareport
Customevents
DefinecustomeventsCustomtraceeventsinnativecodeInspectGPUrendering
Benchmarking
Overview
Macrobenchmark
WritingabenchmarkCapturethemetricsControlyourappAddinginstrumentationarguments
Microbenchmark
OverviewWritingabenchmarkProfilingabenchmarkAddinginstrumentationargumentsBuildingwithoutGradleBenchmarkinginCI
Measureperformance
OverviewExamples
Improvingperformance
OverviewBaselineProfilesAppstartuplibrary
Guides
WorkinginthebackgroundPerformanceclassAppStandbyBucketsAppHibernationVerifyingAppBehaviorontheAndroidRuntime(ART)
Solvingcommonproblems
AppStartup
Slowrendering
KeepingyourappresponsiveImprovinglayoutperformanceRendering
Memory
OverviewofmemorymanagementMemoryallocationamongpropertiesManageyourapp'smemoryProcessesandthreads
Batteryandpower
OptimizefordozeandappstandbyMonitorthebatterylevelandchargingstateMonitorconnectivitystatusandconnectionmeteringDetermingandmonitordockingstateandtypeProfilebatteryusagewithBatterystatsandBatteryHistorianAnalyzepowerusewithBatteryHistorianTestpower-relatedissuesBackgroundoptimizationsReduceappsize
Monitoringperformance
Overview
AndroidVitals
OverviewStuckPartialWakeLocksExcessiveWakeupsExcessiveBackgroundWi-FiScansExcessiveBackgroundNetworkUsageANRsCrashesSlowRenderingFrozenFramesPermissionDenialsAppStartupTimeJankStatslibrary
Accessibility
Overview
Buildandtestappsforaccessibility
MakeappsmoreaccessiblePrinciplesforimprovingappaccessibilityTestyourapp'saccessibility
Advancedtopics
MakecustomviewsmoreaccessibleCreateyourownaccessibilityserviceAdditionalresources
Privacy
Privacybestpractices
Security
AppsecuritybestpracticesSecuritytipsSecuritywithdataSecuritywithdataacrossadditionalAndroidversionsSecuritywithHTTPSandSSLNetworksecurityconfigurationUpdatingyoursecurityprovidertoprotectagainstSSLexploits
ProtectingagainstsecuritythreatswithSafetyNet
OverviewSafetyNetAttestationAPIDiscontinuingSafetyNetAttestationPlayIntegrityAPISafetyNetSafeBrowsingAPISafetyNetreCAPTCHAAPISafetyNetVerifyAppsAPICryptographyAndroidKeystoreSystemVerifyinghardware-backedkeypairswithkeyattestationAndroidProtectedConfirmationSupportingDirectBootRunningembeddedDEXcodeAppsecurityimprovementprogram
SDKs
SDKbestpractices
BuildforBillions
OverviewConnectivityDevicecapabilityDatacostBatteryconsumptionUIandcontent
BuildforEnterprise
OverviewDeveloperguideWorkprofilesSetupmanagedconfigurations
Appfeedback
SendappfeedbacktoEMMsTestappfeedbackWorkcontactsDevicemanagementpolicies
Devicemanagement
OverviewBuildadevicepolicycontroller
Dedicateddevices
OverviewLocktaskmodeMultipleusersCookbookDevicecontrolNetworkingandtelephonySecuritySystemupdatesNetworkactivitylogging
Androidversions
OverviewAndroid12Android11Android10Android9Android8.0Android7.0Deviceadministration
AndroidDevelopers
Docs
Guides
OpenGLES
Androidincludessupportforhighperformance2Dand3DgraphicswiththeOpenGraphicsLibrary
(OpenGL®),specifically,theOpenGLESAPI.OpenGLisacross-platformgraphicsAPIthat
specifiesa
standardsoftwareinterfacefor3Dgraphicsprocessinghardware.OpenGLESisaflavoroftheOpenGL
specificationintendedforembeddeddevices.AndroidsupportsseveralversionsoftheOpenGLES
API:
OpenGLES1.0and1.1-ThisAPIspecificationissupportedbyAndroid1.0andhigher.
OpenGLES2.0-ThisAPIspecificationissupportedbyAndroid2.2(APIlevel8)andhigher.
OpenGLES3.0-ThisAPIspecificationissupportedbyAndroid4.3(APIlevel18)andhigher.
OpenGLES3.1-ThisAPIspecificationissupportedbyAndroid5.0(APIlevel21)andhigher.
Caution:
RegardlessoftheAndroidplatformversion,adevicecannotsupport
theOpenGLES3.0APIunlessthedevicemanufacturerprovidesan
implementationofthisgraphicspipeline.Ifyouspecifyinthemanifestthat
OpenGLES3.0isrequired,youcanbesurethatthatversionwillbepresent
onthedevice.Ifyouspecifythatalower-levelversionisrequiredbutyou
wanttouse3.0featuresifthey'reavailable,youshouldcheckatruntime
toseewhatversionofOpenGLthedevicesupports.Forinformationonhowto
dothis,seeCheckingOpenGLESversion.
Note:
ThespecificAPIprovidedbytheAndroidframeworkissimilartotheJ2MEJSR239OpenGLESAPI,
butisnotidentical.IfyouarefamiliarwithJ2MEJSR239specification,bealertfor
variations.
Alsosee
DisplayinggraphicswithOpenGLES
OpenGLES
OpenGLES1.xSpecification
OpenGLES2.xspecification
OpenGLES3.xspecification
Thebasics
AndroidsupportsOpenGLboththroughitsframeworkAPIandtheNativeDevelopment
Kit(NDK).ThistopicfocusesontheAndroidframeworkinterfaces.Formoreinformationaboutthe
NDK,seetheAndroidNDK.
TherearetwofoundationalclassesintheAndroidframeworkthatletyoucreateandmanipulate
graphicswiththeOpenGLESAPI:GLSurfaceViewand
GLSurfaceView.Renderer.IfyourgoalistouseOpenGLinyourAndroidapplication,
understandinghowtoimplementtheseclassesinanactivityshouldbeyourfirstobjective.
GLSurfaceView
ThisclassisaViewwhereyoucandrawandmanipulateobjectsusing
OpenGLAPIcallsandissimilarinfunctiontoaSurfaceView.Youcanuse
thisclassbycreatinganinstanceofGLSurfaceViewandaddingyour
Renderertoit.However,ifyouwanttocapture
touchscreenevents,youshouldextendtheGLSurfaceViewclassto
implementthetouchlisteners,asshowninOpenGLtraininglesson,
Respondingtotouchevents.
GLSurfaceView.Renderer
ThisinterfacedefinesthemethodsrequiredfordrawinggraphicsinaGLSurfaceView.Youmustprovideanimplementationofthisinterfaceasa
separateclassandattachittoyourGLSurfaceViewinstanceusing
GLSurfaceView.setRenderer().
TheGLSurfaceView.Rendererinterfacerequiresthatyouimplementthe
followingmethods:
onSurfaceCreated():Thesystemcallsthis
methodonce,whencreatingtheGLSurfaceView.Usethismethodtoperform
actionsthatneedtohappenonlyonce,suchassettingOpenGLenvironmentparametersor
initializingOpenGLgraphicobjects.
onDrawFrame():ThesystemcallsthismethodoneachredrawoftheGLSurfaceView.Usethismethodastheprimaryexecutionpointfor
drawing(andre-drawing)graphicobjects.
onSurfaceChanged():ThesystemcallsthismethodwhentheGLSurfaceViewgeometrychanges,includingchangesinsizeoftheGLSurfaceViewororientationofthedevicescreen.Forexample,thesystemcalls
thismethodwhenthedevicechangesfromportraittolandscapeorientation.Usethismethodto
respondtochangesintheGLSurfaceViewcontainer.
OpenGLESpackages
OnceyouhaveestablishedacontainerviewforOpenGLESusingGLSurfaceViewandGLSurfaceView.Renderer,youcanbegin
callingOpenGLAPIsusingthefollowingclasses:
OpenGLES1.0/1.1APIPackages
android.opengl-ThispackageprovidesastaticinterfacetotheOpenGLES
1.0/1.1classesandbetterperformancethanthejavax.microedition.khronospackage
interfaces.
GLES10
GLES10Ext
GLES11
GLES11Ext
javax.microedition.khronos.opengles-Thispackageprovidesthestandard
implementationofOpenGLES1.0/1.1.
GL10
GL10Ext
GL11
GL11Ext
GL11ExtensionPack
OpenGLES2.0APIClass
android.opengl.GLES20-Thispackageprovidesthe
interfacetoOpenGLES2.0andisavailablestartingwithAndroid2.2(APIlevel8).
OpenGLES3.0/3.1APIPackages
android.opengl-ThispackageprovidestheinterfacetotheOpenGLES3.0/3.1
classes.
Version3.0isavailablestartingwithAndroid4.3(APIlevel18).Version3.1isavailable
startingwithAndroid5.0(APIlevel21).
GLES30
GLES31
GLES31Ext(AndroidExtensionPack)
IfyouwanttostartbuildinganappwithOpenGLESrightaway,followthe
DisplayinggraphicswithOpenGLES
class.
DeclaringOpenGLrequirements
IfyourapplicationusesOpenGLfeaturesthatarenotavailableonalldevices,youmustinclude
theserequirementsinyourAndroidManifest.xml
file.HerearethemostcommonOpenGLmanifestdeclarations:
OpenGLESversionrequirements-Ifyourapplicationrequiresaspecific
versionof
OpenGLES,youmustdeclarethatrequirementbyaddingthefollowingsettingstoyourmanifestas
shownbelow.
ForOpenGLES2.0:
AddingthisdeclarationcausesGooglePlaytorestrictyourapplicationfrombeing
installedondevicesthatdonotsupportOpenGLES2.0.Ifyourapplicationisexclusivelyfor
devicesthatsupportOpenGLES3.0,youcanalsospecifythisinyourmanifest:
ForOpenGLES3.0:
ForOpenGLES3.1:
Note:
TheOpenGLES3.xAPIisbackwards-compatiblewiththe2.0API,whichmeansyoucanbemore
flexiblewithyourimplementationofOpenGLESinyourapplication.BydeclaringtheOpenGL
ES2.0APIasarequirementinyourmanifest,youcanusethatAPIversionasadefault,check
fortheavailabilityofthe3.xAPIatruntimeandthenuseOpenGLES3.xfeaturesifthe
devicesupportsit.FormoreinformationaboutcheckingtheOpenGLESversionsupportedbya
device,seeCheckingOpenGLESversion.
Texturecompressionrequirements-Ifyourapplicationusestexture
compressionformats,youmustdeclaretheformatsyourapplicationsupportsinyourmanifestfile
using.
Formoreinformationaboutavailabletexturecompression
formats,seeTexturecompressionsupport.
Declaringtexturecompressionrequirementsinyourmanifesthidesyourapplicationfromusers
withdevicesthatdonotsupportatleastoneofyourdeclaredcompressiontypes.Formore
informationonhowGooglePlayfilteringworksfortexturecompressions,seethe
GooglePlayandtexturecompressionfilteringsectionofthedocumentation.
Mappingcoordinatesfordrawnobjects
OneofthebasicproblemsindisplayinggraphicsonAndroiddevicesisthattheirscreenscan
varyinsizeandshape.OpenGLassumesasquare,uniformcoordinatesystemand,bydefault,happily
drawsthosecoordinatesontoyourtypicallynon-squarescreenasifitisperfectlysquare.
Figure1.DefaultOpenGLcoordinatesystem(left)mappedtoatypicalAndroid
devicescreen(right).
TheillustrationaboveshowstheuniformcoordinatesystemassumedforanOpenGLframeonthe
left,andhowthesecoordinatesactuallymaptoatypicaldevicescreeninlandscapeorientation
ontheright.Tosolvethisproblem,youcanapplyOpenGLprojectionmodesandcameraviewsto
transformcoordinatessoyourgraphicobjectshavethecorrectproportionsonanydisplay.
Inordertoapplyprojectionandcameraviews,youcreateaprojectionmatrixandacameraview
matrixandapplythemtotheOpenGLrenderingpipeline.Theprojectionmatrixrecalculatesthe
coordinatesofyourgraphicssothattheymapcorrectlytoAndroiddevicescreens.Thecameraview
matrixcreatesatransformationthatrendersobjectsfromaspecificeyeposition.
ProjectionandcameraviewinOpenGLES1.0
IntheES1.0API,youapplyprojectionandcameraviewbycreatingeachmatrixandthen
addingthemtotheOpenGLenvironment.
Projectionmatrix-Createaprojectionmatrixusingthegeometryofthe
devicescreeninordertorecalculateobjectcoordinatessotheyaredrawnwithcorrectproportions.
ThefollowingexamplecodedemonstrateshowtomodifytheonSurfaceChanged()methodofaGLSurfaceView.Renderer
implementationtocreateaprojectionmatrixbasedonthescreen'saspectratioandapplyittothe
OpenGLrenderingenvironment.
Kotlin
overridefunonSurfaceChanged(gl:GL10,width:Int,height:Int){
gl.apply{
glViewport(0,0,width,height)
//makeadjustmentsforscreenratio
valratio:Float=width.toFloat()/height.toFloat()
glMatrixMode(GL10.GL_PROJECTION)//setmatrixtoprojectionmode
glLoadIdentity()//resetthematrixtoitsdefaultstate
glFrustumf(-ratio,ratio,-1f,1f,3f,7f)//applytheprojectionmatrix
}
}
Java
publicvoidonSurfaceChanged(GL10gl,intwidth,intheight){
gl.glViewport(0,0,width,height);
//makeadjustmentsforscreenratio
floatratio=(float)width/height;
gl.glMatrixMode(GL10.GL_PROJECTION);//setmatrixtoprojectionmode
gl.glLoadIdentity();//resetthematrixtoitsdefaultstate
gl.glFrustumf(-ratio,ratio,-1,1,3,7);//applytheprojectionmatrix
}
Cameratransformationmatrix-Onceyouhaveadjustedthecoordinatesystem
usingaprojectionmatrix,youmustalsoapplyacameraview.Thefollowingexamplecodeshowshow
tomodifytheonDrawFrame()methodofaGLSurfaceView.Renderer
implementationtoapplyamodelviewandusethe
GLU.gluLookAt()utilitytocreateaviewingtranformation
whichsimulatesacameraposition.
Kotlin
overridefunonDrawFrame(gl:GL10){
...
gl.apply{
//SetGL_MODELVIEWtransformationmode
glMatrixMode(GL10.GL_MODELVIEW)
glLoadIdentity()//resetthematrixtoitsdefaultstate
}
//WhenusingGL_MODELVIEW,youmustsetthecameraview
GLU.gluLookAt(gl,0f,0f,-5f,0f,0f,0f,0f,1.0f,0.0f)
...
}
Java
publicvoidonDrawFrame(GL10gl){
...
//SetGL_MODELVIEWtransformationmode
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();//resetthematrixtoitsdefaultstate
//WhenusingGL_MODELVIEW,youmustsetthecameraview
GLU.gluLookAt(gl,0,0,-5,0f,0f,0f,0f,1.0f,0.0f);
...
}
ProjectionandcameraviewinOpenGLES2.0andhigher
IntheES2.0and3.0APIs,youapplyprojectionandcameraviewbyfirstaddingamatrixmember
tothevertexshadersofyourgraphicsobjects.Withthismatrixmemberadded,youcanthen
generateandapplyprojectionandcameraviewingmatricestoyourobjects.
Addmatrixtovertexshaders-Createavariablefortheviewprojectionmatrix
andincludeitasamultiplieroftheshader'sposition.Inthefollowingexamplevertexshader
code,theincludeduMVPMatrixmemberallowsyoutoapplyprojectionandcameraviewing
matricestothecoordinatesofobjectsthatusethisshader.
Kotlin
privatevalvertexShaderCode=
//Thismatrixmembervariableprovidesahooktomanipulate
//thecoordinatesofobjectsthatusethisvertexshader.
"uniformmat4uMVPMatrix;\n"+
"attributevec4vPosition;\n"+
"voidmain(){\n"+
//Thematrixmustbeincludedaspartofgl_Position
//NotethattheuMVPMatrixfactor*mustbefirst*inorder
//forthematrixmultiplicationproducttobecorrect.
"gl_Position=uMVPMatrix*vPosition;\n"+
"}\n"
Java
privatefinalStringvertexShaderCode=
//Thismatrixmembervariableprovidesahooktomanipulate
//thecoordinatesofobjectsthatusethisvertexshader.
"uniformmat4uMVPMatrix;\n"+
"attributevec4vPosition;\n"+
"voidmain(){\n"+
//Thematrixmustbeincludedaspartofgl_Position
//NotethattheuMVPMatrixfactor*mustbefirst*inorder
//forthematrixmultiplicationproducttobecorrect.
"gl_Position=uMVPMatrix*vPosition;\n"+
"}\n";
Note:Theexampleabovedefinesasingletransformationmatrix
memberinthevertexshaderintowhichyouapplyacombinedprojectionmatrixandcameraview
matrix.Dependingonyourapplicationrequirements,youmaywanttodefineseparateprojection
matrixandcameraviewingmatrixmembersinyourvertexshaderssoyoucanchangethem
independently.
Accesstheshadermatrix-Aftercreatingahookinyourvertexshadersto
applyprojectionandcameraview,youcanthenaccessthatvariabletoapplyprojectionand
cameraviewingmatrices.ThefollowingcodeshowshowtomodifytheonSurfaceCreated()methodofaGLSurfaceView.Rendererimplementationtoaccessthematrix
variabledefinedinthevertexshaderabove.
Kotlin
overridefunonSurfaceCreated(gl:GL10,config:EGLConfig){
...
muMVPMatrixHandle=GLES20.glGetUniformLocation(program,"uMVPMatrix")
...
}
Java
publicvoidonSurfaceCreated(GL10unused,EGLConfigconfig){
...
muMVPMatrixHandle=GLES20.glGetUniformLocation(program,"uMVPMatrix");
...
}
Createprojectionandcameraviewingmatrices-Generatetheprojectionand
viewingmatricestobeappliedthegraphicobjects.Thefollowingexamplecodeshowshowtomodify
theonSurfaceCreated()and
onSurfaceChanged()methodsofa
GLSurfaceView.Rendererimplementationtocreatecameraviewmatrixanda
projectionmatrixbasedonthescreenaspectratioofthedevice.
Kotlin
overridefunonSurfaceCreated(gl:GL10,config:EGLConfig){
...
//Createacameraviewmatrix
Matrix.setLookAtM(vMatrix,0,0f,0f,-3f,0f,0f,0f,0f,1.0f,0.0f)
}
overridefunonSurfaceChanged(gl:GL10,width:Int,height:Int){
GLES20.glViewport(0,0,width,height)
valratio:Float=width.toFloat()/height.toFloat()
//createaprojectionmatrixfromdevicescreengeometry
Matrix.frustumM(projMatrix,0,-ratio,ratio,-1f,1f,3f,7f)
}
Java
publicvoidonSurfaceCreated(GL10unused,EGLConfigconfig){
...
//Createacameraviewmatrix
Matrix.setLookAtM(vMatrix,0,0,0,-3,0f,0f,0f,0f,1.0f,0.0f);
}
publicvoidonSurfaceChanged(GL10unused,intwidth,intheight){
GLES20.glViewport(0,0,width,height);
floatratio=(float)width/height;
//createaprojectionmatrixfromdevicescreengeometry
Matrix.frustumM(projMatrix,0,-ratio,ratio,-1,1,3,7);
}
Applyprojectionandcameraviewingmatrices-Toapplytheprojectionand
cameraviewtransformations,multiplythematricestogetherandthensetthemintothevertex
shader.ThefollowingexamplecodeshowshowmodifytheonDrawFrame()methodofaGLSurfaceView.Rendererimplementationtocombine
theprojectionmatrixandcameraviewcreatedinthecodeaboveandthenapplyittothegraphic
objectstoberenderedbyOpenGL.
Kotlin
overridefunonDrawFrame(gl:GL10){
...
//Combinetheprojectionandcameraviewmatrices
Matrix.multiplyMM(vPMatrix,0,projMatrix,0,vMatrix,0)
//Applythecombinedprojectionandcameraviewtransformations
GLES20.glUniformMatrix4fv(muMVPMatrixHandle,1,false,vPMatrix,0)
//Drawobjects
...
}
Java
publicvoidonDrawFrame(GL10unused){
...
//Combinetheprojectionandcameraviewmatrices
Matrix.multiplyMM(vPMatrix,0,projMatrix,0,vMatrix,0);
//Applythecombinedprojectionandcameraviewtransformations
GLES20.glUniformMatrix4fv(muMVPMatrixHandle,1,false,vPMatrix,0);
//Drawobjects
...
}
ForacompleteexampleofhowtoapplyprojectionandcameraviewwithOpenGLES2.0,seetheDisplayinggraphicswithOpenGLES
class.
Shapefacesandwinding
InOpenGL,thefaceofashapeisasurfacedefinedbythreeormorepointsinthree-dimensional
space.Asetofthreeormorethree-dimensionalpoints(calledverticesinOpenGL)haveafrontface
andabackface.Howdoyouknowwhichfaceisfrontandwhichistheback?Goodquestion.The
answerhastodowithwinding,or,thedirectioninwhichyoudefinethepointsofashape.
Figure1.Illustrationofacoordinatelistwhichtranslatesintoa
counterclockwisedrawingorder.
Inthisexample,thepointsofthetrianglearedefinedinanordersuchthattheyaredrawnina
counterclockwisedirection.Theorderinwhichthesecoordinatesaredrawndefinesthewinding
directionfortheshape.Bydefault,inOpenGL,thefacewhichisdrawncounterclockwiseisthe
frontface.ThetriangleshowninFigure1isdefinedsothatyouarelookingatthefrontfaceof
theshape(asinterpretedbyOpenGL)andtheothersideisthebackface.
Whyisitimportanttoknowwhichfaceofashapeisthefrontface?Theanswerhastodowitha
commonlyusedfeatureofOpenGL,calledfaceculling.FacecullingisanoptionfortheOpenGL
environmentwhichallowstherenderingpipelinetoignore(notcalculateordraw)thebackfaceofa
shape,savingtime,memoryandprocessingcycles:
Kotlin
gl.apply{
//enablefacecullingfeature
glEnable(GL10.GL_CULL_FACE)
//specifywhichfacestonotdraw
glCullFace(GL10.GL_BACK)
}
Java
//enablefacecullingfeature
gl.glEnable(GL10.GL_CULL_FACE);
//specifywhichfacestonotdraw
gl.glCullFace(GL10.GL_BACK);
Ifyoutrytousethefacecullingfeaturewithoutknowingwhichsidesofyourshapesarethe
frontandback,yourOpenGLgraphicsaregoingtolookabitthin,orpossiblynotshowupatall.
So,alwaysdefinethecoordinatesofyourOpenGLshapesinacounterclockwisedrawingorder.
Note:ItispossibletosetanOpenGLenvironmenttotreatthe
clockwisefaceasthefrontface,butdoingsorequiresmorecodeandislikelytoconfuse
experiencedOpenGLdeveloperswhenyouaskthemforhelp.Sodon’tdothat.
OpenGLversionsanddevicecompatibility
TheOpenGLES1.0and1.1APIspecificationshavebeensupportedsinceAndroid1.0.
BeginningwithAndroid2.2(APIlevel8),theframeworksupportstheOpenGLES2.0API
specification.OpenGLES2.0issupportedbymostAndroiddevicesandisrecommendedfornew
applicationsbeingdevelopedwithOpenGL.OpenGLES3.0issupportedwithAndroid4.3
(APIlevel18)andhigher,ondevicesthatprovideanimplementationoftheOpenGLES3.0API.
ForinformationabouttherelativenumberofAndroid-powereddevices
thatsupportagivenversionofOpenGLES,seethe
OpenGLESversiondashboard.
GraphicsprogrammingwithOpenGLES1.0/1.1APIissignificantlydifferentthanusingthe2.0
andhigherversions.The1.xversionoftheAPIhasmoreconveniencemethodsandafixedgraphics
pipeline,whiletheOpenGLES2.0and3.0APIsprovidemoredirectcontrolofthepipelinethrough
useofOpenGLshaders.YoushouldcarefullyconsiderthegraphicsrequirementsandchoosetheAPI
versionthatworksbestforyourapplication.Formoreinformation,see
ChoosinganOpenGLAPIversion.
TheOpenGLES3.0APIprovidesadditionalfeaturesandbetterperformancethanthe2.0APIandis
alsobackwardcompatible.Thismeansthatyoucanpotentiallywriteyourapplicationtargeting
OpenGLES2.0andconditionallyincludeOpenGLES3.0graphicsfeaturesiftheyareavailable.For
moreinformationoncheckingforavailabilityofthe3.0API,see
CheckingOpenGLESversion
Texturecompressionsupport
TexturecompressioncansignificantlyincreasetheperformanceofyourOpenGLapplicationby
reducingmemoryrequirementsandmakingmoreefficientuseofmemorybandwidth.TheAndroid
frameworkprovidessupportfortheETC1compressionformatasastandardfeature,includinga
ETC1Utilutilityclassandtheetc1toolcompressiontool(locatedinthe
AndroidSDKat/tools/).ForanexampleofanAndroidapplicationthatuses
texturecompression,seetheCompressedTextureActivitycodesampleinAndroidSDK
(/samples//ApiDemos/src/com/example/android/apis/graphics/).
Caution:TheETC1formatissupportedbymostAndroiddevices,
butisnotguaranteedtobeavailable.TocheckiftheETC1formatissupportedonadevice,call
theETC1Util.isETC1Supported()method.
Note:TheETC1texturecompressionformatdoesnotsupporttextureswitha
transparency(alphachannel).Ifyourapplicationrequirestextureswithtransparency,youshould
investigateothertexturecompressionformatsavailableonyourtargetdevices.
TheETC2/EACtexturecompressionformatsareguaranteedtobeavailablewhenusingtheOpenGLES
3.0API.Thistextureformatoffersexcellentcompressionratioswithhighvisualqualityandthe
formatalsosupportstransparency(alphachannel).
BeyondtheETCformats,Androiddeviceshavevariedsupportfortexturecompressionbasedon
theirGPUchipsetsandOpenGLimplementations.Youshouldinvestigatetexturecompressionsupporton
thedevicesyouarearetargetingtodeterminewhatcompressiontypesyourapplicationshould
support.Inordertodeterminewhattextureformatsaresupportedonagivendevice,youmust
querythedeviceandreviewtheOpenGLextensionnames,
whichidentifywhattexturecompressionformats(andotherOpenGLfeatures)aresupportedbythe
device.Somecommonlysupportedtexturecompressionformatsareasfollows:
ATITC(ATC)-ATItexturecompression(ATITCorATC)isavailableona
widevarietyofdevicesandsupportsfixedratecompressionforRGBtextureswithandwithout
analphachannel.ThisformatmayberepresentedbyseveralOpenGLextensionnames,forexample:
GL_AMD_compressed_ATC_texture
GL_ATI_texture_compression_atitc
PVRTC-PowerVRtexturecompression(PVRTC)isavailableonawide
varietyofdevicesandsupports2-bitand4-bitperpixeltextureswithorwithoutanalphachannel.
ThisformatisrepresentedbythefollowingOpenGLextensionname:
GL_IMG_texture_compression_pvrtc
S3TC(DXTn/DXTC)-S3texturecompression(S3TC)hasseveral
formatvariations(DXT1toDXT5)andislesswidelyavailable.TheformatsupportsRGBtextureswith
4-bitalphaor8-bitalphachannels.TheseformatsarerepresentedbythefollowingOpenGLextension
name:
GL_EXT_texture_compression_s3tc
SomedevicesonlysupporttheDXT1formatvariation;thislimitedsupportisrepresentedbythe
followingOpenGLextensionname:
GL_EXT_texture_compression_dxt1
3DC-3DCtexturecompression(3DC)isalesswidelyavailableformatthat
supportsRGBtextureswithanalphachannel.ThisformatisrepresentedbythefollowingOpenGL
extensionname:
GL_AMD_compressed_3DC_texture
Warning:Thesetexturecompressionformatsarenot
supportedonalldevices.Supportfortheseformatscanvarybymanufactureranddevice.For
informationonhowtodeterminewhattexturecompressionformatsareonaparticulardevice,see
thenextsection.
Note:Onceyoudecidewhichtexturecompressionformatsyour
applicationwillsupport,makesureyoudeclaretheminyourmanifestusing
.UsingthisdeclarationenablesfilteringbyexternalservicessuchasGooglePlay,sothat
yourappisinstalledonlyondevicesthatsupporttheformatsyourapprequires.Fordetails,see
OpenGLmanifestdeclarations.
DeterminingOpenGLextensions
ImplementationsofOpenGLvarybyAndroiddeviceintermsoftheextensionstotheOpenGLESAPI
thataresupported.Theseextensionsincludetexturecompressions,buttypicallyalsoincludeother
extensionstotheOpenGLfeatureset.
Todeterminewhattexturecompressionformats,andotherOpenGLextensions,aresupportedona
particulardevice:
Runthefollowingcodeonyourtargetdevicestodeterminewhattexturecompression
formatsaresupported:
Kotlin
varextensions=gl.glGetString(GL10.GL_EXTENSIONS)
Java
Stringextensions=gl.glGetString(GL10.GL_EXTENSIONS);
Warning:Theresultsofthiscallvarybydevicemodel!You
mustrunthiscallonseveraltargetdevicestodeterminewhatcompressiontypesarecommonly
supported.
ReviewtheoutputofthismethodtodeterminewhatOpenGLextensionsaresupportedonthe
device.
AndroidExtensionPack(AEP)
TheAEPensuresthatyourapplicationsupportsastandardizedsetofOpenGLextensionsabove
andbeyond
thecoresetdescribedintheOpenGL3.1specification.Packagingtheseextensionstogether
encouragesaconsistentsetoffunctionalityacrossdevices,whileallowingdeveloperstotakefull
advantageofthelatestcropofmobileGPUdevices.
TheAEPalsoimprovessupportforimages,shaderstoragebuffers,andatomiccountersin
fragmentshaders.
ForyourapptobeabletousetheAEP,theapp'smanifestmustdeclarethattheAEPisrequired.
Inaddition,theplatformversionmustsupportit.
DeclaretheAEPrequirementinthemanifestasfollows:
ToverifythattheplatformversionsupportstheAEP,usethe
hasSystemFeature(String)method,passingin
FEATURE_OPENGLES_EXTENSION_PACKastheargument.Thefollowingcodesnippet
showsanexampleofhowtodoso:
Kotlin
vardeviceSupportsAEP:Boolean=
packageManager.hasSystemFeature(PackageManager.FEATURE_OPENGLES_EXTENSION_PACK)
Java
booleandeviceSupportsAEP=getPackageManager().hasSystemFeature
(PackageManager.FEATURE_OPENGLES_EXTENSION_PACK);
Ifthemethodreturnstrue,AEPissupported.
FormoreinformationabouttheAEP,visititspageatthe
KhronosOpenGLESRegistry.
CheckingtheOpenGLESversion
ThereareseveralversionsofOpenGLESavailableonAndroiddevices.Youcanspecifythe
minimumversionoftheAPIyourapplicationrequiresinyourmanifest,but
youmayalsowanttotakeadvantageoffeaturesinanewerAPIatthesametime.Forexample,
theOpenGLES3.0APIisbackward-compatiblewiththe2.0versionoftheAPI,soyoumaywantto
writeyourapplicationsothatitusesOpenGLES3.0features,butfallsbacktothe2.0APIifthe
3.0APIisnotavailable.
BeforeusingOpenGLESfeaturesfromaversionhigherthantheminimumrequiredinyour
applicationmanifest,yourapplicationshouldchecktheversionoftheAPIavailableonthedevice.
Youcandothisinoneoftwoways:
Attempttocreatethehigher-levelOpenGLEScontext(EGLContext)and
checktheresult.
Createaminimum-supportedOpenGLEScontextandchecktheversionvalue.
ThefollowingexamplecodedemonstrateshowtochecktheavailableOpenGLESversionbycreating
anEGLContextandcheckingtheresult.Thisexampleshowshowtocheckfor
OpenGLES3.0version:
Kotlin
privateconstvalEGL_CONTEXT_CLIENT_VERSION=0x3098
privateconstvalglVersion=3.0
privateclassContextFactory:GLSurfaceView.EGLContextFactory{
overridefuncreateContext(egl:EGL10,display:EGLDisplay,eglConfig:EGLConfig):EGLContext{
Log.w(TAG,"creatingOpenGLES$glVersioncontext")
returnegl.eglCreateContext(
display,
eglConfig,
EGL10.EGL_NO_CONTEXT,
intArrayOf(EGL_CONTEXT_CLIENT_VERSION,glVersion.toInt(),EGL10.EGL_NONE)
)//returnsnullif3.0isnotsupported
}
}
Java
privatestaticdoubleglVersion=3.0;
privatestaticclassContextFactoryimplementsGLSurfaceView.EGLContextFactory{
privatestaticintEGL_CONTEXT_CLIENT_VERSION=0x3098;
publicEGLContextcreateContext(
EGL10egl,EGLDisplaydisplay,EGLConfigeglConfig){
Log.w(TAG,"creatingOpenGLES"+glVersion+"context");
int[]attrib_list={EGL_CONTEXT_CLIENT_VERSION,(int)glVersion,
EGL10.EGL_NONE};
//attempttocreateaOpenGLES3.0context
EGLContextcontext=egl.eglCreateContext(
display,eglConfig,EGL10.EGL_NO_CONTEXT,attrib_list);
returncontext;//returnsnullif3.0isnotsupported;
}
}
IfthecreateContext()methodshowabovereturnsnull,yourcodeshouldcreateaOpenGL
ES2.0contextinsteadandfallbacktousingonlythatAPI.
ThefollowingcodeexampledemonstrateshowtochecktheOpenGLESversionbycreatingaminimum
supportedcontextfirst,andthencheckingtheversionstring:
Kotlin
//CreateaminimumsupportedOpenGLEScontext,thencheck:
gl.glGetString(GL10.GL_VERSION).also{
Log.w(TAG,"Version:$it")
}
//Theversionformatisdisplayedas:"OpenGLES."
//followedbyoptionalcontentprovidedbytheimplementation.
Java
//CreateaminimumsupportedOpenGLEScontext,thencheck:
Stringversion=gl.glGetString(GL10.GL_VERSION);
Log.w(TAG,"Version:"+version);
//Theversionformatisdisplayedas:"OpenGLES."
//followedbyoptionalcontentprovidedbytheimplementation.
Withthisapproach,ifyoudiscoverthatthedevicesupportsahigher-levelAPIversion,you
mustdestroytheminimumOpenGLEScontextandcreateanewcontextwiththehigher
availableAPIversion.
ChoosinganOpenGLAPIversion
OpenGLES1.0APIversion(andthe1.1extensions),version2.0,andversion3.0allprovidehigh
performancegraphicsinterfacesforcreating3Dgames,visualizationsanduserinterfaces.Graphics
progammingforOpenGLES2.0and3.0islargelysimilar,withversion3.0representingasuperset
ofthe2.0APIwithadditionalfeatures.ProgrammingfortheOpenGLES1.0/1.1APIversusOpenGLES
2.0and3.0differssignificantly,andsodevelopersshouldcarefullyconsiderthefollowing
factorsbeforestartingdevelopmentwiththeseAPIs:
Performance-Ingeneral,OpenGLES2.0and3.0providefastergraphics
performancethantheES1.0/1.1APIs.However,theperformancedifferencecanvarydependingon
theAndroiddeviceyourOpenGLapplicationisrunningon,duetodifferencesinhardware
manufacturer'simplementationoftheOpenGLESgraphicspipeline.
DeviceCompatibility-Developersshouldconsiderthetypesofdevices,
AndroidversionsandtheOpenGLESversionsavailabletotheircustomers.Formoreinformation
onOpenGLcompatibilityacrossdevices,seetheOpenGLversionsand
devicecompatibilitysection.
CodingConvenience-TheOpenGLES1.0/1.1APIprovidesafixedfunction
pipelineandconveniencefunctionswhicharenotavailableintheOpenGLES2.0or3.0APIs.
DeveloperswhoarenewtoOpenGLESmayfindcodingforversion1.0/1.1fasterandmore
convenient.
GraphicsControl-TheOpenGLES2.0and3.0APIsprovideahigherdegree
ofcontrolbyprovidingafullyprogrammablepipelinethroughtheuseofshaders.Withmore
directcontrolofthegraphicsprocessingpipeline,developerscancreateeffectsthatwouldbe
verydifficulttogenerateusingthe1.0/1.1API.
TextureSupport-TheOpenGLES3.0APIhasthebestsupportfortexture
compressionbecauseitguaranteesavailabilityoftheETC2compressionformat,whichsupports
transparency.The1.xand2.0APIimplementationsusuallyincludesupportforETC1,however
thistextureformatdoesnotsupporttransparencyandsoyoumusttypicallyprovideresources
inothercompressionformatssupportedbythedevicesyouaretargeting.Formoreinformation,
seeTexturecompressionsupport.
Whileperformance,compatibility,convenience,controlandotherfactorsmayinfluenceyour
decision,youshouldpickanOpenGLAPIversionbasedonwhatyouthinkprovidesthebestexperience
foryourusers.
ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates.
Lastupdated2021-10-27UTC.
[{
"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
LinkedIn
ConnectwiththeAndroidDeveloperscommunityonLinkedIn
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
English
BahasaIndonesia
Español–AméricaLatina
Português–Brasil
中文–简体
日本語
한국어