adb shell cmd

# このページの概要
adbでandroid端末の各種操作をするにあたり、android Nからは、新規に

```
$ adb shell cmd <service> <options>
```
というコマンド体系が追加された模様。

各種コマンドの役割、使い方を整理したい。
なお、現状、未実装なコマンドも多いようなので、随時更新する予定。


# 現状のservice一覧 (Nexus 5x, NPF10C, 2016/10/27現在)
各種serviceは存在しているが、実際のコマンドは未実装なものが多い

```
$ adb shell cmd -l
Currently running services:
  AtCmdFwd
  DockObserver
  SurfaceFlinger
  accessibility
  account
  activity
  alarm
  android.hardware.fingerprint.IFingerprintDaemon
  android.security.keystore
  appops
  appwidget
  assetatlas
  audio
  backup
  battery
  batteryproperties
  batterystats
  bluetooth_manager
  carrier_config
  clipboard
  cneservice
  commontime_management
  connectivity
  connectivity_metrics_logger
  connmetrics
  consumer_ir
  content
  contexthub_service
  country_detector
  cpuinfo
  dbinfo
  device_policy
  deviceidle
  devicestoragemonitor
  diskstats
  display
  display.qservice
  dns_listener
  dreams
  drm.drmManager
  dropbox
  ethernet
  fingerprint
  gfxinfo
  gpu
  graphicsstats
  hardware_properties
  imms
  ims
  input
  input_method
  iphonesubinfo
  isms
  isub
  jobscheduler
  launcherapps
  location
  lock_settings
  media.audio_flinger
  media.audio_policy
  media.camera
  media.camera.proxy
  media.codec
  media.drm
  media.extractor
  media.player
  media.radio
  media.resource_manager
  media.sound_trigger_hw
  media_projection
  media_router
  media_session
  meminfo
  midi
  mount
  netpolicy
  netstats
  network_management
  network_score
  network_time_update_service
  nfc
  notification
  otadexopt
  package
  permission
  persistent_data_block
  phone
  pinner
  power
  print
  processinfo
  procstats
  recovery
  restrictions
  rttmanager
  samplingprofiler
  scheduling_policy
  search
  sensorservice
  serial
  servicediscovery
  shortcut
  simphonebook
  sip
  soundtrigger
  statusbar
  telecom
  telephony.registry
  textservices
  trust
  uimode
  updatelock
  usagestats
  usb
  user
  vendor.qcom.PeripheralManager
  vibrator
  voiceinteraction
  vrmanager
  wallpaper
  webviewupdate
  wifi
  wifip2p
  wifiscanner
  window
```

# 各コマンドについて（随時、補足説明する予定、、、）

## adb shell cmd activity

```
Activity manager (activity) commands:
  help
    Print this help text.
  force-stop [--user <USER_ID> | all | current] <PACKAGE>
    Completely stop the given application package.
  kill [--user <USER_ID> | all | current] <PACKAGE>
    Kill all processes associated with the given application.
  kill-all
    Kill all processes that are safe to kill (cached, etc).
  write
    Write all pending state to storage.
  track-associations
    Enable association tracking.
  untrack-associations
    Disable and clear association tracking.
  is-user-stopped <USER_ID>
    Returns whether <USER_ID> has been stopped or not.
  lenient-background-check [<true|false>]
    Optionally controls lenient background check mode, returns current mode.
  get-uid-state <UID>
    Gets the process state of an app given its <UID>.
```


## adb shell cmd appops

```
AppOps service (appops) commands:
  help
    Print this help text.
  set [--user <USER_ID>] <PACKAGE> <OP> <MODE>
    Set the mode for a particular application and operation.
  get [--user <USER_ID>] <PACKAGE> [<OP>]
    Return the mode for a particular application and optional operation.
  query-op [--user <USER_ID>] <OP> [<MODE>]
    Print all packages that currently have the given op in the given mode.
  reset [--user <USER_ID>] [<PACKAGE>]
    Reset the given application or all applications to default modes.
  write-settings
    Immediately write pending changes to storage.
  read-settings
    Read the last written settings, replacing current state in RAM.
  options:
    <PACKAGE> an Android package name.
    <OP>      an AppOps operation.
    <MODE>    one of allow, ignore, deny, or default
    <USER_ID> the user id under which the package is installed. If --user is not
              specified, the current user is assumed.
```


