adb shell dumpsys 使用命令和来源

一、概述

        adb shell dumpsys 在Android开发中经常要用到,平时都是零碎的积累,用到什么的时候就

记录下来,最近看了一些资料,发现可以汇总所有的命令,当带某个参数的时候,就可以查看具体

的信息, 本篇文章中还讲解了如何去找命令的源码和源头,供参考!

二、支持dumpsys命令的服务

1. 列出系统所有支持的dumpsys命令的服务


adb shell dumpsys | grep -i "DUMP OF SERVICE"

2. 支持dumpsys命令的服务

 adb shell service list
Found 203 services:
0	DockObserver: []
1	SurfaceFlinger: [android.ui.ISurfaceComposer]
2	VideoCallEngineService: []
3	accessibility: [android.view.accessibility.IAccessibilityManager]
4	account: [android.accounts.IAccountManager]
5	activity: [android.app.IActivityManager]
6	activity_task: [android.app.IActivityTaskManager]
7	adb: [android.debug.IAdbManager]
8	alarm: [android.app.IAlarmManager]
9	android.hardware.light.ILights/default: []
10	android.hardware.power.IPower/default: []
11	android.hardware.rebootescrow.IRebootEscrow/default: []
12	android.hardware.vibrator.IVibrator/default: []
13	android.os.UpdateEngineService: []
14	android.security.identity: [android.security.identity.ICredentialStoreFactory]
15	android.security.keystore: [android.security.keystore.IKeystoreService]
16	android.service.gatekeeper.IGateKeeperService: []
17	app_binding: []
18	app_integrity: [android.content.integrity.IAppIntegrityManager]
19	appops: [com.android.internal.app.IAppOpsService]
20	appwidget: [com.android.internal.appwidget.IAppWidgetService]
21	audio: [android.media.IAudioService]
22	auth: [android.hardware.biometrics.IAuthService]
23	autofill: [android.view.autofill.IAutoFillManager]
24	backup: [android.app.backup.IBackupManager]
25	battery: []
26	batteryproperties: [android.os.IBatteryPropertiesRegistrar]
27	batterystats: [com.android.internal.app.IBatteryStats]
28	binder_calls_stats: []
29	biometric: [android.hardware.biometrics.IBiometricService]
30	blob_store: [android.app.blob.IBlobStoreManager]
31	bluetooth_manager: [android.bluetooth.IBluetoothManager]
32	broadcastradio: [android.hardware.radio.IRadioService]
33	bugreport: [android.os.IDumpstate]
34	cacheinfo: []
35	carrier_config: [com.android.internal.telephony.ICarrierConfigLoader]
36	clipboard: [android.content.IClipboard]
37	color_display: [android.hardware.display.IColorDisplayManager]
38	companiondevice: [android.companion.ICompanionDeviceManager]
39	connectivity: [android.net.IConnectivityManager]
40	connmetrics: [android.net.IIpConnectivityMetrics]
41	consumer_ir: [android.hardware.IConsumerIrService]
42	content: [android.content.IContentService]
43	country_detector: [android.location.ICountryDetector]
44	cpuinfo: []
45	crossprofileapps: [android.content.pm.ICrossProfileApps]
46	dataloader_manager: [android.content.pm.IDataLoaderManager]
47	dbinfo: []
48	device_config: []
49	device_identifiers: [android.os.IDeviceIdentifiersPolicyService]
50	device_policy: [android.app.admin.IDevicePolicyManager]
51	deviceidle: [android.os.IDeviceIdleController]
52	devicestoragemonitor: []
53	diskstats: []
54	display: [android.hardware.display.IDisplayManager]
55	dnsresolver: []
56	dreams: [android.service.dreams.IDreamManager]
57	drm.drmManager: [drm.IDrmManagerService]
58	dropbox: [com.android.internal.os.IDropBoxManagerService]
59	dynamic_system: [android.os.image.IDynamicSystemService]
60	emergency_affordance: []
61	ethernet: [android.net.IEthernetManager]
62	external_vibrator_service: [android.os.IExternalVibratorService]
63	face: [android.hardware.face.IFaceService]
64	file_integrity: [android.security.IFileIntegrityService]
65	fingerprint: [android.hardware.fingerprint.IFingerprintService]
66	gfxinfo: []
67	gpu: [android.graphicsenv.IGpuService]
68	graphicsstats: [android.view.IGraphicsStats]
69	hardware_properties: [android.os.IHardwarePropertiesManager]
70	imms: [com.android.internal.telephony.IMms]
71	ims_doze_manager: [com.android.ims.internal.IImsDozeManager]
72	ims_ex: [com.android.ims.internal.IImsServiceEx]
73	ims_ut_ex: [com.android.ims.internal.IImsUtEx]
74	incident: []
75	incidentcompanion: [android.os.IIncidentCompanion]
76	incremental: [android.os.incremental.IIncrementalService]
77	input: [android.hardware.input.IInputManager]
78	input_method: [com.android.internal.view.IInputMethodManager]
79	inputflinger: [android.input.IInputFlinger]
80	installd: []
81	ions: [com.android.internal.telephony.IOns]
82	ions_ex: [com.android.unisoc.telephony.aidl.IOperatorNameHandler]
83	iphonesubinfo: [com.android.internal.telephony.IPhoneSubInfo]
84	ipsec: [android.net.IIpSecService]
85	irit: [com.android.unisoc.telephony.aidl.IRadioInteractor]
86	isms: [com.android.internal.telephony.ISms]
87	ismsEx: [com.android.internal.telephony.ISmsEx]
88	isub: [com.android.internal.telephony.ISub]
89	jobscheduler: [android.app.job.IJobScheduler]
90	launcherapps: [android.content.pm.ILauncherApps]
91	ledsrv: [android.os.ILedService]
92	lights: [android.hardware.lights.ILightsManager]
93	linkturbonative: []
94	location: [android.location.ILocationManager]
95	lock_settings: [com.android.internal.widget.ILockSettings]
96	looper_stats: []
97	manager: [android.os.IServiceManager]
98	media.audio_flinger: [android.media.IAudioFlinger]
99	media.audio_policy: [android.media.IAudioPolicyService]
100	media.camera: [android.hardware.ICameraService]
101	media.camera.proxy: [android.hardware.ICameraServiceProxy]
102	media.extractor: [android.IMediaExtractorService]
103	media.metrics: [android.media.IMediaMetricsService]
104	media.player: [android.media.IMediaPlayerService]
105	media.resource_manager: [android.media.IResourceManagerService]
106	media_projection: [android.media.projection.IMediaProjectionManager]
107	media_resource_monitor: [android.media.IMediaResourceMonitor]
108	media_router: [android.media.IMediaRouterService]
109	media_session: [android.media.session.ISessionManager]
110	meminfo: []
111	midi: [android.media.midi.IMidiManager]
112	mount: [android.os.storage.IStorageManager]
113	netd: []
114	netd_listener: [android.net.metrics.INetdEventListener]
115	netpolicy: [android.net.INetworkPolicyManager]
116	netstats: [android.net.INetworkStatsService]
117	network_adapter: [android.os.INetworkAdapterService]
118	network_management: [android.os.INetworkManagementService]
119	network_score: [android.net.INetworkScoreService]
120	network_stack: [android.net.INetworkStackConnector]
121	network_time_update_service: []
122	network_watchlist: [com.android.internal.net.INetworkWatchlistManager]
123	notification: [android.app.INotificationManager]
124	oem_lock: [android.service.oemlock.IOemLockService]
125	otadexopt: [android.content.pm.IOtaDexopt]
126	overlay: [android.content.om.IOverlayManager]
127	package: [android.content.pm.IPackageManager]
128	package_native: [android.content.pm.IPackageManagerNative]
129	performance_fw: [android.app.IPerformanceManagerInternal]
130	performancemanager: []
131	permission: [android.os.IPermissionController]
132	permissionmgr: [android.permission.IPermissionManager]
133	persistent_data_block: [android.service.persistentdata.IPersistentDataBlockService]
134	phone: [com.android.internal.telephony.ITelephony]
135	pinner: []
136	platform_compat: [com.android.internal.compat.IPlatformCompat]
137	platform_compat_native: [com.android.internal.compat.IPlatformCompatNative]
138	power: [android.os.IPowerManager]
139	power_ex: [android.os.sprdpower.IPowerManagerEx]
140	powerguru: [android.app.sprdpower.IPowerGuru]
141	print: [android.print.IPrintManager]
142	processinfo: [android.os.IProcessInfoService]
143	procstats: [com.android.internal.app.procstats.IProcessStats]
144	recovery: [android.os.IRecoverySystem]
145	restrictions: [android.content.IRestrictionsManager]
146	role: [android.app.role.IRoleManager]
147	rollback: [android.content.rollback.IRollbackManager]
148	runtime: []
149	scheduling_policy: [android.os.ISchedulingPolicyService]
150	search: [android.app.ISearchManager]
151	sec_key_att_app_id_provider: [android.security.keymaster.IKeyAttestationApplicationIdProvider]
152	sensor_privacy: [android.hardware.ISensorPrivacyManager]
153	sensorservice: [android.gui.SensorServer]
154	serial: [android.hardware.ISerialManager]
155	servicediscovery: [android.net.nsd.INsdManager]
156	settings: []
157	shortcut: [android.content.pm.IShortcutService]
158	simphonebook: [com.android.internal.telephony.IIccPhoneBookEx]
159	slice: [android.app.slice.ISliceManager]
160	soundtrigger: [com.android.internal.app.ISoundTriggerService]
161	soundtrigger_middleware: [android.media.soundtrigger_middleware.ISoundTriggerMiddlewareService]
162	sprd_power: []
163	sprdssense: [android.os.sprdpower.ISSense]
164	stats: [android.os.IStatsd]
165	statscompanion: [android.os.IStatsCompanionService]
166	statsmanager: [android.os.IStatsManagerService]
167	statusbar: [com.android.internal.statusbar.IStatusBarService]
168	storaged: [android.os.IStoraged]
169	storaged_pri: [android.os.storaged.IStoragedPrivate]
170	storagestats: [android.app.usage.IStorageStatsManager]
171	suspend_control: []
172	system_config: [android.os.ISystemConfig]
173	system_update: [android.os.ISystemUpdateManager]
174	telecom: [com.android.internal.telecom.ITelecomService]
175	telephony.registry: [com.android.internal.telephony.ITelephonyRegistry]
176	telephony_ims: [android.telephony.ims.aidl.IImsRcsController]
177	testharness: []
178	tethering: [android.net.ITetheringConnector]
179	textclassification: [android.service.textclassifier.ITextClassifierService]
180	textservices: [com.android.internal.textservice.ITextServicesManager]
181	thermalservice: [android.os.IThermalService]
182	time_detector: [android.app.timedetector.ITimeDetectorService]
183	time_zone_detector: [android.app.timezonedetector.ITimeZoneDetectorService]
184	trust: [android.app.trust.ITrustManager]
185	uimode: [android.app.IUiModeManager]
186	uni_carrierconfig: [com.android.internal.telephony.IUniCarrierConfigLoader]
187	uni_telephony: [com.android.internal.telephony.IUniTelephony]
188	updatelock: [android.os.IUpdateLock]
189	uri_grants: [android.app.IUriGrantsManager]
190	usagestats: [android.app.usage.IUsageStatsManager]
191	usb: [android.hardware.usb.IUsbManager]
192	user: [android.os.IUserManager]
193	vibrator: [android.os.IVibratorService]
194	voiceinteraction: [com.android.internal.app.IVoiceInteractionManagerService]
195	vold: []
196	wallpaper: [android.app.IWallpaperManager]
197	webviewupdate: [android.webkit.IWebViewUpdateService]
198	wifi: [android.net.wifi.IWifiManager]
199	wifinl80211: []
200	wifip2p: [android.net.wifi.p2p.IWifiP2pManager]
201	wifiscanner: [android.net.wifi.IWifiScanner]
202	window: [android.view.IWindowManager]

