Android Debug Bridge (adb)

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

Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate with a device. The adb command facilitates a variety of device actions ... 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 AndroidDebugBridge(adb) AndroidDebugBridge(adb)isaversatilecommand-linetoolthatletsyoucommunicatewitha device.Theadbcommandfacilitatesavarietyofdeviceactions,suchasinstallinganddebugging apps,anditprovidesaccesstoaUnixshellthatyoucanusetorunavarietyofcommandsona device.Itisaclient-serverprogramthatincludesthreecomponents: Aclient,whichsendscommands.Theclientrunsonyourdevelopmentmachine.Youcan invokeaclientfromacommand-lineterminalbyissuinganadbcommand. Adaemon(adbd),whichrunscommandsonadevice.Thedaemonrunsasabackground processoneachdevice. Aserver,whichmanagescommunicationbetweentheclientandthedaemon.Theserver runsasabackgroundprocessonyourdevelopmentmachine. adbisincludedintheAndroidSDKPlatform-Toolspackage.Youcandownloadthis packagewiththeSDKManager,whichinstalls itatandroid_sdk/platform-tools/.OrifyouwantthestandaloneAndroidSDK Platform-Toolspackage,youcandownloadithere. ForinformationonconnectingadeviceforuseoverADB,includinghowtousetheConnection Assistanttotroubleshootcommonproblems,see Runappsonahardwaredevice. Howadbworks Whenyoustartanadbclient,theclientfirstcheckswhetherthereisanadbserver processalreadyrunning.Ifthereisn't,itstartstheserverprocess.Whentheserverstarts, itbindstolocalTCPport5037andlistensforcommandssentfromadbclients—alladb clientsuseport5037tocommunicatewiththeadbserver. Theserverthensetsupconnectionstoallrunningdevices. Itlocatesemulatorsbyscanningodd-numberedportsintherange 5555to5585,therangeusedbythefirst16emulators.Wheretheserverfindsanadb daemon(adbd),itsetsupaconnectiontothatport.Notethateachemulator usesapairofsequentialports—aneven-numberedportfor consoleconnectionsandanodd-numberedportforadbconnections.Forexample: Emulator1,console:5554 Emulator1,adb:5555 Emulator2,console:5556 Emulator2,adb:5557 andsoon... Asshown,theemulatorconnectedtoadbonport5555isthesameastheemulator whoseconsolelistensonport5554. Oncetheserverhassetupconnectionstoalldevices,youcanuseadbcommandsto accessthosedevices.Becausetheservermanagesconnectionstodevicesandhandles commandsfrommultipleadbclients,youcancontrolanydevicefromanyclient(or fromascript). Enableadbdebuggingonyourdevice TouseadbwithadeviceconnectedoverUSB,youmustenable USBdebugginginthedevicesystemsettings,under Developeroptions.TouseadbwithadeviceconnectedoverWi-Fi,see ConnecttoadeviceoverWi-Fi. OnAndroid4.2andhigher,theDeveloperoptionsscreenis hiddenbydefault.Tomakeitvisible,goto Settings>AboutphoneandtapBuildnumberseventimes.Returntotheprevious screentofindDeveloperoptionsatthebottom. Onsomedevices,theDeveloperoptionsscreenmightbelocatedornameddifferently. YoucannowconnectyourdevicewithUSB.Youcanverifythatyourdeviceis connectedbyexecutingadbdevicesfromthe android_sdk/platform-tools/directory.Ifconnected, you'llseethedevicenamelistedasa"device." Note:WhenyouconnectadevicerunningAndroid4.2.2orhigher, thesystemshowsadialogaskingwhethertoacceptanRSAkeythatallows debuggingthroughthiscomputer.Thissecuritymechanismprotectsuserdevicesbecauseitensures thatUSBdebuggingandotheradbcommandscannotbeexecutedunlessyou'reabletounlockthe deviceandacknowledgethedialog. FormoreinformationaboutconnectingtoadeviceoverUSB,read RunAppsonaHardwareDevice. ConnecttoadeviceoverWi-Fi(Android11+) Note:TheinstructionsbelowdonotapplytoWeardevicesrunning Android11.Seetheguideto debuggingaWearOSappfor moreinformation. Android11andhighersupportsdeployinganddebuggingyourappwirelesslyfromyourworkstation usingAndroidDebugBridge(adb).Forexample,youcandeployyourdebuggableapptomultiple remotedeviceswithoutphysicallyconnectingyourdeviceviaUSB.Thiseliminatestheneedto dealwithcommonUSBconnectionissues,suchasdriverinstallation. Beforeyoubeginusingwirelessdebugging,youmustcompletethefollowingsteps: Ensurethatyourworkstationanddeviceareconnectedtothesamewirelessnetwork. EnsurethatyourdeviceisrunningAndroid11orhigher.Formoreinformaton,see Check&updateyour Androidversion. EnsurethatyouhaveAndroidStudioBumblebee.Youcandownloadit here. Onyourworkstation,updatetothelatestversionofthe SDKPlatform-Tools. Tousewirelessdebugging,youmustpairyourdevicetoyourworkstationusingaQRCodeora pairingcode.Yourworkstationanddevicemustbeconnectedtothesamewirelessnetwork.To connecttoyourdevice,followthesesteps: Enabledeveloperoptionsonyourdevice: Onyourdevice,findtheBuildnumberoption.Youcanfindthisinthese locationsforthefollowingdevices: Device Setting GooglePixel Settings>Aboutphone>Buildnumber SamsungGalaxyS8andlater Settings>Aboutphone>Softwareinformation> Buildnumber LGG6andlater Settings>Aboutphone>Softwareinfo>Buildnumber HTCU11andlater Settings>About>Softwareinformation>More> BuildnumberorSettings>System>Aboutphone >Softwareinformation>More>Buildnumber OnePlus5Tandlater Settings>Aboutphone>Buildnumber TaptheBuildNumberoptionseventimesuntilyouseethemessageYouare nowadeveloper!Thisenablesdeveloperoptionsonyourphone. EnabledebuggingoverWi-Fionyourdevice: Onyourdevice,findDeveloperoptions.Youcanfindthisoptioninthese locationsforthefollowingdevices: Device Setting GooglePixel,OnePlus5Tandlater Settings>System>Developeroptions SamsungGalaxyS8andlater,LGG6andlater,HTCU11andlater Settings>Developeroptions InDeveloperoptions,scrolldowntotheDebuggingsectionandturnon Wirelessdebugging.OntheAllowwirelessdebuggingonthisnetwork?popup, selectAllow. OpenAndroidStudioandselectPairDevicesUsingWi-Fifromtherun configurationsdropdownmenu. Figure1.Runconfigurationsdropdownmenu. ThePairdevicesoverWi-Fiwindowpopsup,asshownbelow. Figure2.PopupwindowtopairdevicesusingQRcodeorpairing code Onyourdevice,taponWirelessdebuggingandpairyourdevice: Figure3.ScreenshotoftheWirelessdebuggingsettingon aGooglePixelphone. TopairyourdevicewithaQRcode,selectPairdevicewithQRcodeandscanthe QRcodeobtainedfromthePairdevicesoverWi-Fipopupabove. Topairyourdevicewithapairingcode,selectPairdevicewithpairingcodefrom thePairdevicesoverWi-Fipopupabove.Onyourdevice,selectPairusing pairingcodeandtakenoteofthesixdigitpincode.Onceyourdeviceappearsonthe PairdevicesoverWi-Fiwindow,youcanselectPairandenterthesixdigit pincodeshownonyourdevice. Figure4.Exampleofsixdigitpincodeentry. Afteryouarepaired,youcanattempttodeployyourapptoyourdevice. Topairadifferentdeviceortoforgetthisdeviceonyourworkstation,navigateto Wirelessdebuggingonyourdevice,taponyourworkstationnameunderPaired devices,andselectForget. Ifyouwanttoquicklyturnonandoffwirelessdebugging,youcanutilizethe Quicksettingsdevelopertilesfor Wirelessdebugging,foundinDeveloperOptions>Quicksettingsdeveloper tiles. Figure5.TheQuicksettingsdevelopertilessetting allowsyoutoquicklyturnwirelessdebuggingonandoff. Alternatively,toconnecttoyourdeviceviacommandlinewithoutAndroidStudio,follow thesesteps: Enabledeveloperoptionsonyourdevice,asdescribedabove. EnableWirelessdebuggingonyourdevice,asdescribedabove. Onyourworkstation,openaterminalwindowandnavigateto android_sdk/platform-tools. FindyourIPaddress,portnumber,andpairingcodebyselectingPairdevicewith pairingcode.TakenoteoftheIPaddress,portnumber,andpairingcodedisplayedon thedevice. Onyourworkstation'sterminal,runadbpairipaddr:port.UsetheIPaddress andportnumberfromabove. Whenprompted,enterthepairingcode,asshownbelow. Figure6.Amessageindicatesthatyourdevicehasbeensuccessfully paired. Resolvewirelessconnectionissues Ifyouarehavingissuesconnectingtoyourdevicewirelessly,youcantrythefollowing troubleshootingstepstoresolvetheissue. Checkifyourworkstationanddevicemeettheprerequisites Tomeettheprerequisitesforwirelessdebugging,ensurethat: Yourworkstationanddeviceareconnectedtothesamewirelessnetwork. YourdeviceisrunningAndroid11orhigher.Formoreinformation,see Check&updateyourAndroid version. YouhaveAndroidStudioBumblebee.Youcandownloadit here. Youhavethelatestversionofthe SDKPlatformToolson yourworkstation. Checkforotherknownissues ThefollowingisalistofcurrentknownissueswithwirelessdebugginginAndroidStudioand howtoresolvethem. Wi-Fiisnotconnecting:SomeWi-Finetworks,suchascorporateWi-Finetworks,may blockp2pconnectionsandnotallowyoutoconnectoverWi-Fi.Tryconnectingwithacableor anotherWi-Finetwork. ADBoverWi-Fisometimesturnsoffautomatically:Thiscanhappenifthedevice eitherswitchesWi-Finetworksordisconnectsfromthenetwork. ConnecttoadeviceoverWi-Fi(Android10andlower) Note:TheinstructionsbelowdonotapplytoWeardevicesrunning Android10(orlower).Seetheguideto debuggingaWearOSappfor moreinformation. adbusuallycommunicateswiththedeviceoverUSB,butyoucanalsouseadboverWi-Fi.To connectadevicerunningAndroid10orlower,therearesomeinitialsteps youmustdooverUSB,asdescribedbelow: ConnectyourAndroiddeviceandadbhostcomputer toacommonWi-Finetworkaccessibletoboth. Bewarethatnotallaccesspoints aresuitable;youmightneedtouseanaccesspoint whosefirewallisconfiguredproperlytosupportadb. Ifyouareconnecting toaWearOSdevice,turnoffBluetoothonthephonethat'spairedwiththedevice. ConnectthedevicetothehostcomputerwithaUSBcable. SetthetargetdevicetolistenforaTCP/IPconnectiononport5555. adbtcpip5555 DisconnecttheUSBcablefromthetargetdevice. FindtheIPaddressoftheAndroiddevice.Forexample,onaNexusdevice,youcanfind theIPaddressatSettings>Abouttablet (orAboutphone)>Status>IPaddress.Or, onaWearOSdevice,youcanfindtheIPaddressatSettings> Wi-FiSettings>Advanced>IPaddress. ConnecttothedevicebyitsIPaddress. adbconnectdevice_ip_address:5555 Confirmthatyourhostcomputerisconnectedtothetargetdevice: $adbdevices Listofdevicesattached device_ip_address:5555device You'renowgoodtogo! Iftheadbconnectioniseverlost: MakesurethatyourhostisstillconnectedtothesameWi-FinetworkyourAndroiddeviceis. Reconnectbyexecutingtheadbconnectstepagain. Orifthatdoesn'twork,resetyouradbhost: adbkill-server Thenstartoverfromthebeginning. Queryfordevices Beforeissuingadbcommands,itishelpfultoknowwhatdeviceinstancesareconnected totheadbserver.Youcangeneratealistofattacheddevicesusingthe devicescommand. adbdevices-l Inresponse,adbprintsthisstatusinformationforeachdevice: Serialnumber:Astringcreatedbyadbtouniquelyidentifythedevice byitsportnumber. Here'sanexampleserialnumber:emulator-5554 State:Theconnectionstateofthedevicecanbeoneofthefollowing: offline:Thedeviceisnotconnectedtoadborisnot responding. device:Thedeviceisnowconnectedtotheadbserver.Notethat thisstatedoesnotimplythattheAndroidsystemisfullybootedandoperationalbecause thedeviceconnectstoadb whilethesystemisstillbooting.However,afterboot-up,thisisthenormaloperational stateofandevice. nodevice:Thereisnodeviceconnected. Description:Ifyouincludethe-loption,thedevices commandtellsyouwhatthedeviceis.Thisinformationishelpfulwhenyouhavemultipledevices connectedsothatyoucantellthemapart. Thefollowingexampleshowsthedevicescommandanditsoutput.Therearethree devicesrunning.Thefirsttwolinesinthelistareemulators,andthethirdlineisahardware devicethatisattachedtothecomputer. $adbdevices Listofdevicesattached emulator-5556deviceproduct:sdk_google_phone_x86_64model:Android_SDK_built_for_x86_64device:generic_x86_64 emulator-5554deviceproduct:sdk_google_phone_x86model:Android_SDK_built_for_x86device:generic_x86 0a388e93deviceusb:1-1product:razormodel:Nexus_7device:flo Emulatornotlisted Theadbdevicescommandhasacorner-casecommandsequencethatcausesrunning emulator(s)tonotshowupintheadbdevicesoutputeventhough theemulator(s)arevisibleonyourdesktop.Thishappenswhenallofthefollowing conditionsaretrue: Theadbserverisnotrunning,and Youusetheemulatorcommandwiththe-portor -portsoptionwithanodd-numberedportvaluebetween5554and5584,and Theodd-numberedportyouchoseisnotbusysotheportconnectioncanbemadeatthe specifiedportnumber,orifitisbusy,theemulatorswitchesto anotherportthatmeetstherequirementsin2,and Youstarttheadbserverafteryoustarttheemulator. Onewaytoavoidthissituationistolettheemulatorchooseitsownports,anddon'trunmore than16emulatorsatonce.Anotherwayistoalwaysstarttheadbserverbeforeyouusethe emulatorcommand,asexplainedinthefollowingexamples. Example1:Inthefollowingcommandsequence,theadbdevicescommandstarts theadbserver,butthelistofdevicesdoesnotappear. Stoptheadbserverandenterthefollowingcommandsintheordershown.Fortheavdname,provide avalidavdnamefromyoursystem.Togetalistofavdnames,typeemulator-list-avds. Theemulatorcommandisintheandroid_sdk/toolsdirectory. $adbkill-server $emulator-avdNexus_6_API_25-port5555 $adbdevices Listofdevicesattached *daemonnotrunning.startingitnowonport5037* *daemonstartedsuccessfully* Example2:Inthefollowingcommandsequence,adbdevicesdisplaysthe listofdevicesbecausetheadbserverwasstartedfirst. Toseetheemulatorintheadbdevicesoutput,stoptheadbserver,andthenstart itagainafterusingtheemulatorcommandandbeforeusingthe adbdevicescommand,asfollows: $adbkill-server $emulator-avdNexus_6_API_25-port5557 $adbstart-server $adbdevices Listofdevicesattached emulator-5557device Formoreinformationaboutemulatorcommand-lineoptions, seeUsingCommandLine Parameters. Sendcommandstoaspecificdevice Ifmultipledevicesarerunning,youmustspecifythetargetdevice whenyouissuetheadbcommand.Tospecifythetarget,usethedevicescommand togettheserialnumberofthetarget.Onceyouhavetheserialnumber,usethe -soptionwiththeadbcommandstospecifytheserialnumber. Ifyou'regoingtoissuealotofadbcommands,youcansetthe $ANDROID_SERIALenvironmentvariabletocontaintheserialnumber instead.Ifyouuseboth -sand$ANDROID_SERIAL,-soverrides $ANDROID_SERIAL. Inthefollowingexample,thelistofattacheddevicesisobtained,andthentheserial numberofoneofthedevicesisusedtoinstallthehelloWorld.apkonthatdevice. $adbdevices Listofdevicesattached emulator-5554device emulator-5555device $adb-semulator-5555installhelloWorld.apk Note:Ifyouissueacommandwithoutspecifyingatargetdevice whenmultipledevicesareavailable,adbgeneratesanerror. Ifyouhavemultipledevicesavailable,butonlyoneisanemulator, usethe-eoptiontosendcommandstotheemulator.Likewise,iftherearemultiple devicesbutonlyonehardwaredeviceattached,usethe-doptiontosendcommandsto thehardwaredevice. Installanapp YoucanuseadbtoinstallanAPKonanemulatororconnecteddevice withtheinstallcommand: adbinstallpath_to_apk Youmustusethe-toptionwiththeinstall commandwhenyouinstallatestAPK.Formoreinformation, see-t. FormoreinformationabouthowtocreateanAPKfilethatyoucaninstallonanemulator/device instance,seeBuildandRunYourApp. Notethat,ifyouareusingAndroidStudio,youdonotneedtouseadbdirectlytoinstall yourappontheemulator/device.Instead,AndroidStudiohandlesthepackagingandinstallation oftheappforyou. Setupportforwarding Youcanusetheforwardcommandtosetuparbitraryportforwarding,which forwardsrequestsonaspecifichostporttoadifferentportonadevice. Thefollowingexamplesetsupforwardingofhostport6100todeviceport7100: adbforwardtcp:6100tcp:7100 Thefollowingexamplesetsupforwardingofhostport6100tolocal:logd: adbforwardtcp:6100local:logd Copyfilesto/fromadevice Usethepullandpushcommandstocopyfilesto andfromandevice.Unliketheinstallcommand, whichonlycopiesanAPKfiletoaspecificlocation,thepullandpush commandsletyoucopyarbitrarydirectoriesandfilestoanylocationinadevice. Tocopyafileordirectoryanditssub-directoriesfromthedevice, dothefollowing: adbpullremotelocal Tocopyafileordirectoryanditssub-directoriestothedevice, dothefollowing: adbpushlocalremote Replacelocalandremotewiththepathsto thetargetfiles/directoryonyourdevelopmentmachine(local)andonthe device(remote).Forexample: adbpushfoo.txt/sdcard/foo.txt Stoptheadbserver Insomecases,youmightneedtoterminatetheadbserverprocessandthenrestartit toresolvetheproblem(e.g.,ifadbdoesnotrespondtoacommand). Tostoptheadbserver,usetheadbkill-servercommand. Youcanthenrestarttheserverbyissuinganyotheradbcommand. Issuingadbcommands Youcanissueadbcommandsfromacommandlineonyourdevelopmentmachineorfromascript. Theusageis: adb[-d|-e|-sserial_number]command Ifthere'sonlyoneemulatorrunningoronlyonedeviceconnected,theadbcommandis senttothatdevicebydefault.Ifmultipleemulatorsarerunningand/ormultipledevicesare attached,youneedtousethe-d,-e,or-s optiontospecifythetargetdevicetowhichthecommandshouldbedirected. Youcanseeadetailedlistofallsupportedadbcommandsusingthefollowingcommand: adb--help Issueshellcommands Youcanusetheshellcommandtoissuedevicecommandsthroughadb,ortostartan interactiveshell. Toissueasinglecommandusetheshellcommandlikethis: adb[-d|-e|-sserial_number]shellshell_command Tostartaninteractiveshellonadeviceusetheshellcommandlikethis: adb[-d|-e|-sserial_number]shell Toexitaninteractiveshell,pressControl+Dortypeexit. Note: WithAndroidPlatform-Tools23andhigher,adbhandlesargumentsthesamewaythatthe ssh(1)commanddoes. Thischangehasfixedalotofproblemswith commandinjection andmakesit possibletonowsafelyexecutecommandsthatcontainshell metacharacters,suchas adbinstallLet\'sGo.apk.But,thischangemeansthattheinterpretation ofanycommandthatcontainsshellmetacharactershasalsochanged. Forexample,theadbshellsetpropfoo'ab'commandisnowanerrorbecausethe singlequotes(')areswallowedbythelocalshell,andthedevicesees adbshellsetpropfooab.Tomakethecommandwork,quotetwice, onceforthelocalshellandoncefortheremoteshell,thesameasyoudowith ssh(1).Forexample,adbshellsetpropfoo"'ab'". AndroidprovidesmostoftheusualUnixcommand-linetools.Foralistofavailabletools,use thefollowingcommand: adbshellls/system/bin Helpisavailableformostofthecommandsviathe--helpargument. Manyoftheshellcommandsareprovidedby toybox. Generalhelpapplicabletoalltoyboxcommandsisavailableviatoybox--help. SeealsoLogcatCommand-LineToolwhichisuseful formonitoringthesystemlog. Callactivitymanager(am) Withinanadbshell,youcanissuecommandswiththeactivitymanager(am)toolto performvarioussystemactions,suchasstartanactivity,force-stopaprocess, broadcastanintent,modifythedevicescreenproperties,andmore.Whileinashell, thesyntaxis: amcommand Youcanalsoissueanactivitymanagercommanddirectlyfromadb withoutenteringaremoteshell.Forexample: adbshellamstart-aandroid.intent.action.VIEW Table2.Availableactivitymanagercommands Command Description start[options]intent StartanActivityspecifiedby intent.Seethe Specificationforintentarguments. Optionsare: -D:Enabledebugging. -W:Waitforlaunchtocomplete. --start-profilerfile:Startprofilerandsendresultsto file. -Pfile:Like--start-profiler, butprofilingstopswhentheappgoesidle. -Rcount:Repeattheactivitylaunchcount times.Priortoeachrepeat, thetopactivitywillbefinished. -S:Forcestopthetargetappbeforestartingtheactivity. --opengl-trace:EnabletracingofOpenGLfunctions. --useruser_id|current:Specifywhichusertorunas;ifnot specified,thenrunasthecurrentuser. startservice[options]intent StarttheServicespecifiedby intent.Seethe Specificationforintentarguments. Optionsare: --useruser_id|current:Specifywhichusertorunas;ifnot specified,thenrunasthecurrentuser. force-stoppackage Forcestopeverythingassociatedwithpackage(theapp'spackagename). kill[options]package Killallprocessesassociatedwithpackage (theapp'spackagename).Thiscommandkillsonly processesthataresafetokillandthatwillnotimpacttheuser experience. Optionsare: --useruser_id|all|current:Specifyuserwhoseprocessestokill; allusersifnotspecified. kill-all Killallbackgroundprocesses. broadcast[options]intent Issueabroadcastintent.Seethe Specificationforintentarguments. Optionsare: [--useruser_id|all|current]:Specifywhichusertosendto;ifnot specifiedthensendtoallusers. instrument[options]component Startmonitoringwithan Instrumentationinstance. Typicallythetargetcomponent istheformtest_package/runner_class.Optionsare: -r:Printrawresults(otherwisedecode report_key_streamresult).Usewith [-eperftrue]togeneraterawoutputforperformancemeasurements. -enamevalue:Setargumentname tovalue. Fortestrunnersacommonformis -etestrunner_flagvalue[,value...]. -pfile:Writeprofilingdatatofile. -w:Waitforinstrumentationtofinishbeforereturning.Requiredfor testrunners. --no-window-animation:Turnoffwindowanimationswhilerunning. --useruser_id|current:Specifywhichuserinstrumentationrunsin; currentuserifnotspecified. profilestartprocessfile Startprofileronprocess,writeresultstofile. profilestopprocess Stopprofileronprocess. dumpheap[options]processfile Dumptheheapofprocess,writetofile.Optionsare: --user[user_id|current]:Whensupplyingaprocessname, specifyuserofprocesstodump;usescurrentuserifnotspecified. -n:Dumpnativeheapinsteadofmanagedheap. set-debug-app[options]package Setapppackagetodebug.Optionsare: -w:Waitfordebuggerwhenappstarts. --persistent:Retainthisvalue. clear-debug-app Clearthepackageprevioussetfordebuggingwithset-debug-app. monitor[options] StartmonitoringforcrashesorANRs.Optionsare: --gdb:Startgdbservonthegivenportatcrash/ANR. screen-compat{on|off}package Controlscreen compatibilitymodeofpackage. display-size[reset|widthxheight] Overridedevicedisplaysize. Thiscommandishelpfulfortestingyourappacrossdifferentscreensizesbymimickingasmall screenresolutionusingadevicewithalargescreen,andviceversa. Example:amdisplay-size1280x800 display-densitydpi Overridedevicedisplaydensity. Thiscommandishelpfulfortestingyourappacrossdifferentscreendensitiesonhigh-density screenenvironmentusingalowdensityscreen,andviceversa. Example:amdisplay-density480 to-uriintent PrintthegivenintentspecificationasaURI.Seethe Specificationforintentarguments. to-intent-uriintent Printthegivenintentspecificationasanintent:URI.Seethe Specificationforintentarguments. Specificationforintentarguments Foractivitymanagercommandsthattakeanintentargument,youcan specifytheintentwiththefollowingoptions: Showall -aaction Specifytheintentaction,suchasandroid.intent.action.VIEW. Youcandeclarethisonlyonce. -ddata_uri SpecifytheintentdataURI,suchascontent://contacts/people/1. Youcandeclarethisonlyonce. -tmime_type SpecifytheintentMIMEtype,suchasimage/png. Youcandeclarethisonlyonce. -ccategory Specifyanintentcategory,suchasandroid.intent.category.APP_CONTACTS. -ncomponent Specifythecomponentnamewithpackagenameprefixtocreateanexplicitintent,such ascom.example.app/.ExampleActivity. -fflags Addflagstotheintent,assupportedby setFlags(). --esnextra_key Addanullextra.ThisoptionisnotsupportedforURIintents. -e|--esextra_keyextra_string_value Addstringdataasakey-valuepair. --ezextra_keyextra_boolean_value Addbooleandataasakey-valuepair. --eiextra_keyextra_int_value Addintegerdataasakey-valuepair. --elextra_keyextra_long_value Addlongdataasakey-valuepair. --efextra_keyextra_float_value Addfloatdataasakey-valuepair. --euextra_keyextra_uri_value AddURIdataasakey-valuepair. --ecnextra_keyextra_component_name_value Addacomponentname,whichisconvertedandpassedas aComponentNameobject. --eiaextra_keyextra_int_value[,extra_int_value...] Addanarrayofintegers. --elaextra_keyextra_long_value[,extra_long_value...] Addanarrayoflongs. --efaextra_keyextra_float_value[,extra_float_value...] Addanarrayoffloats. --grant-read-uri-permission IncludetheflagFLAG_GRANT_READ_URI_PERMISSION. --grant-write-uri-permission IncludetheflagFLAG_GRANT_WRITE_URI_PERMISSION. --debug-log-resolution IncludetheflagFLAG_DEBUG_LOG_RESOLUTION. --exclude-stopped-packages IncludetheflagFLAG_EXCLUDE_STOPPED_PACKAGES. --include-stopped-packages IncludetheflagFLAG_INCLUDE_STOPPED_PACKAGES. --activity-brought-to-front IncludetheflagFLAG_ACTIVITY_BROUGHT_TO_FRONT. --activity-clear-top IncludetheflagFLAG_ACTIVITY_CLEAR_TOP. --activity-clear-when-task-reset IncludetheflagFLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET. --activity-exclude-from-recents IncludetheflagFLAG_ACTIVITY_EXCLUDE_FROM_RECENTS. --activity-launched-from-history IncludetheflagFLAG_ACTIVITY_LAUNCHED_FROM_HISTORY. --activity-multiple-task IncludetheflagFLAG_ACTIVITY_MULTIPLE_TASK. --activity-no-animation IncludetheflagFLAG_ACTIVITY_NO_ANIMATION. --activity-no-history IncludetheflagFLAG_ACTIVITY_NO_HISTORY. --activity-no-user-action IncludetheflagFLAG_ACTIVITY_NO_USER_ACTION. --activity-previous-is-top IncludetheflagFLAG_ACTIVITY_PREVIOUS_IS_TOP. --activity-reorder-to-front IncludetheflagFLAG_ACTIVITY_REORDER_TO_FRONT. --activity-reset-task-if-needed IncludetheflagFLAG_ACTIVITY_RESET_TASK_IF_NEEDED. --activity-single-top IncludetheflagFLAG_ACTIVITY_SINGLE_TOP. --activity-clear-task IncludetheflagFLAG_ACTIVITY_CLEAR_TASK. --activity-task-on-home IncludetheflagFLAG_ACTIVITY_TASK_ON_HOME. --receiver-registered-only IncludetheflagFLAG_RECEIVER_REGISTERED_ONLY. --receiver-replace-pending IncludetheflagFLAG_RECEIVER_REPLACE_PENDING. --selector Requirestheuseof-dand-toptionstosettheintentdataandtype. URIcomponentpackage YoucandirectlyspecifyaURI,packagename,andcomponentnamewhennotqualified byoneoftheaboveoptions.Whenanargumentisunqualified,thetoolassumestheargument isaURIifitcontainsa":"(colon);itassumestheargumentisacomponentnameifit containsa"/"(forward-slash);otherwiseitassumestheargumentisapackagename. Callpackagemanager(pm) Withinanadbshell,youcanissuecommandswiththepackagemanager(pm)toolto performactionsandqueriesonapppackagesinstalledonthedevice.Whileinashell, thesyntaxis: pmcommand Youcanalsoissueapackagemanagercommanddirectlyfromadb withoutenteringaremoteshell.Forexample: adbshellpmuninstallcom.example.MyApp Table3.Availablepackagemanagercommands. Command Description listpackages[options]filter Printsallpackages,optionallyonly thosewhosepackagenamecontainsthetextinfilter.Options: -f:Seetheirassociatedfile. -d:Filtertoonlyshowdisabledpackages. -e:Filtertoonlyshowenabledpackages. -s:Filtertoonlyshowsystempackages. -3:Filtertoonlyshowthirdpartypackages. -i:Seetheinstallerforthepackages. -u:Alsoincludeuninstalledpackages. --useruser_id:Theuserspacetoquery. listpermission-groups Printsallknownpermissiongroups. listpermissions[options]group Printsallknownpermissions,optionallyonly thoseingroup.Options: -g:Organizebygroup. -f:Printallinformation. -s:Shortsummary. -d:Onlylistdangerouspermissions. -u:Listonlythepermissionsuserswillsee. listinstrumentation[options] Listalltestpackages.Options: -f:ListtheAPKfileforthetestpackage. target_package:Listtestpackagesforonlythisapp. listfeatures Printsallfeaturesofthesystem. listlibraries Printsallthelibrariessupportedbythecurrentdevice. listusers Printsallusersonthesystem. pathpackage PrintthepathtotheAPKofthegivenpackage. install[options]path Installsapackage(specifiedbypath)tothesystem.Options: -r:Reinstallanexistingapp,keepingitsdata. -t:AllowtestAPKstobeinstalled.GradlegeneratesatestAPKwhen youhaveonlyrunordebuggedyourapporhaveusedtheAndroidStudioBuild>Build APKcommand.IftheAPKisbuiltusingadeveloperpreviewSDK (ifthetargetSdkVersionis aletterinsteadofanumber),youmustincludethe -toption withtheinstallcommandifyouareinstallingatestAPK. -iinstaller_package_name:Specifytheinstallerpackagename. --install-locationlocation:Setstheinstalllocation usingoneofthefollowingvalues: 0:Usethedefaultinstalllocation 1:Installoninternaldevicestorage 2:Installonexternalmedia -f:Installpackageontheinternalsystemmemory. -d:Allowversioncodedowngrade. -g:Grantallpermissionslistedintheappmanifest. --fastdeploy:Quicklyupdateaninstalledpackagebyonlyupdatingthepartsof theAPKthatchanged. --incremental:InstallsenoughoftheAPKtolaunchtheapp whilestreamingtheremainingdatainthebackground.Tousethisfeature,youmustsignthe APK,createan APKSignatureSchemev4file, andplacethisfileinthesamedirectoryastheAPK.Thisfeatureisonlysupportedon certaindevices.Thisoptionforcesadbtousethefeatureorfailifitisnotsupported (withverboseinformationonwhyitfailed).Appendthe--waitoptiontowait untiltheAPKisfullyinstalledbeforegrantingaccesstotheAPK. --no-incrementalpreventsadbfromusingthisfeature. uninstall[options]package Removesapackagefromthesystem.Options: -k:Keepthedataandcachedirectoriesaroundafterpackageremoval. clearpackage Deletesalldataassociatedwithapackage. enablepackage_or_component Enablethegivenpackageorcomponent(writtenas"package/class"). disablepackage_or_component Disablethegivenpackageorcomponent(writtenas"package/class"). disable-user[options]package_or_component Options: --useruser_id:Theusertodisable. grantpackage_namepermission Grantapermissiontoanapp.OndevicesrunningAndroid6.0(APIlevel23) andhigher,thepermissioncanbeanypermissiondeclaredintheappmanifest.Ondevices runningAndroid5.1(APIlevel22)andlower,mustbeanoptionalpermissiondefinedbythe app. revokepackage_namepermission Revokeapermissionfromanapp.OndevicesrunningAndroid6.0(APIlevel 23)andhigher,thepermissioncanbeanypermissiondeclaredintheappmanifest.Ondevices runningAndroid5.1(APIlevel22)andlower,mustbeanoptionalpermissiondefinedbythe app. set-install-locationlocation Changesthedefaultinstalllocation.Locationvalues: 0:Auto:Letsystemdecidethebestlocation. 1:Internal:installoninternaldevicestorage. 2:External:onexternalmedia. Note:Thisisonlyintendedfordebugging;usingthiscancause appstobreakandotherundesireablebehavior. get-install-location Returnsthecurrentinstalllocation.Returnvalues: 0[auto]:Letssystemdecidethebestlocation 1[internal]:Installsoninternaldevicestorage 2[external]:Installsonexternalmedia set-permission-enforcedpermission[true|false] Specifieswhetherthegivenpermissionshouldbeenforced. trim-cachesdesired_free_space Trimcachefilestoreachthegivenfreespace. create-useruser_name Createanewuserwiththegivenuser_name, printingthenewuseridentifieroftheuser. remove-useruser_id Removetheuserwiththegivenuser_id, deletingalldataassociatedwiththatuser get-max-users Printsthemaximumnumberofuserssupportedbythedevice. Calldevicepolicymanager(dpm) Tohelpyoudevelopandtestyourdevicemanagement(orotherenterprise)apps,youcanissue commandstothedevicepolicymanager(dpm)tool.Usethetooltocontroltheactive adminapporchangeapolicy'sstatusdataonthedevice. Whileinashell,thesyntaxis: dpmcommand Youcanalsoissueadevicepolicymanagercommanddirectlyfromadb withoutenteringaremoteshell: adbshelldpmcommand Table4.Availabledevicepolicymanagercommands Command Description set-active-admin[options]component Setscomponentasactiveadmin. Optionsare: --useruser_id:Specifythetargetuser.Youcanalsopass --usercurrenttoselectthecurrentuser. set-profile-owner[options]component Setscomponentasactiveadminanditspackageasprofileownerforanexistinguser. Optionsare: --useruser_id:Specifythetargetuser.Youcan alsopass--usercurrenttoselectthecurrentuser. --namename:Specifythehuman-readableorganizationname. set-device-owner[options]component Setscomponentasactiveadminanditspackageasdeviceowner. Optionsare: --useruser_id:Specifythetargetuser.Youcanalsopass --usercurrenttoselectthecurrentuser. --namename:Specifythehuman-readableorganizationname. remove-active-admin[options]component Disablesanactiveadmin.Theappmustdeclare android:testOnly inthemanifest.Thiscommandalsoremovesdeviceandprofileowners. Optionsare: --useruser_id:Specifythetargetuser.Youcanalsopass --usercurrenttoselectthecurrentuser. clear-freeze-period-record Clearsthedevice'srecordofpreviously-setfreezeperiodsforsystemOTAupdates.Thisisuseful toavoidthedevice'sschedulingrestrictionswhendevelopingappsthatmanagefreeze-periods.See Managesystemupdates. SupportedondevicesrunningAndroid9.0(APIlevel28)andhigher. force-network-logs ForcesthesystemtomakeanyexistingnetworklogsreadyforretrievalbyaDPC.Ifthereare connectionorDNSlogsavailable,theDPCreceivesthe onNetworkLogsAvailable() callback.SeeNetworkactivitylogging. Thiscommandisrate-limited.SupportedondevicesrunningAndroid9.0(APIlevel28)andhigher. force-security-logs ForcesthesystemtomakeanyexistingsecuritylogsavailabletotheDPC.Iftherearelogs available,theDPCreceivesthe onSecurityLogsAvailable() callback.SeeLogenterprisedevice activity. Thiscommandisrate-limited.SupportedondevicesrunningAndroid9.0(APIlevel28)andhigher. Takeascreenshot Thescreencapcommandisashellutilityfortakingascreenshotofadevicedisplay. Whileinashell,thesyntaxis: screencapfilename Tousethescreencapfromthecommandline,typethefollowing: adbshellscreencap/sdcard/screen.png Here'sanexamplescreenshotsession,usingtheadbshelltocapturethescreenshotandthe pullcommandtodownloadthefilefromthedevice: $adbshell shell@$screencap/sdcard/screen.png shell@$exit $adbpull/sdcard/screen.png Recordavideo Thescreenrecordcommandisashellutilityforrecordingthedisplayofdevices runningAndroid4.4(APIlevel19)andhigher.TheutilityrecordsscreenactivitytoanMPEG-4 file.Youcanusethisfiletocreatepromotionalortrainingvideosorfordebuggingandtesting. Inashell,usethefollowingsyntax: screenrecord[options]filename Tousescreenrecordfromthecommandline,typethefollowing: adbshellscreenrecord/sdcard/demo.mp4 StopthescreenrecordingbypressingControl+C(Command+ConMac);otherwise,therecording stopsautomaticallyatthreeminutesorthetimelimitsetby--time-limit. Tobeginrecordingyourdevicescreen,runthescreenrecordcommandtorecord thevideo.Then,runthepullcommandtodownloadthevideofromthedevicetothehost computer.Here'sanexamplerecordingsession: $adbshell shell@$screenrecord--verbose/sdcard/demo.mp4 (pressControl+Ctostop) shell@$exit $adbpull/sdcard/demo.mp4 Thescreenrecordutilitycanrecordatanysupportedresolutionandbitrateyou request,whileretainingtheaspectratioofthedevicedisplay.Theutilityrecordsatthenative displayresolutionandorientationbydefault,withamaximumlengthofthreeminutes. Limitationsofthescreenrecordutility: Audioisnotrecordedwiththevideofile. VideorecordingisnotavailablefordevicesrunningWearOS. Somedevicesmightnotbeabletorecordattheirnativedisplayresolution. Ifyouencounterproblemswithscreenrecording,tryusingalowerscreenresolution. Rotationofthescreenduringrecordingisnotsupported.Ifthescreendoesrotateduring recording,someofthescreeniscutoffintherecording. Table5.screenrecordoptions Options Description --help Displayscommandsyntaxandoptions --sizewidthxheight Setsthevideosize:1280x720.Thedefaultvalueisthedevice'snative displayresolution(ifsupported),1280x720ifnot.Forbestresults,useasizesupported byyourdevice'sAdvancedVideoCoding(AVC)encoder. --bit-raterate Setsthevideobitrateforthevideo,inmegabitspersecond.Thedefaultvalueis4Mbps. Youcanincreasethebitratetoimprovevideoquality,butdoingsoresultsinlargermovie files.Thefollowingexamplesetstherecordingbitrateto6Mbps: screenrecord--bit-rate6000000/sdcard/demo.mp4 --time-limittime Setsthemaximumrecordingtime,inseconds.Thedefaultandmaximumvalueis180 (3minutes). --rotate Rotatestheoutput90degrees.Thisfeatureisexperimental. --verbose Displaysloginformationonthecommand-linescreen.Ifyoudonotsetthisoption, theutilitydoesnotdisplayanyinformationwhilerunning. ReadARTprofilesforapps StartinginAndroid7.0(APIlevel24)theAndroidRuntime(ART)collectsexecutionprofilesfor installedapps,whichareusedtooptimizeappperformance.Youmightwant toexaminethecollectedprofilestounderstandwhichmethodsaredeterminedtobefrequently executedandwhichclassesareusedduringappstartup. Toproduceatextformoftheprofileinformation,usethecommand: adbshellcmdpackagedump-profilespackage Toretrievethefileproduced,use: adbpull/data/misc/profman/package.txt Resettestdevices Ifyoutestyourappacrossmultipletestdevices,itmaybeusefultoresetyourdevicebetween tests,forexample,toremoveuserdataandresetthetestenvironment.Youcanperformafactory resetofatestdevicerunningAndroid10(APIlevel29)orhigherusingthe testharnessadbshellcommand,asshownbelow. adbshellcmdtestharnessenable Whenrestoringthedeviceusingtestharness,thedeviceautomaticallybacksuptheRSA keythatallowsdebuggingthroughthecurrentworkstationinapersistentlocation.Thatis,after thedeviceisreset,theworkstationcancontinuetodebugandissueadbcommandstothedevice withoutmanuallyregisteringanewkey. Additionally,tohelpmakeiteasierandmoresecuretokeeptestingyourapp,usingthe testharnesstorestoreadevicealsochangesthefollowingdevicesettings: Thedevicesetsupcertainsystemsettingssothatinitialdevicesetupwizardsdonotappear.Thatis,thedeviceentersastatefromwhichyoucanquicklyinstall,debug,andtestyourapp. Settings: Disableslockscreen Disablesemergencyalerts Disablesauto-syncforaccounts Disablesautomaticsystemupdates Other: Disablespreinstalledsecurityapps Ifyouappneedstodetectandadapttothedefaultsettingsofthetestharness command,youcanusethe ActivityManager.isRunningInUserTestHarness(). sqlite sqlite3startsthesqlitecommand-lineprogramforexaminingsqlitedatabases. Itincludescommandssuchas.dumptoprintthecontentsofatable,and .schematoprinttheSQLCREATEstatementforanexistingtable. YoucanalsoexecuteSQLitecommandsfromthecommandline,asshownbelow. $adb-semulator-5554shell $sqlite3/data/data/com.example.app/databases/rssitems.db SQLiteversion3.3.12 Enter".help"forinstructions Formoreinformation,seethesqlite3commandlinedocumentation. ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates. Lastupdated2022-03-30UTC. [{ "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 中文–简体 日本語 한국어



請為這篇文章評分?