## adb shell cmd battery
バッテリー状態のエミュレートとか？

```
Battery service (battery) commands:
  help
    Print this help text.
  set [ac|usb|wireless|status|level|invalid] <value>
    Force a battery property value, freezing battery state.
  unplug
    Force battery unplugged, freezing battery state.
  reset
    Unfreeze battery state, returning to current hardware values.
```

## adb shell cmd deviceidle
Doze状態の確認、Emulate、除外アプリの設定

```
Device idle controller (deviceidle) commands:
  help
    Print this help text.
  step [light|deep]
    Immediately step to next state, without waiting for alarm.
  force-idle [light|deep]
    Force directly into idle mode, regardless of other device state.
  force-inactive
    Force to be inactive, ready to freely step idle states.
  unforce
    Resume normal functioning after force-idle or force-inactive.
  get [light|deep|force|screen|charging|network]
    Retrieve the current given state.
  disable [light|deep|all]
    Completely disable device idle mode.
  enable [light|deep|all]
    Re-enable device idle mode after it had previously been disabled.
  enabled [light|deep|all]
    Print 1 if device idle mode is currently enabled, else 0.
  whitelist
    Print currently whitelisted apps.
  whitelist [package ...]
    Add (prefix with +) or remove (prefix with -) packages.
  tempwhitelist
    Print packages that are temporarily whitelisted.
  tempwhitelist [-u] [package ..]
    Temporarily place packages in whitelist for 10 seconds.
```

## adb shell cmd input

```
Input manager commands:
  help
    Print this help text.

  setlayout IME_ID IME_SUPTYPE_HASH_CODE DEVICE_DESCRIPTOR VENDOR_ID PRODUCT_ID KEYBOARD_DESCRIPTOR
    Sets a keyboard layout for a given IME subtype and input device pair
```


## adb shell cmd jobscheduler
Job操作

```
Job scheduler (jobscheduler) commands:
  help
    Print this help text.

  run [-f | --force] [-u | --user USER_ID] PACKAGE JOB_ID
    Trigger immediate execution of a specific scheduled job.
    Options:
      -f or --force: run the job even if technical constraints such as
         connectivity are not currently met
      -u or --user: specify which user's job is to be run; the default is
         the primary or system user
```

## adb shell cmd netpolicy
通信制御（UID単位で）

```
Network policy manager (netpolicy) commands:
  help
    Print this help text.

  add restrict-background-whitelist UID
    Adds a UID to the whitelist for restrict background usage.
  add restrict-background-blacklist UID
    Adds a UID to the blacklist for restrict background usage.
  get restrict-background
    Gets the global restrict background usage status.
  list wifi-networks [BOOLEAN]
    Lists all saved wifi networks and whether they are metered or not.
    If a boolean argument is passed, filters just the metered (or unmetered)
    networks.
  list restrict-background-whitelist
    Lists UIDs that are whitelisted for restrict background usage.
  list restrict-background-blacklist
    Lists UIDs that are blacklisted for restrict background usage.
  remove restrict-background-whitelist UID
    Removes a UID from the whitelist for restrict background usage.
  remove restrict-background-blacklist UID
    Removes a UID from the blacklist for restrict background usage.
  set metered-network ID BOOLEAN
    Toggles whether the given wi-fi network is metered.
  set restrict-background BOOLEAN
    Sets the global restrict background usage status.
```

## adb shell cmd otadexopt