上面两条命令的结果相差不大,代表系统中可以通过adb shell dumpsys 服务名 去获取相应信息的命令

三、常用dumpsys命令

1. 查看AMS中所有信息

adb shell dumpsys activity

2. 查看内存信息

adb shell dumpsys meminfo

3. 查看电池信息

adb shell dumpsys battery

4. 显示alarm信息

adb shell dumpsys alarm

5. 显示内存状态

adb shell dumpsys procstats

6. 查看Window的相关信息

adb shell dumpsys window

7. 查看CPU相关信息

adb shell dumpsys cpuinfo

有些服务还可以带参数,如果不是很清楚细节,就加上 -h  参数

比如:

home@ubuntu:~$ adb shell dumpsys activity -h
Activity manager dump options:
  [-a] [-c] [-p PACKAGE] [-h] [WHAT] ...
  WHAT may be one of:
    a[ctivities]: activity stack state
    r[recents]: recent activities state
    b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state
    broadcast-stats [PACKAGE_NAME]: aggregated broadcast statistics
    i[ntents] [PACKAGE_NAME]: pending intent state
    p[rocesses] [PACKAGE_NAME]: process state
    o[om]: out of memory management
    perm[issions]: URI permission grant state
    prov[iders] [COMP_SPEC ...]: content provider state
    provider [COMP_SPEC]: provider client-side state
    s[ervices] [COMP_SPEC ...]: service state
    allowed-associations: current package association restrictions
    as[sociations]: tracked app associations
    exit-info [PACKAGE_NAME]: historical process exit information
    lmk: stats on low memory killer
    lru: raw LRU process list
    binder-proxies: stats on binder objects and IPCs
    settings: currently applied config settings
    service [COMP_SPEC]: service client-side state
    package [PACKAGE_NAME]: all state related to given package
    all: dump all activities
    top: dump the top activity
  WHAT may also be a COMP_SPEC to dump activities.
  COMP_SPEC may be a component name (com.foo/.myApp),
    a partial substring in a component name, a
    hex object identifier.
  -a: include all available server state.
  -c: include client state.
  -p: limit output to given package.
  --checkin: output checkin format, resetting data.
  --C: output checkin format, not resetting data.
  --proto: output dump in protocol buffer format.
  --autofill: dump just the autofill-related state of an activity

