Run apps on the Android Emulator

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

In Android Studio, create an Android Virtual Device (AVD) that the emulator can use to install and run your app. In the toolbar, select the AVD ... Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Games Language English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어 Signin AndroidStudio Download What'snew Userguide Preview Platform AndroidStudio Download What'snew Userguide Preview GooglePlay Jetpack Kotlin Docs Games MeetAndroidStudio OverviewInstallAndroidStudioMigratetoAndroidStudioConfiguretheIDEKeyboardshortcutsAccessibilityfeaturesUpdatetheIDEandtools Workflowbasics Manageyourproject OverviewCreateaprojectAboutPlayFeatureDelivery AddCandC++code OverviewInstallNDKandCMakeConfiguretheNDKforAGPConfigureCMakeLinkGradleCreateanAndroidlibrarySetupcontinuousintegration Writeyourapp OverviewAddcodefromatemplateFindsamplecodeAddamoduleforanewdeviceCreateaJavaclassortypeUseJava8languagefeaturesJava8languagesupporttableAddappresourcesBuildaUIwithLayoutEditorBuildanimationwithMotionEditorManageyourapp'sUIresourcesDesignappthemesAddmulti-densityvectorgraphicsCreateiconswithImageAssetStudioCreateresizablebitmaps(9-Patch)CreateWebPimagesLocalizetheUIAddAndroidapplinksConnecttoFirebaseImproveyourcodewithlintchecksImprovecodeinspectionwithannotationsToolsattributesreference Buildandrunyourapp Overview Runappsontheemulator OverviewCreateandmanagevirtualdevicesStarttheemulatorfromthecommandlineSendemulatorconsolecommandsSetupemulatornetworkingConfigurehardwareaccelerationEmulatorfeaturecomparisonTroubleshootemulator Runappsonahardwaredevice OverviewInstallOEMUSBdriversGettheGoogleUSBdriverCreaterun/debugconfigurationsBuildyourappfromthecommandline Configureyourbuild OverviewConfiguretheappmoduleAddbuilddependenciesConfigurebuildvariantsUsetheAndroidGradlepluginUpgradeAssistantGradletipsandrecipesMigratetoKotlinscript Optimizeyourbuildspeed OverviewTroubleshootbuildperformanceProfileyourbuildUsetheMavenPublishpluginManagemanifestfilesShrinkyourappEnablemultidexExtendtheAndroidGradlepluginIntegrateacustomC/C++buildsystem Debugyourapp OverviewConfiguredeveloperoptionsWriteandviewlogsAnalyzeastacktraceDebugyourlayoutwithLayoutInspectorInspectnetworktrafficwiththeNetworkInspectorDebugyourdatabasewiththeDatabaseInspectorDebugyourWorkManagerWorkerswithBackgroundTaskInspectorViewon-devicefilesDebugpre-builtAPKsTakeascreenshotRecordavideoCaptureandreadbugreportsAnalyzeyourbuildwithAPKAnalyzer Testyourapp OverviewTestinAndroidStudioTestfromthecommandlineAdvancedtestsetup Othertestingtools OverviewEspressoTestRecorderAppCrawlerMonkeytesting monkeyrunnerreference OverviewMonkeyDeviceMonkeyImageMonkeyRunner Profileyourapp Overview AndroidStudioprofilers Overview ProfileCPUactivity OverviewRecordtracesExporttracesImporttracesInspecttracesUIjankdetectionGeneratetracelogsbyinstrumentingyourappProfilememoryusageProfileenergyuseProfilewithpre-builtAPKs Benchmarkyourapp Overview Microbenchmark OverviewWritingabenchmarkProfilingabenchmarkInstrumentationargumentsBuildwithoutGradle Macrobenchmark WritingabenchmarkCapturethemetricsControlyourappInstrumentationargumentsContinuousIntegrationTrackandanalyzeperformanceImproveappperformanceusingBaselineProfiles Measureperformance OverviewExamples Publishyourapp OverviewPrepareforreleaseVersionyourappSignyourappUploadyourapp Publishyourlibrary OverviewPrepareforreleaseConfigurepublicationvariantsConfiguretestfixturesforpublicationUploadyourlibrary Commandlinetools Overviewaapt2adbapkanalyzerapksigneravdmanagerbmgrbundletoold8dmtracedumpdumpsysetc1tooljobbjetifier-standalonelogcatmksdcardretracesdkmanagersystraceperfettozipalignEnvironmentvariables Troubleshoot Knownissues Reportabug AndroidDevelopers AndroidStudio Userguide RunappsontheAndroidEmulator TheAndroidEmulatorsimulatesAndroiddevicesonyourcomputersothatyoucan testyourapplicationonavarietyofdevicesandAndroidAPIlevelswithout needingtohaveeachphysicaldevice. TheemulatorprovidesalmostallofthecapabilitiesofarealAndroiddevice. Youcansimulateincomingphonecallsandtextmessages,specifythelocationof thedevice,simulatedifferentnetworkspeeds,simulaterotationandother hardwaresensors,accesstheGooglePlayStore,andmuchmore. Testingyourappontheemulatorisinsomewaysfasterandeasierthandoingso onaphysicaldevice.Forexample,youcantransferdatafastertotheemulator thantoadeviceconnectedoverUSB. TheemulatorcomeswithpredefinedconfigurationsforvariousAndroidphone, tablet,WearOS,andAndroidTVdevices. Watchthefollowingvideoforanoverviewofsomeemulatorfeatures. Youcanusetheemulatormanuallythroughitsgraphicaluserinterfaceand programmaticallythroughthecommandlineandtheemulatorconsole.Fora comparisonofthefeaturesavailablethrougheachinterface,see ComparisonofAndroidEmulatortools. Requirementsandrecommendations TheAndroidEmulatorhasadditionalrequirementsbeyondthebasic systemrequirementsforAndroidStudio,whichare describedbelow: SDKTools26.1.1orhigher 64-bitprocessor Windows:CPUwithUG(unrestrictedguest)support HAXM6.2.1orlater(HAXM7.2.0orlaterrecommended) Theuseofhardwareaccelerationhas additionalrequirementsonWindowsandLinux: IntelprocessoronWindowsorLinux:IntelprocessorwithsupportforIntel VT-x,IntelEM64T(Intel64),andExecuteDisable(XD)Bitfunctionality AMDprocessoronLinux:AMDprocessorwithsupportforAMDVirtualization (AMD-V)andSupplementalStreamingSIMDExtensions3(SSSE3) AMDprocessoronWindows:AndroidStudio3.2orhigherandWindows10April 2018releaseorhigherfor WindowsHypervisorPlatform(WHPX) functionality ToworkwithAndroid8.1(APIlevel27)andhighersystemimages,anattached webcammusthavethecapabilitytocapture720pframes. Deprecationfor32-bitWindowssystems TheAndroidEmulatorwasdeprecatedinJune2019for32-bitWindowssystems. Supportforthe32-bitWindowsemulatorcontinuesuntilJune2020,including criticalbugfixes,butnonewfeatureswillbeadded.Ifyouareusingthe emulatorona32-bitWindowssystem,youshouldplantomigratetoa64-bit Windowssystem. Ifyouareusingtheemulatorona32-bitWindowssystem,youcanusethe SDKManagertoinstallthelatestversionof theemulatorfor32-bitWindows. Installtheemulator ToinstalltheAndroidEmulator,selecttheAndroidEmulatorcomponent intheSDKToolstaboftheSDKManager.Forinstructions,see UpdateyourtoolsusingtheSDKManager. Androidvirtualdevices EachinstanceoftheAndroidEmulatorusesanAndroidvirtualdevice (AVD)tospecifytheAndroidversionandhardwarecharacteristicsofthe simulateddevice.Toeffectivelytestyourapp,youshouldcreateanAVDthat modelseachdeviceonwhichyourappisdesignedtorun.Tocreateandmanage AVDs,usetheDeviceManager. EachAVDfunctionsasanindependentdevice,withitsownprivatestoragefor userdata,SDcard,andsoon.Bydefault,theemulatorstorestheuserdata,SD carddata,andcacheinadirectoryspecifictothatAVD.Whenyoulaunchthe emulator,itloadstheuserdataandSDcarddatafromtheAVDdirectory. RunanappontheAndroidEmulator YoucanrunanappfromanAndroidStudioproject,oryoucanrunanapp that'sbeeninstalledontheAndroidEmulatorasyouwouldrunanyappona device. TostarttheAndroidEmulatorandrunanappinyourproject: InAndroidStudio,createanAndroidVirtualDevice(AVD) thattheemulatorcanusetoinstallandrunyourapp. Inthetoolbar,selecttheAVDthatyouwanttorunyour apponfromthetargetdevicedrop-downmenu. ClickRun . Ifyoureceiveanerrororwarningmessageatthetopofthedialog,click thelinktocorrecttheproblemortogetmoreinformation. Someerrorsyoumustfixbeforeyoucancontinue,suchascertainHardware AcceleratedExecutionManager(IntelHAXM)errors. FormacOS,ifyouseeaWarning:NoDNSserversfounderrorwhen startingtheemulator,checktoseewhetheryouhavean /etc/resolv.conffile.Ifyoudon'thavethisfile,enterthe followingcommandinaterminalwindow: ln-s/private/var/run/resolv.conf/etc/resolv.conf WearOSpairingassistant TheWearOSpairingassistantguidesyoustep-by-stepthroughpairing WearOSemulatorswithphysicalorvirtualphonesdirectlyinAndroidStudio. TheassistantcanhelpyougettherightWearOSCompanionappinstalledon yourphoneandsetupaconnectionbetweenthetwodevices.Youcangetstarted bygoingtothedevicedropdown>WearOSEmulatorPairingAssistant. LaunchtheAndroidEmulatorwithoutfirstrunninganapp Tostarttheemulator: OpentheDeviceManager. Double-clickanAVD,orclickRun . TheAndroidEmulatorloads. Whiletheemulatorisrunning,youcanrunAndroidStudioprojectsandchoose theemulatorasthetargetdevice.YoucanalsodragoneormoreAPKsontothe emulatortoinstallthem,andthenrunthem. RuntheAndroidEmulatordirectlyinAndroidStudio TheAndroidEmulatorrunsdirectlyinsideAndroidStudiobydefault.Thisallows youtoconservescreenrealestate,navigatequicklybetweentheemulatorand theeditorwindowusinghotkeys,andorganizeyourIDEandemulatorworkflow inasingleapplicationwindow. Whentheemulatorisrunning,you'llhaveaccesstocommonemulatoractionslike rotating,andextendedcontroloptionslikenavigationplayback.Torunthe emulatorinaseparatewindowinsteadgoto File>Settings>Tools>Emulator(AndroidStudio>Preferences>Tools> EmulatoronmacOS)anddeselectLaunchinatoolwindow. Limitations Currently,youcan'tusetheemulator'sextendedcontrolswhenit'srunningin atoolwindow.Ifyourdevelopmentworkflowdependsheavilyontheextended controls,continuetousetheAndroidEmulatorasastandaloneapplication.In addition,certainvirtualdevices—suchasAndroidTVandfoldabledevices—can't beruninAndroidStudiobecausetheyhavespecializedUIrequirementsor importantfunctionsintheextendedcontrols. Installandaddfiles ToinstallanAPKfileontheemulateddevice,draganAPKfileontothe emulatorscreen.AnAPKInstallerdialogappears.Whentheinstallation completes,youcanviewtheappinyourappslist. Toaddafiletotheemulateddevice,dragthefileontotheemulatorscreen. Thefileisplacedinthe/sdcard/Download/directory.Youcan viewthefilefromAndroidStudiousingthe DeviceFileExplorer,or finditfromthedeviceusingtheDownloadsorFilesapp,depending onthedeviceversion. Snapshots AsnapshotisastoredimageofanAVD(AndroidVirtualDevice)thatpreserves theentirestateofthedeviceatthetimethatitwassaved–includingOS settings,applicationstate,anduserdata.Youcanreturntoasavedsystem statebyloadingasnapshotwheneveryouchoose,savingyouthetimeofwaiting fortheoperatingsystemandapplicationsonthevirtualdevicetorestart,as wellassavingyoutheeffortofbringingyourappbacktothestateatwhich youwanttoresumeyourtesting.Startingavirtualdevicebyloadingasnapshot ismuchlikewakingaphysicaldevicefromasleepstate,asopposedtobooting itfromapowered-offstate. ForeachAVD,youcanhaveoneQuickBootsnapshotandanynumberofgeneral snapshots. ThesimplestwaytotakeadvantageofsnapshotsistouseQuickBootsnapshots: Bydefault,eachAVDissettoautomaticallysaveaQuickBootsnapshotonexit andloadfromaQuickBootsnapshotonstart. ThefirsttimethatanAVDstarts,itmustperformacoldboot,justlike poweringonadevice.IfQuickBootisenabled,allsubsequentstartsloadfrom thespecifiedsnapshot,andthesystemisrestoredtothestatesavedinthat snapshot. Snapshotsarevalidforthesystemimage,AVDconfiguration,andemulator featureswithwhichtheyaresaved.Whenyoumakeachangeinanyofthese areas,allsnapshotsoftheaffectedAVDbecomeinvalid.Anyupdatetothe AndroidEmulator,systemimage,orAVDsettingsresetstheAVD'ssavedstate,so thenexttimeyoustarttheAVD,itmustperformacoldboot. Mostcontrolsforsaving,loading,andmanagingsnapshotsareinthe SnapshotsandSettingstabsintheSnapshotspaneintheemulator's Extendedcontrolswindow. YoucanalsocontroltheQuickBootoptionswhenstartingtheemulatorfromthe commandline. SaveQuickBootsnapshots WhenyoucloseanAVD,youcanspecifywhethertheemulatorautomaticallysaves asnapshotwhenyouclose.Tocontrolthisbehavior,proceedasfollows: Opentheemulator'sExtendedcontrolswindow. IntheSnapshotscategoryofcontrols,navigatetotheSettingstab. UsetheAuto-savecurrentstatetoQuickbootdrop-downmenutoselect oneofthefollowingoptions: Yes:AlwayssaveanAVDsnapshotwhenyouclosetheemulator.Thisis thedefault. Note:WhenautomaticQuickBootsnapshotsareenabled,youcanskipsaving aQuickBootsnapshotbyholdingtheShiftkeydownwhenyouclosethe emulator. No:Don'tsaveanAVDsnapshotwhenyouclosetheemulator. YourselectionappliesonlytotheAVDthatiscurrentlyopen.Youcannotsave snapshotswhileADBisoffline(suchaswhiletheAVDisstillbooting). Savegeneralsnapshots WhereasyoucanonlyhaveoneQuickBootsnapshotforeachAVD,youcanhave multiplegeneralsnapshotsforeachAVD. Tosaveageneralsnapshot,opentheemulator'sExtendedcontrols window,selecttheSnapshotscategory,andclicktheTakesnapshot buttoninthelower-rightcornerofthewindow. Toeditthenameanddescriptionoftheselectedsnapshot,clicktheedit buttonatthebottomofthewindow. Deleteasnapshot Tomanuallydeleteasnapshot,opentheemulator'sExtendedcontrols window,selecttheSnapshotscategory,selectthesnapshot,andclickthe delete buttonatthebottomofthewindow. Youcanalsospecifywhetheryouwouldliketheemulatortoautomaticallydelete snapshotswhentheybecomeinvalid,suchaswhentheAVDsettingsoremulator versionchange.Bydefault,theemulatorwillaskyouifyou'dlikeforitto deleteinvalidsnapshots.Youcanchangethissettingwiththe DeleteinvalidsnapshotsmenuintheSettingstaboftheSnapshots pane. Loadasnapshot Toloadasnapshotatanytime,opentheemulator'sExtendedcontrols window,selecttheSnapshotscategory,chooseasnapshot,andclickthe load buttonatthebottomofthewindow. InAndroidStudio3.2andhigher,eachdeviceconfigurationincludesa Bootoptioncontrolintheadvancedsettingsinthe VirtualDeviceConfigurationdialogwithwhichyou canspecifywhichsnapshottoloadwhenstartingthatAVD. DisableQuickBoot IfyouwanttodisableQuickBootsoyourAVDalwaysperformsacoldboot,do thefollowing: SelectTools>DeviceManagerandclickEditthisAVD . ClickShowAdvancedSettingsandscrolldowntoEmulatedPerformance. SelectColdboot. Coldbootonce InsteadofdisablingQuickBootcompletely,youcancoldbootjustonceby clickingColdBootNowfromtheAVD'sdrop-downmenuintheDeviceManager. Snapshotrequirementsandtroubleshooting SnapshotsdonotworkwithAndroid4.0.4(APIlevel15)orlower. SnapshotsdonotworkwithARMsystemimagesforAndroid8.0(APIlevel26). Iftheemulatorfailstobootfromasnapshot,selectColdBootNowfor theAVDintheDeviceManagerandsubmitabugreport. Snapshotsarenotreliablewhensoftwarerenderingisenabled.Ifsnapshots donotwork,clickEditthisAVD intheDeviceManagerandchangeGraphicstoeitherHardwareor Automatic. Loadingorsavingasnapshotisamemory-intensiveoperation.Ifyoudonot haveenoughRAMfreewhenaloadorsaveoperationbegins,theoperatingsystem mayswapthecontentsofRAMtotheharddisk,whichcangreatlyslowthe operation.Ifyouexperienceveryslowsnapshotloadsorsaves,youmaybeable tospeedtheseoperationsbyfreeingRAM.Closingapplicationsthatarenot essentialforyourworkisagoodwaytofreeRAM. Navigatetheemulatorscreen Useyourcomputermousepointertomimicyourfingeronthetouchscreen;select menuitemsandinputfields;andclickbuttonsandcontrols.Useyourcomputer keyboardtotypecharactersandenteremulatorshortcuts. Table1.Gesturesfornavigatingtheemulator Feature Description Swipethescreen Pointtothescreen,pressandholdtheprimarymousebutton,swipe acrossthescreen,andthenrelease. Draganitem Pointtoanitemonthescreen,pressandholdtheprimarymouse button,movetheitem,andthenrelease. Tap(touch) Pointtothescreen,presstheprimarymousebutton,andthenrelease. Forexample,youcouldclickatextfieldtostarttypinginit,selectan app,orpressabutton. Doubletap Pointtothescreen,presstheprimarymousebuttonquicklytwice, andthenrelease. Touchandhold Pointtoanitemonthescreen,presstheprimarymousebutton,hold, andthenrelease.Forexample,youcouldopenoptionsforanitem. Type Youcantypeintheemulatorbyusingyourcomputerkeyboard,orusing akeyboardthatpopsupontheemulatorscreen.Forexample,youcould typeinatextfieldafteryouselectedit. Pinchandspread PressingControl(CommandonMac)bringsupapinchgesture multi-touchinterface.Themouseactsasthefirstfinger,andacrossthe anchorpointisthesecondfinger.Dragthecursortomovethefirstpoint. Clickingtheleftmousebuttonactsliketouchingdownbothpoints,and releasingactslikepickingbothup. Verticalswipe Openaverticalmenuonthescreenandusethescrollwheel(mouse wheel)toscrollthroughthemenuitemsuntilyouseetheoneyouwant. Clickthemenuitemtoselectit. Performcommonactionsintheemulator Toperformcommonactionswiththeemulator,usethepanelontherightside, asdescribedintable2. Youcanusekeyboardshortcutstoperformmanycommonactionsintheemulator. Foracompletelistofshortcutsintheemulator,pressF1(Command+/onMac) toopentheHelppaneintheExtendedcontrols window. Table2.Commonactionsintheemulator Feature Description Close Closetheemulator. Minimize Minimizetheemulatorwindow. Resize Resizetheemulatorasyouwouldanyotheroperatingsystemwindow.The emulatormaintainsanaspectratioappropriateforyourdevice. Power Clicktoturnthescreenonoroff.Clickandholdtoturnthedevice onoroff. Volumeup Clicktoviewaslidercontrolandturnthevolumeup.Clickagainto turnitupmore,orusetheslidercontroltochangethevolume. Volumedown Clicktoviewaslidercontrolandturnthevolumedown.Clickagainto turnitdownmore,orusetheslidercontroltochangethevolume. Rotateleft Rotatethedevice90degreescounterclockwise. Rotateright Rotatethedevice90degreesclockwise. Takescreenshot Clicktotakeascreenshotofthedevice.Fordetails,see Screenshots. Enterzoommode Clicksothecursorchangestothezoomicon.Toexitzoommode,click thebuttonagain. Zoominandoutinzoommode: Left-clickthescreentozoominby25%,uptoamaximumofabout twicethescreenresolutionofthevirtualdevice. Right-clicktozoomout. Left-clickanddragtoselectabox-shapedareatozoominon. Right-clickanddragaselectionboxtoresettodefaultzoom. Topaninzoommode,holdControl(CommandonMac)whilepressingthe arrowkeysonthekeyboard. Totapthedevicescreeninzoommode,Control-click(Command-clickon Mac). Back Returntothepreviousscreen,orcloseadialogbox,anoptionsmenu, theNotificationspanel,ortheonscreenkeyboard. Home ReturntotheHomescreen. Overview (RecentApps) Taptoopenalistofthumbnailimagesofappsyou’veworkedwith recently.Toopenanapp,tapit.Toremoveathumbnailfromthelist, swipeitleftorright.Thisbuttonisn'tsupportedforWearOS. Fold Forfoldabledevices,foldthedevicetodisplayitssmallerscreen configuration. Unfold Forfoldabledevices,unfoldthedevicetodisplayitslargerscreen configuration. Menu PressControl+M(Command+MonMac)tosimulatetheMenubutton. More Clicktoaccessotherfeaturesandsettings,describedinthenext table. Screenrecording YoucanrecordvideoandaudiofromtheAndroidEmulatorandsavetherecording toaWebMoranimatedGIFfile. ThescreenrecordingcontrolsareintheScreenrecordtabofthe ExtendedControlswindow. Tip:Youcanalsoopenthescreenrecordingcontrolsby pressingControl+Shift+R(Command+Shift+RonMac). Tobeginscreenrecording,clicktheStartrecordingbuttonintheScreen recordtab.Tostoprecording,clickStoprecording. Controlsforplayingandsavingtherecordedvideoareatthebottomofthe Screenrecordtab.Tosavethevideo,chooseWebMorGIFfromthe menuatthebottomofthetabandclickSave. Youcanalsorecordandsaveascreenrecordingfromtheemulatorusingthe followingcommandonthecommandline: adbemuscreenrecordstart--time-limit10[pathtosavevideo]/sample_video.webm Screenshots Totakeascreenshotofthevirtualdevice,clicktheTakescreenshot button. TheemulatorcreatesaPNGfilewiththenameScreenshot_yyyymmdd-hhmmss.png usingtheyear,month,day,hour,minute,andsecondofthecapture.Forexample, Screenshot_20160219-145848.png. Bydefault,thescreenshotissavedonyourcomputerdesktop.Tochangethe locationtowhichscreenshotsaresaved,usetheScreenshotsavelocation controlintheSettingscategoryintheemulator's Extendedcontrolswindow. Youcanalsotakescreenshotsfromthecommandlinewitheitherofthefollowing commands: screenrecordscreenshot[destination-directory] adbemuscreenrecordscreenshot[destination-directory] Camerasupport Theemulatorsupportstheuseofbasiccamerafunctionalityonyourvirtual deviceforearlierAndroidversions.Android11andhighersupportsthe followingadditionalAndroidEmulatorcameracapabilities: RAWcapture YUVreprocessing Level3devices Logicalcamerasupport Emulatingsensororientationbyusingdatafromthesensormanager Applyingvideostabilizationbyreducinghandshakefrequency ApplyingedgeenhancementbyremovingtheupscalingusuallydoneintheYUVpipeline Concurrentcameras VirtualscenecameraandARCore Youcanusethevirtualscenecamerainavirtualenvironmenttoexperiment withaugmentedreality(AR)appsmadewith ARCore. Forinformationonusingthevirtualscenecameraintheemulator,see RunARappsinAndroidEmulator. Whenusingtheemulatorwithacameraapp,youcanimportanimageinPNGor JPEGformattobeusedwithinavirtualscene.Tochooseanimageforuseina virtualscene,clickAddimageintheCamera>Virtualsceneimagestab intheExtendedcontrolswindow.Thisfeaturecanbeusedtoimportcustom imagessuchasQRcodesforusewithanycamera-basedapp.Formoreinformation, see AddAugmentedImagestothescene. TestcommonARactionswithmacros YoucangreatlyreducethetimeittakestotestcommonARactionsbyusing thepresetmacrosintheemulator.Forexample,youcanuseamacrotoresetall thedevice'ssensorstotheirdefaultstate. Beforeusingmacros,followthestepsinRunARappsinAndroidEmulator tosetupthevirtualscenecameraforyourapp,runyourappontheemulator, andupdateARCore.Then,followthesestepstouseemulatormacros: WiththeemulatorrunningandyourappconnectedtoARCore,clickMore intheemulatorpanel. SelectRecordandPlayback>MacroPlayback. Chooseamacrothatyouwanttouse,thenclickPlay. Duringplayback,youcaninterruptamacrobyclickingStop. Extendedcontrols,settings,andhelp Usetheextendedcontrolstosenddata,changedeviceproperties,control apps,andmore.ToopentheExtendedcontrolswindow,clickMore intheemulatorpanel. Youcanusekeyboardshortcutstoperformmanyofthesetasks.Foracomplete listofshortcutsintheemulator,pressF1(Command+/onMac)toopentheHelp pane. Table3.Extendedcontrolsdetails Feature Description Location Theemulatorletsyousimulate"mylocation"information:thelocationwhere theemulateddeviceiscurrentlylocated.Forexample,ifyouclickMyLocation inGoogleMapsandthensendalocation,themapshowsit. Controlsforthedevice'slocationinformationareorganizedundertwo tabs:SinglepointsandRoutes. Singlepoints IntheSinglepointstab,youcanusetheGoogleMapswebviewto searchforpointsofinterest,justasyouwouldwhenusingGoogleMaps onaphoneorinabrowser.Whenyousearchfor(orclickon)alocationin themap,youcansavethelocationbyselectingSavepointnear thebottomofthemap.Allofyoursavedlocationsarelistedonthe rightsideoftheExtendedcontrolswindow. Tosettheemulatorslocationtothelocationyouhaveselectedonthe map,clicktheSetlocationbuttonnearthebottomrightofthe Extendedcontrolswindow. Routes SimilartotheSinglepointstab,theRoutestabprovides aGoogleMapswebviewthatyoucanusetocreatearoutebetweentwoor morelocations.Tocreateandsavearoute,dothefollowing: Inthemapview,usethetextfieldtosearchforthefirst destinationinyourroute. Selectthelocationfromthesearchresults. SelecttheNavigatebutton. Selectthestartingpointofyourroutefromthemap. (Optional)ClickAdddestinationtoaddmorestopsto yourroute. SaveyourroutebyclickingSaverouteinthemapview. SpecifyanamefortherouteandclickSave. Tosimulatetheemulatorfollowingtherouteyousaved,selecttheroute fromthelistofSavedroutesandclickPlayroutenear thebottomrightoftheExtendedcontrolswindow.Tostopthe simulation,clickStoproute. Tocontinuouslysimulatetheemulatorfollowingthespecifiedroute, enabletheswitchnexttoRepeatplayback.Tochangehowquicklythe emulatorfollowsthespecifiedroute,selectanoptionfromthePlayback speeddropdown. ImportGPXandKMLdata TousegeographicdatafromaGPSexchangeformat(GPX)orKeyhole MarkupLanguage(KML)file: ClickLoadGPX/KML. Inthefiledialog,selectafileonyourcomputerandclick Open. OptionallyselectaSpeed. ThespeeddefaultstotheDelayvalue(Speed1X).You canincreasethespeedbydouble(Speed2X),triple (Speed3X),andsoon. ClickRun. Displays Theemulatorallowsyoutodeployyourapptomultiple displays,whichsupportcustomizabledimensionsandcanhelpyoutestapps thatsupportmulti- windowandmulti- display.Whileavirtualdeviceisrunning,youcanadduptotwo additionaldisplaysasfollows: AddanotherdisplaybyclickingAddsecondarydisplay. FromthedropdownmenuunderSecondarydisplays,dooneofthefollowing: Selectoneofthepresetaspectratios. Selectcustomandsettheheight,width, anddpiforyourcustomdisplay. (Optional)ClickAddsecondarydisplaytoaddathird display. ClickApplychangestoaddthespecifieddisplay(s)tothe runningvirtualdevice. Cellular Theemulatorletsyousimulatevariousnetworkconditions.Youcan approximatethenetworkspeedfordifferentnetworkprotocols,oryoucan specifyFull,whichtransfersdataasquicklyasyour computerallows.Specifyinganetworkprotocolisalwaysslowerthan Full.Youcanalsospecifythevoiceanddatanetwork status,suchasroaming.ThedefaultsaresetintheAVD. SelectaNetworktype: GSM:GlobalSystemforMobileCommunications HSCSD:High-SpeedCircuit-SwitchedData GPRS:GenericPacketRadioService EDGE:EnhancedDataratesforGSMEvolution UMTS:UniversalMobileTelecommunicationsSystem HSPDA:High-SpeedDownlinkPacketAccess LTE:Long-TermEvolution Full(default):Usethenetworkasprovidedbyyourcomputer SelectaSignalstrength: None Poor Moderate(default) Good Great SelectaVoicestatus,Datastatus,or both: Home(default) Roaming Searching Denied(emergencycallsonly) Unregistered(off) Battery Youcansimulatethebatterypropertiesofadevicetoseehowyour appperformsunderdifferentconditions.ToselectaChargelevel, usetheslidercontrol. SelectaChargerconnectionvalue: None ACcharger SelectaBatteryhealthvalue: Good(default) Failed Dead Overvoltage Overheated Unknown SelectaBatterystatusvalue: Unknown Charging(default) Discharging Notcharging Full Phone Theemulatorletsyousimulateincomingphonecallsandtext messages. Toinitiateacalltotheemulator: SelectortypeaphonenumberintheFromfield. ClickCallDevice. OptionallyclickHoldCalltoputthecallonhold. Toendthecall,clickEndCall. Tosendatextmessagetotheemulator: SelectortypeaphonenumberintheFromfield. TypeamessageintheSMSmessagefield. ClickSendMessage. DirectionalPad IftheAVDhasthedirectionalpadenabledinthehardwareprofile, youcanusethedirectionalpadcontrolswiththeemulator.However,not alldevicescansupportthedirectionalpad;forexample,anAndroidwatch. Thebuttonssimulatethefollowingactions: Fingerprint Thiscontrolcansimulate10differentfingerprintscans.Youcan useittotestfingerprintintegrationinyourapp.Thisfeatureisdisabled forAndroid5.1(APIlevel22)andlower,andforWearOS. Tosimulateafingerprintscanonthevirtualdevice: Prepareanapptoreceiveafingerprint. SelectaFingerprintvalue. ClickTouchSensor. Virtualsensors>Accelerometer Thiscontrolletsyoutestyourappagainstchangesindeviceposition, orientation,orboth.Forexample,youcansimulategesturessuchastiltand rotation.Theaccelerometerdoesn'ttracktheabsolutepositionofthedevice: itjustdetectswhenachangeisoccurring.Thecontrolsimulatestheway accelerometerandmagnetometersensorswouldrespondwhenyoumoveorrotatea realdevice. Youmustenabletheaccelerometersensorinyour AVDtousethiscontrol. Thecontrolreports TYPE_ACCELEROMETER eventsonthex,y,andzaxis.Thesevaluesincludegravity.Forexample,if thedeviceissuspendedinouterspace,itwouldexperiencezeroacceleration (allofx,y,andzwillbe0).WhenthedeviceisonEarthandlayingscreen-up ontopofatable,theaccelerationis0,0,and9.8becauseofgravity. Thecontrolalsoreports TYPE_MAGNETIC_FIELD events,whichmeasuretheambientmagneticfieldonthex,yandzaxisin microteslas(μT). Torotatethedevicearoundthex,y,andzaxes,selectRotateanddo oneofthefollowing: AdjusttheYaw,Pitch,andRollslidersandobserve thepositionintheupperpane. Movethedevicerepresentationintheupperpaneandobservethe Yaw,Pitch,andRollandhowtheresulting accelerometervalueschange. SeeComputingthedevice'sorientation formoreinformationabouthowyaw,pitch,androllarecalculated. Tomovethedevicehorizontally(x)orvertically(y),selectMoveand dooneofthefollowing: AdjusttheXandYslidersandobservethepositioninthe upperpane. MovethedevicerepresentationintheupperpaneandobservetheX andYslidervaluesandhowtheresultingaccelerometervalueschange. Topositionthedeviceat0,90,180,or270degrees: IntheDevicerotationarea,selectabuttontochangethe rotation. Asyouadjustthedevice,theResultingvaluesfieldschange accordingly.Thesearethevaluesthatanappcanaccess. Formoreinformationaboutthesesensors,see Sensorsoverview, Motionsensors,and Positionsensors. Virtualsensors>Additionalsensors Theemulatorcansimulatevariouspositionandenvironmentsensors. Itletsyouadjustthefollowingsensorssoyoucantestthemwithyourapp: Ambienttemperature:Thisenvironmentalsensormeasuresambient airtemperature. Magneticfield:Thispositionsensormeasurestheambientmagneticfield ontheX,Y,andZaxes,respectively.Thevaluesareinmicroteslas(μT). Proximity:Thispositionsensormeasuresthedistancefromanobject; forexample,itcannotifyaphonethatafaceisclosetoittomakeacall. Theproximitysensormustbeenabledinyour AVDtousethis control. Light:Thisenvironmentalsensormeasuresilluminance.Thevalues areinluxunits. Pressure:Thisenvironmentalsensormeasuresambientairpressure. Thevaluesareinmillibar(hPa)units. RelativeHumidity:Thisenvironmentalsensormeasuresambient relativehumidity. Formoreinformationaboutthesesensors,see Sensorsoverview, Positionsensors,and Environmentsensors. Snapshots SeeSnapshots. Screenrecord SeeScreenrecording. Settings>General Emulatorwindowtheme:SelectLightorDark. Sendkeyboardshortcutsto:Bydefault,somekeyboard combinationswilltriggeremulatorcontrolshortcuts.Ifyou’redeveloping anappthatincludeskeyboardshortcuts,suchasonetargetedatdeviceswith Bluetoothkeyboards,youcanchangethissettingtosendallkeyboard inputtothevirtualdevice,includinginputthatwouldbeashortcutinthe emulator. Screenshotsavelocation:Clickthefoldericonto specifyalocationtosavescreenshotsoftheemulatorscreen. UsedetectedADBlocation:Ifyou'rerunningthe emulatorfromAndroidStudio,youshouldselectthissetting(thedefault). IfyouruntheemulatorfromoutsideAndroidStudioandwantittousea specificadbexecutable,deselectthisoptionandspecifytheSDKTools location.Ifthissettingisincorrect,featuressuchasscreenshotcapture anddrag-and-dropappinstallationwon'twork. Whentosendcrashreports:SelectAlways,Never,orAsk. Showwindowframearounddevice:Bydefault,emulatorswithdevice skinfilesareshownwithoutasurroundingwindowframe. Settings>Proxy Bydefault,theemulatorusestheAndroidStudioHTTPproxysettings, butthisscreenallowsyoutomanuallydefineanHTTPproxyconfiguration fortheemulator.Formoreinformation,seeUsingtheemulatorwitha proxy. Settings>Advanced OpenGLESrenderer:Selectthegraphicsaccelerationtype. (Thisisequivalanttothe-gpu commandlineoption). Autodetectbasedonhost: Lettheemulatorchoosehardwareorsoftwaregraphicsacceleration basedonyourcomputersetup.ItchecksifyourGPUdrivermatchesalistof knownfaultyGPUdrivers,andifitdoes,theemulatordisablesgraphics hardwareemulationandinsteadusestheCPU. ANGLE:(Windowsonly.)Use ANGLEDirect3Dtorendergraphicsinsoftware. SwiftShader:UseSwiftShadertorendergraphicsinsoftware. DesktopnativeOpenGL:UsetheGPUonyourhostcomputer.Thisoption istypicallythefastest.However,somedrivershaveissueswithrendering OpenGLgraphics,soitmightnotbeareliableoption. OpenGLESAPIlevel:SelectthemaximumversionofOpenGLESto useintheemulator. Autoselect:LettheemulatorchoosetheOpenGLESversionbased onthehostandguestsupport. Renderermaximum(uptoOpenGLES3.1):Attempttousethe maximumversionofOpenGLES. Compatibility(OpenGLES1.1/2.0):UsetheversionofOpenGLES thatiscompatiblewithmostenvironments. Help>KeyboardShortcuts Thispaneprovidesacompletelistofkeyboardshortcutsforthe emulator.Toopenthispanewhileworkingintheemulator,pressF1 (Command+/onMac).Fortheshortcutstowork,theSendkeyboard shortcutsoptionintheGeneralsettingspanemustbesetto Emulatorcontrols(default). Help>EmulatorHelp Togototheonlinedocumentationfortheemulator,click Documentation. Tofileabugagainsttheemulator,clickSendfeedback. Formoreinformation,seehowtoreportemulatorbugs. Help>About Seewhichadbporttheemulatoruses,aswellastheAndroidand emulatorversionnumbers.Comparethelatestavailableemulatorversion withyourversiontodetermineifyouhavethelatestsoftwareinstalled. Theemulatorserialnumberisemulator-adb_port, whichyoucanspecifyasanadbcommandlineoption,forexample. Wi-Fi WhenusinganAVDwithAPIlevel25orhigher,theemulatorprovidesasimulated Wi-Fiaccesspoint("AndroidWifi"),andAndroidautomaticallyconnectstoit. YoucandisableWi-Fiintheemulatorbyrunningtheemulatorwiththe command-lineparameter -feature-Wifi. Limitations TheAndroidEmulatordoesn'tincludevirtualhardwareforthefollowing: Bluetooth NFC SDcardinsert/eject Device-attachedheadphones USB ThewatchemulatorforWearOSdoesn'tprovidetheOverview(RecentApps) button,D-pad,andfingerprintsensor. ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates. Lastupdated2022-01-25UTC. [{ "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 Language English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어



請為這篇文章評分?