```
OTA Dexopt (ota) commands:
  help
    Print this help text.

  prepare
    Prepare an OTA dexopt pass, collecting all packages.
  done
    Replies whether the OTA is complete or not.
  step
    OTA dexopt the next package.
  next
    Get parameters for OTA dexopt of the next package.
  cleanup
    Clean up internal states. Ends an OTA session.
```

    
## adb shell cmd package

```
Package manager (package) commands:
  help
    Print this help text.

  compile [-m MODE | -r REASON] [-f] [-c]
          [--reset] [--check-prof (true | false)] (-a | TARGET-PACKAGE)
    Trigger compilation of TARGET-PACKAGE or all packages if "-a".
    Options:
      -a: compile all packages
      -c: clear profile data before compiling
      -f: force compilation even if not needed
      -m: select compilation mode
          MODE is one of the dex2oat compiler filters:
            verify-none
            verify-at-runtime
            verify-profile
            interpret-only
            space-profile
            space
            speed-profile
            speed
            everything
      -r: select compilation reason
          REASON is one of:
            first-boot
            boot
            install
            bg-dexopt
            ab-ota
            nsys-library
            shared-apk
            forced-dexopt
            core-app
      --reset: restore package to its post-install state
      --check-prof (true | false): look at profiles when doing dexopt?
  list features
    Prints all features of the system.
  list instrumentation [-f] [TARGET-PACKAGE]
    Prints all test packages; optionally only those targeting TARGET-PACKAGE
    Options:
      -f: dump the name of the .apk file containing the test package
  list libraries
    Prints all system libraries.
  list packages [-f] [-d] [-e] [-s] [-3] [-i] [-u] [--user USER_ID] [FILTER]
    Prints all packages; optionally only those whose name contains
    the text in FILTER.
    Options:
      -f: see their associated file
      -d: filter to only show disabled packages
      -e: filter to only show enabled packages
      -s: filter to only show system packages
      -3: filter to only show third party packages
      -i: see the installer for the packages
      -u: also include uninstalled packages
  list permission-groups
    Prints all known permission groups.
  list permissions [-g] [-f] [-d] [-u] [GROUP]
    Prints all known permissions; optionally only those in GROUP.
    Options:
      -g: organize by group
      -f: print all information
      -s: short summary
      -d: only list dangerous permissions
      -u: list only the permissions users will see
  dump-profiles TARGET-PACKAGE
    Dumps method/class profile files to
    /data/misc/profman/TARGET-PACKAGE.txt
  resolve-activity [--brief] [--components] [--user USER_ID] INTENT
    Prints the activity that resolves to the given Intent.
  query-activities [--brief] [--components] [--user USER_ID] INTENT
    Prints all activities that can handle the given Intent.
  query-services [--brief] [--components] [--user USER_ID] INTENT
    Prints all services that can handle the given Intent.
  query-receivers [--brief] [--components] [--user USER_ID] INTENT
    Prints all broadcast receivers that can handle the given Intent.
  suspend [--user USER_ID] TARGET-PACKAGE
    Suspends the specified package (as user).
  unsuspend [--user USER_ID] TARGET-PACKAGE
    Unsuspends the specified package (as user).
  set-home-activity [--user USER_ID] TARGET-COMPONENT
    set the default home activity (aka launcher).

<INTENT> specifications include these flags and arguments:
    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
    [-c <CATEGORY> [-c <CATEGORY>] ...]
    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
    [--esn <EXTRA_KEY> ...]
    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
    [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
    [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]
    [--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> ...]
    [--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]
    [--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE>]
    [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]
        (mutiple extras passed as Integer[])
    [--eial <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]
        (mutiple extras passed as List<Integer>)
    [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]
        (mutiple extras passed as Long[])
    [--elal <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]
        (mutiple extras passed as List<Long>)
    [--efa <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]
        (mutiple extras passed as Float[])
    [--efal <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]
        (mutiple extras passed as List<Float>)
    [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
        (mutiple extras passed as String[]; to embed a comma into a string,
         escape it using "\,")
    [--esal <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
        (mutiple extras passed as List<String>; to embed a comma into a string,
         escape it using "\,")
    [--f <FLAG>]
    [--grant-read-uri-permission] [--grant-write-uri-permission]
    [--grant-persistable-uri-permission] [--grant-prefix-uri-permission]
    [--debug-log-resolution] [--exclude-stopped-packages]
    [--include-stopped-packages]
    [--activity-brought-to-front] [--activity-clear-top]
    [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
    [--activity-launched-from-history] [--activity-multiple-task]
    [--activity-no-animation] [--activity-no-history]
    [--activity-no-user-action] [--activity-previous-is-top]
    [--activity-reorder-to-front] [--activity-reset-task-if-needed]
    [--activity-single-top] [--activity-clear-task]
    [--activity-task-on-home]
    [--receiver-registered-only] [--receiver-replace-pending]
    [--receiver-foreground]
    [--selector]
    [<URI> | <PACKAGE> | <COMPONENT>]
```