然后对照英文注释,带上不同的参数后,可以获取具体的信息:

adb shell dumpsys activity activities----------查看Activity组件信息
adb shell dumpsys activity services-----------查看Service组件信息
adb shell dumpsys activity providers----------产看ContentProvider组件信息
adb shell dumpsys activity broadcasts--------查看BraodcastReceiver信息
adb shell dumpsys activity intents--------------查看Intent信息
adb shell dumpsys activity processes---------查看进程信息
adb shell dumpsys activity intents -------- 查看 PendingIntentRecord 信息

四、命令来源

上述的这些命令都涉及到adb shell 命令,我们看看系统源头类

public abstract class BasicShellCommandHandler {

    //两个重要的方法:
    public abstract int onCommand(String cmd);

    public abstract void onHelp();

​​​​​​​}

onCommand方法 就是各个系统服务 adb shell 直接操作的方法:

比如 AMS 中的  启动一个activity

adb shell am start  -n com.DeviceTest/com.DeviceTest.VersionTestActivity

AMS 中的  启动一个service

adb shell am startservice -n com.tentent.mm/.plugin.acountsync.model.AcountAuthenticatorService
启动微信

AMS 中的 停止一个服务

adb shell am stopservice -n  xxxx

AMS 发送一个广播:

adb shell am broadcast  -a   android.intent.action.BOOT_COMPLETED  -n org.mazhuang.boottimemeasure/.BootCompletedReceiver
表示向 org.mazhuang.boottimemeasure/.BootCompletedReceiver 发送一个 BOOT_COMPLETED 