### デフォルトactivityの確認
たとえば、複数のbrowserがインストールされた状態で、
"$ adb shell am start -a android.intent.action.VIEW http://xxx" というintentを投げたときにdefaultで起動するActivity

##### 標準アプリが設定されていたときの結果

```
$ adb shell cmd package resolve-activity -a android.intent.action.VIEW http://xxx
priority=0 preferredOrder=0 match=0x208000 specificIndex=-1 isDefault=true
ActivityInfo:
  name=com.google.android.apps.chrome.Main
  packageName=com.android.chrome

     ----------------------(snip)---------------------------------  
```

#### 標準アプリが設定されていなかったときの結果

```
$ adb shell cmd package resolve-activity -a android.intent.action.VIEW http://xxx
priority=0 preferredOrder=0 match=0x0 specificIndex=-1 isDefault=false
ActivityInfo:
  name=com.android.internal.app.ResolverActivity <------「起動アプリを選択するためのダイアログ」
  packageName=android

     ----------------------(snip)---------------------------------  
```

### Intent-filterを登録しているactivityの確認

たとえば、複数のbrowserがインストールされた状態で、
"$ adb shell am start -a android.intent.action.VIEW http://xxx" というintentを投げたときに、起動候補になりうるActivity

```
$ adb shell cmd package query-activities -a android.intent.action.VIEW http://xxx
3 activities found:
  Activity #0:
    priority=0 preferredOrder=0 match=0x208000 specificIndex=-1 isDefault=true
    ActivityInfo:
      name=com.google.android.apps.chrome.Main
      packageName=com.android.chrome

     ----------------------(snip)---------------------------------

  Activity #1:
    priority=0 preferredOrder=0 match=0x208000 specificIndex=-1 isDefault=true
    ActivityInfo:
      name=com.opera.mini.android.Browser
      packageName=com.opera.mini.native

     ----------------------(snip)---------------------------------

  Activity #2:
    priority=0 preferredOrder=0 match=0x208000 specificIndex=-1 isDefault=true
    ActivityInfo:
      name=org.mozilla.gecko.tabqueue.TabQueueDispatcher
      packageName=org.mozilla.firefox

     ----------------------(snip)---------------------------------

```


## adb shell cmd shortcut

```
Usage: cmd shortcut COMMAND [options ...]

cmd shortcut reset-throttling [--user USER_ID]
    Reset throttling for all packages and users

cmd shortcut reset-all-throttling
    Reset the throttling state for all users

cmd shortcut override-config CONFIG
    Override the configuration for testing (will last until reboot)

cmd shortcut reset-config
    Reset the configuration set with "update-config"

cmd shortcut clear-default-launcher [--user USER_ID]
    Clear the cached default launcher

cmd shortcut get-default-launcher [--user USER_ID]
    Show the default launcher

cmd shortcut unload-user [--user USER_ID]
    Unload a user from the memory
    (This should not affect any observable behavior)

cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE
    Remove all shortcuts from a package, including pinned shortcuts
```

## adb shell cmd statusbar
```
Status bar commands:
  help
    Print this help text.

  expand-notifications
    Open the notifications panel.

  expand-settings
    Open the notifications panel and expand quick settings if present.

  collapse
    Collapse the notifications and settings panel.

  add-tile COMPONENT
    Add a TileService of the specified component

  remove-tile COMPONENT
    Remove a TileService of the specified component

  click-tile COMPONENT
    Click on a TileService of the specified component
```


## adb shell cmd user

```
User manager (user) commands:
  help
    Print this help text.

  list
    Prints all users on the system.
```

## adb shell cmd webviewupdate
```
WebView updater commands:
  help
    Print this help text.

  enable-redundant-packages
    Allow a fallback package to be installed and enabled even when a
    more-preferred package is available. This command is useful when testing
    fallback packages.
  disable-redundant-packages
    Disallow installing and enabling fallback packages when a more-preferred
    package is available.
  set-webview-implementation PACKAGE
    Set the WebView implementation to the specified package.
```

# まだ未実装なもの（2016/10/27現在）
実行しても、

```
adb shell cmd <service>
No shell command implementation.
```
となるもの

## adb shell cmd AtCmdFwd
## adb shell cmd DockObserver
ドッキングステーション関連？
## adb shell cmd accessibility
ユーザ補助関連
## adb shell cmd account
googleアカウントなど、各種アカウント管理？
## adb shell cmd alarm
AlarmManager関連？
## adb shell cmd appwidget
## adb shell cmd assetatlas
## adb shell cmd audio
## adb shell cmd backup
バックアップマネージャー関連？
## adb shell cmd batterystats
## adb shell cmd bluetooth_manager
## adb shell cmd carrier_config
## adb shell cmd clipboard
## adb shell cmd cneservice
## adb shell cmd commontime_management
## adb shell cmd connectivity
## adb shell cmd connectivity_metrics_logger
## adb shell cmd connmetrics
## adb shell cmd consumer_ir
## adb shell cmd content
## adb shell cmd contexthub_service
## adb shell cmd country_detector
## adb shell cmd cpuinfo
## adb shell cmd dbinfo
## adb shell cmd device_policy
## adb shell cmd devicestoragemonitor
## adb shell cmd diskstats
## adb shell cmd display
## adb shell cmd display.qservice
## adb shell cmd dns_listener
## adb shell cmd dreams
## adb shell cmd dropbox
## adb shell cmd ethernet
## adb shell cmd fingerprint
## adb shell cmd graphicsstats
## adb shell cmd gfxinfo
## adb shell cmd hardware_properties
## adb shell cmd imms
## adb shell cmd ims
## adb shell cmd input_method
## adb shell cmd iphonesubinfo
## adb shell cmd isms
## adb shell cmd isub
## adb shell cmd launcherapps
## adb shell cmd location
## adb shell cmd lock_settings
## adb shell cmd media.camera.proxy
## adb shell cmd media_projection
## adb shell cmd media_router
## adb shell cmd media_session
## adb shell cmd meminfo
## adb shell cmd midi
## adb shell cmd mount
## adb shell cmd netstats
## adb shell cmd network_management
## adb shell cmd network_score
## adb shell cmd network_time_update_service
## adb shell cmd nfc
## adb shell cmd notification
## adb shell cmd permission
## adb shell cmd persistent_data_block
## adb shell cmd phone
## adb shell cmd pinner
## adb shell cmd power
## adb shell cmd print
## adb shell cmd processinfo
## adb shell cmd procstats
## adb shell cmd recovery
## adb shell cmd restrictions
## adb shell cmd rttmanager
## adb shell cmd samplingprofiler
## adb shell cmd scheduling_policy
## adb shell cmd search
## adb shell cmd serial
## adb shell cmd servicediscovery
## adb shell cmd simphonebook
## adb shell cmd sip
## adb shell cmd soundtrigger
## adb shell cmd telecom
## adb shell cmd telephony.registry
## adb shell cmd textservices
## adb shell cmd trust
## adb shell cmd uimode
## adb shell cmd updatelock
## adb shell cmd usagestats
## adb shell cmd usb
## adb shell cmd vibrator
## adb shell cmd voiceinteraction
## adb shell cmd vrmanager
## adb shell cmd wallpaper
## adb shell cmd wifi
## adb shell cmd wifip2p
## adb shell cmd wifiscanner
## adb shell cmd window