各系统服务中的 onShellCommand 方法:

最终都会复写onCommand 方法,比如AMS 中的 onCommand

public int onCommand(String cmd) {
        if (cmd == null) {
            return handleDefaultCommands(cmd);
        }
        final PrintWriter pw = getOutPrintWriter();
        try {
            switch (cmd) {
                case "start":
                case "start-activity":
                    return runStartActivity(pw);
                case "startservice":
                case "start-service":
                    return runStartService(pw, false);
                case "startforegroundservice":
                case "startfgservice":
                case "start-foreground-service":
                case "start-fg-service":
                    return runStartService(pw, true);
                case "stopservice":
                case "stop-service":
                    return runStopService(pw);
                case "broadcast":
                    return runSendBroadcast(pw);
                case "instrument":

到这里,就知道上述 adb shell  am 命令的是从哪里来的

我们在看看 PMS 相关的 命令:

adb shell pm uninstall com.example.MyApp    // 卸载一个应用

adb shell pm path :   查询package的安装位置

adb shell pm enable :使package或component可用。(如:pm enable "package/class")

adb shell pm disable :使package或component不可用。(如:pm disable "package/class")

adb shell pm list packages   :  查看所有应用列表

adb shell pm list packages -s   : 查看系统应用(system)列表

adb shell pm list packages -3  :  查看第三方应用

adb shell pm clear 包名  :   清除应用数据与缓存

同理,先进去 PMS中 看看 onShellCommand 方法, 然后最后也会复写 onCommand 方法:

public int onCommand(String cmd) {
        if (cmd == null) {
            return handleDefaultCommands(cmd);
        }

        final PrintWriter pw = getOutPrintWriter();
        try {
            switch (cmd) {
                case "path":
                    return runPath();
                case "validate":
                    return runValidate();
                case "dump":
                    return runDump();
                case "list":
                    return runList();
                case "resolve-activity":
                    return runResolveActivity();
                case "query-activities":
                    return runQueryIntentActivities();
                case "query-services":
                    return runQueryIntentServices();
                case "query-receivers":
                    return runQueryIntentReceivers();
                case "install":
                    return runInstall();

这样子,就找到命令的出处了,如果想知道原理,就继续去看每个方法中的实现逻辑。

同理,dumpsys 命令相关的源头,同样也可以查看每个服务中的 onHelp() 方法:

【备注】:只有部分服务有帮助打印信息

比如 我们想看看 电池服务(BatteryService)相关的信息,通过adb shell service list

找到电池的服务名:battery

adb shell dumpsys  battery -h   查看该命令的帮助信息:

Battery service (battery) commands:
  help
    Print this help text.
  set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>
    Force a battery property value, freezing battery state.
    -f: force a battery change broadcast be sent, prints new sequence.
  unplug [-f]
    Force battery unplugged, freezing battery state.
    -f: force a battery change broadcast be sent, prints new sequence.
  reset [-f]
    Unfreeze battery state, returning to current hardware values.
    -f: force a battery change broadcast be sent, prints new sequence.

然后我们去找 BatteryService.java 中的 onHelp() 方法,可以找到对应的源码,也就知道该命令的源头了,代码如下:

 class Shell extends ShellCommand {
        @Override
        public int onCommand(String cmd) {
            return onShellCommand(this, cmd);
        }

        @Override
        public void onHelp() {
            PrintWriter pw = getOutPrintWriter();
            dumpHelp(pw);
        }
    }

    static void dumpHelp(PrintWriter pw) {
        pw.println("Battery service (battery) commands:");
        pw.println("  help");
        pw.println("    Print this help text.");
        pw.println("  set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
        pw.println("    Force a battery property value, freezing battery state.");
        pw.println("    -f: force a battery change broadcast be sent, prints new sequence.");
        pw.println("  unplug [-f]");
        pw.println("    Force battery unplugged, freezing battery state.");
        pw.println("    -f: force a battery change broadcast be sent, prints new sequence.");
        pw.println("  reset [-f]");
        pw.println("    Unfreeze battery state, returning to current hardware values.");
        pw.println("    -f: force a battery change broadcast be sent, prints new sequence.");
    }

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>