# 実装状況が（私に）わからないもの （2016/10/27現在）
実行しても、何の反応も無いもの

## adb shell cmd SurfaceFlinger
## adb shell cmd android.hardware.fingerprint.IFingerprintDaemon
## adb shell cmd android.security.keystore
## adb shell cmd batteryproperties
## adb shell cmd drm.drmManager
## adb shell cmd media.audio_flinger
## adb shell cmd media.audio_policy
## adb shell cmd media.camera
## adb shell cmd media.codec
## adb shell cmd media.drm
## adb shell cmd media.extractor
## adb shell cmd media.player
## adb shell cmd media.radio
## adb shell cmd media.resource_manager
## adb shell cmd media.sound_trigger_hw
## adb shell cmd sensorservice
## adb shell cmd vendor.qcom.PeripheralManager

# バグってる（？）もの（2016/10/27現在）
## adb shell cmd gpu
実行すると端末が再起動してしまう

# 端末側のコマンド実装について
[ShellCommand](https://android.googlesource.com/platform/frameworks/base/+/android-7.1.0_r4/core/java/android/os/ShellCommand.java "ShellCommand")をextendsしたクラスで実現する模様



## 例：ActivityManagerShellCommand
https://android.googlesource.com/platform/frameworks/base/+/android-7.1.0_r4/services/core/java/com/android/server/am/ActivityManagerShellCommand.java


```

class ActivityManagerShellCommand extends ShellCommand {

    -----(snip)-----------

    @Override
    public int onCommand(String cmd) {
        if (cmd == null) {
            return handleDefaultCommands(cmd);
        }
        PrintWriter pw = getOutPrintWriter();
        try {
            switch (cmd) {
                case "force-stop":
                    return runForceStop(pw);
                case "kill":
                    return runKill(pw);
                case "kill-all":
                    return runKillAll(pw);
                case "write":
                    return runWrite(pw);
                case "track-associations":
                    return runTrackAssociations(pw);
                case "untrack-associations":
                    return runUntrackAssociations(pw);
                case "is-user-stopped":
                    return runIsUserStopped(pw);
                case "lenient-background-check":
                    return runLenientBackgroundCheck(pw);
                case "get-uid-state":
                    return getUidState(pw);
                default:
                    return handleDefaultCommands(cmd);
            }
        } catch (RemoteException e) {
            pw.println("Remote exception: " + e);
        }
        return -1;
    }
    int runIsUserStopped(PrintWriter pw) {
       -----(snip)-----------
    }
    int runForceStop(PrintWriter pw) throws RemoteException {
       -----(snip)-----------
    }
    int runKill(PrintWriter pw) throws RemoteException {
       -----(snip)-----------
    }
    int runKillAll(PrintWriter pw) throws RemoteException {
       -----(snip)-----------
    }
    int runWrite(PrintWriter pw) {
       -----(snip)-----------
    }
    int runTrackAssociations(PrintWriter pw) {
       -----(snip)-----------
    }
    int runUntrackAssociations(PrintWriter pw) {
       -----(snip)-----------
    }
    int runLenientBackgroundCheck(PrintWriter pw) throws RemoteException {
       -----(snip)-----------
    }
    int getUidState(PrintWriter pw) throws RemoteException {
       -----(snip)-----------
    }
    
    @Override
    public void onHelp() {
        PrintWriter pw = getOutPrintWriter();
        dumpHelp(pw, mDumping);
    }

    -----(snip)-----------
}
```