Collection of ADB basic instructions for Android debugging

ADB basic instruction

author: Zhu Hongxi
notice: Updating

Basic Usage

Command syntax

The basic syntax of the adb command is as follows:

adb [-d|-e|-s <serialNumber>] <command>

If only one device / simulator is connected, you can omit the part [- D | - e | - s < serialnumber >] and directly use ADB < command >.

Specify the target device for the command

If there are multiple devices / simulators connected, you need to specify the target device for the command.

parameter meaning
-d Specify the only Android device currently connected via USB as the command target
-e Specify the only simulator currently running as the command target
-s <serialNumber> Specify the device / simulator with the corresponding serialNumber as the command target

When multiple devices / simulators are connected, the - s < serialNumber > parameter is commonly used. serialNumber can be obtained through adb devices command. For example:

$ adb devices

List of devices attached
cf264b8f	device
emulator-5554	device
10.129.164.6:5555	device

cf264b8f, emulator-5554 and 10.129.164.6:5555 in the output are serialNumber.

For example, you want to specify cf264b8f this device to run the adb command to obtain the screen resolution:

adb -s cf264b8f shell wm size

Another example is to install an application on the device 10.129.164.6:5555 (the format of this form of serialNumber is < IP >: < port >, which is generally a wireless connected device or a third-party Android simulator such as Genymotion):

adb -s 10.129.164.6:5555 install test.apk

In case of multiple devices / simulators, these parameters are used to specify the target device for the command. The following is a simplified description and will not be repeated.

Start / stop

Start adb server command:

adb start-server

(generally, it is not necessary to execute this command manually. If the adb server is not started when running the adb command, it will be automatically started.)

Stop adb server command:

adb kill-server

View adb version

Command:

adb version

Sample output:

Android Debug Bridge version 1.0.36
Revision 8f855a3d9b35-android

Run adbd with root privileges

The operation principle of adb is that the adb server on the PC side establishes a connection with the daemon adbd on the mobile phone side, and then the adb client on the PC side forwards commands through the adb server. After receiving the commands, adbd parses and runs.

Therefore, if adbd is executed with normal permission, some commands that require root permission cannot be executed directly with adb xxx. At this time, you can execute the command after the adb shell and su, or you can let the adbd execute with the root permission, and you can execute the high permission command at will.

Command:

adb root

Normal output:

restarting adbd as root

Now run the adb shell again and see if the command line prompt becomes #?

Some mobile phones cannot execute adbd with root authority through the adb root command after root. For example, some models of Samsung will prompt adbd cannot run as root in production builds. At this time, you can first install adbd secure and then try adb root.

Accordingly, if you want to restore adbd to non root permissions, you can use the adb unroot command.

Specify the network port of the adb server

Command:

adb -P <port> start-server

The default port is 5037.

Device connection management

Query connected devices / emulators

Command:

adb devices

Output example:

List of devices attached
cf264b8f	device
emulator-5554	device
10.129.164.6:5555	device

The output formats of [serial number] are usually [serial number], i.e. SN:

  • offline -- indicates that the device is not connected successfully or has no response.

  • Device -- the device is connected. Note that this status does not indicate that the Android system has been fully started and operable. During device startup, the device instance can be connected to the adb, but the system is in an operable state after startup.

  • No device -- no device / simulator connection.

The above output shows that three devices / simulators have been connected. cf264b8f, emulator-5554 and 10.129.164.6:5555 are their SN respectively. From the name of emulator-5554, we can see that it is an Android simulator, while the serialNumber in the form of < IP >: < port > in 10.129.164.6:5555 is generally a wireless connected device or a third-party Android simulator such as Genymotion.

Common exception output:

  1. No devices / emulators connected successfully.

    List of devices attached
    
  2. The device / emulator is not connected to the adb or is not responding.

    List of devices attached
    cf264b8f	offline
    

USB connection

To use adb normally through USB connection, you need to ensure the following points:

  1. The hardware status is normal.

    Including the Android device is in the normal power on state, and the USB connection cable and various interfaces are intact.

  2. The developer option and USB debugging mode of Android device are turned on.

    You can view it in settings - Developer options - Android debugging.

    If you can't find the developer option in the settings, you need to display it through a colored egg: click "version number" 7 times in "Settings" - "about mobile phone".

  3. The device drive status is normal.

    It seems that you don't have to worry about this under Linux and Mac OS X. you may need to install drivers under Windows. To confirm this, you can right-click "computer" - "properties" and check whether there are yellow exclamation marks or question marks on relevant devices in "device manager". If not, it means that the driver status is good. Otherwise, you can download a mobile assistant program to install the driver first.

  4. Confirm the status after connecting the computer and device through USB cable.

    adb devices
    

    If you can see

    xxxxxx device
    

    Indicates that the connection is successful.

Wireless connection (USB cable required)

In addition to connecting the device and computer via USB to use adb, you can also connect wirelessly - although there are steps to use USB in the connection process, after the connection is successful, your device can get rid of the limitation of USB connection cable within a certain range!

Operation steps:

  1. Connect the Android device to the same LAN as the computer running the adb, for example, to the same WiFi.

  2. Connect the device to the computer via USB cable.

    Ensure that the connection is successful (run adb devices to see if the device can be listed).

  3. Let the device listen for TCP/IP connections on port 5555:

    adb tcpip 5555
    
  4. Disconnect the USB connection.

  5. Find the IP address of the device.

    Generally, you can find it in "Settings" - "about mobile phone" - "status information" - "IP address", or you can use the following View device information - IP address Use the adb command to view the methods in the section.

  6. Connect devices through IP addresses.

    adb connect <device-ip-address>
    

    The < device IP address > here is the device IP address found in the previous step.

  7. Confirm the connection status.

    adb devices
    

    If you can see

    <device-ip-address>:5555 device
    

    Indicates that the connection is successful.

If you can't connect, please confirm that the Android device and the computer are connected to the same WiFi, and then perform the step of ADB connect < device IP address > again;

If it still doesn't work, restart adb through adb kill server and try again from the beginning.

Disconnect wireless connection

Command:

adb disconnect <device-ip-address>

Wireless connection (without USB cable)

Note: root permission is required.

In the previous section, "wireless connection (with USB cable)" is the method introduced in the official document. The wireless connection needs to be realized with the help of USB data cable.

Since we want to realize wireless connection, can all steps be wireless? The answer is yes.

  1. Install a terminal simulator on Android devices.

    Devices that have already been installed can skip this step. The download address of the terminal simulator I use is: Terminal Emulator for Android Downloads

  2. Connect the Android device to the same LAN as the computer running the adb, for example, to the same WiFi.

  3. Open the terminal simulator on the Android device and run the commands in turn:

    su
    setprop service.adb.tcp.port 5555
    
  4. Find the IP address of the Android device.

    Generally, you can find it in "Settings" - "about mobile phone" - "status information" - "IP address", or you can use the following View device information - IP address Use the adb command to view the methods in the section.

  5. Connect Android devices through adb and IP address on the computer.

    adb connect <device-ip-address>
    

    The < device IP address > here is the device IP address found in the previous step.

    If you can see the output connected to < device IP address >: 5555, it indicates that the connection is successful.

Section note 1:

Some devices, such as Xiaomi 5S + MIUI 8.0 + Android 6.0.1 MXB48T, may need to restart the adbd service before step 5 and run on the device's terminal simulator:

restart adbd

If restart does not work, try the following command:

stop adbd
start adbd

Application management

View app list

The basic command format for viewing the application list is

adb shell pm list packages [-f] [-d] [-e] [-s] [-3] [-i] [-u] [--user USER_ID] [FILTER]

That is, you can add some parameters to adb shell pm list packages to filter and view different lists. The supported filtering parameters are as follows:

parameter Display list
nothing All applications
-f Displays the apk file associated with the application
-d Show only disabled apps
-e Show only enabled apps
-s Show only system applications
-3 Show only third-party apps
-i Displays the installer of the application
-u Contains uninstalled apps
<FILTER> The package name contains a < Filter > string

All applications

Command:

adb shell pm list packages

Output example:

package:com.android.smoketest
package:com.example.android.livecubes
package:com.android.providers.telephony
package:com.google.android.googlequicksearchbox
package:com.android.providers.calendar
package:com.android.providers.media
package:com.android.protips
package:com.android.documentsui
package:com.android.gallery
package:com.android.externalstorage
...
// other packages here
...

System application

Command:

adb shell pm list packages -s

Third party applications

Command:

adb shell pm list packages -3

Application whose package name contains a string

For example, to view the application list whose package name contains the string mazhuang, the command:

adb shell pm list packages mazhuang

Of course, you can also use grep to filter:

adb shell pm list packages | grep mazhuang

Install APK

Command format:

adb install [-lrtsdg] <path_to_apk>

Parameters:

adb install can be followed by some optional parameters to control the behavior of installing APK. The available parameters and meanings are as follows:

parameter meaning
-l Install the application in the protected directory / mnt/asec
-r Allow override installation
-t Allow the installation of androidmanifest application in XML specifies android:testOnly="true"
-s Install app to sdcard
-d Allow downgrade override installation
-g Grant all runtime permissions

After running the command, if you see the following output (the status is Success), the installation is successful:

[100%] /data/local/tmp/1.apk
	pkg: /data/local/tmp/1.apk
Success

The above is the latest version of V1 The output of 0.36 adb will display the progress percentage of push apk file to the mobile phone.

The output using the old version of adb is like this:

12040 KB/s (22205609 bytes in 1.801s)
        pkg: /data/local/tmp/SogouInput_android_v8.3_sweb.apk
Success

If the status is Failure, the installation fails, for example:

[100%] /data/local/tmp/map-20160831.apk
        pkg: /data/local/tmp/map-20160831.apk
Failure [INSTALL_FAILED_ALREADY_EXISTS]

Common installation failure output codes, meanings and possible solutions are as follows:

output meaning terms of settlement
INSTALL_FAILED_ALREADY_EXISTS The app already exists or has been uninstalled but not completely uninstalled Use the - r parameter when installing ADB, or install ADB uninstall < packagename > first
INSTALL_FAILED_INVALID_APK Invalid APK file
INSTALL_FAILED_INVALID_URI Invalid APK file name Make sure there is no Chinese in the APK file name
INSTALL_FAILED_INSUFFICIENT_STORAGE Insufficient space Clean up space
INSTALL_FAILED_DUPLICATE_PACKAGE A program with the same name already exists
INSTALL_FAILED_NO_SHARED_USER The requested shared user does not exist
INSTALL_FAILED_UPDATE_INCOMPATIBLE An application with the same name has been installed before, but the data is not removed when uninstalling; Or the app is installed, but the signature is inconsistent ADB uninstall < packagename > before installing
INSTALL_FAILED_SHARED_USER_INCOMPATIBLE The requested shared user exists but has inconsistent signatures
INSTALL_FAILED_MISSING_SHARED_LIBRARY The installation package uses a shared library that is not available on the device
INSTALL_FAILED_REPLACE_COULDNT_DELETE Cannot delete while replacing
INSTALL_FAILED_DEXOPT dex optimization validation failed or there is not enough space
INSTALL_FAILED_OLDER_SDK The equipment system version is lower than the application requirements
INSTALL_FAILED_CONFLICTING_PROVIDER A content provider with the same name as the one in the application already exists in the device
INSTALL_FAILED_NEWER_SDK The equipment system version is higher than the application requirements
INSTALL_FAILED_TEST_ONLY The application is test only, but the - t parameter is not specified during installation
INSTALL_FAILED_CPU_ABI_INCOMPATIBLE native code containing binary interface of incompatible device CPU application
INSTALL_FAILED_MISSING_FEATURE The app uses features that are not available on the device
INSTALL_FAILED_CONTAINER_ERROR 1. sdcard access failed;
2. The application signature is consistent with the ROM signature and is regarded as a built-in application.
1. Confirm that the sdcard is available or installed into the built-in storage;
2. Do not use the same signature as ROM when packaging.
INSTALL_FAILED_INVALID_INSTALL_LOCATION 1. It cannot be installed at the specified position;
2. The application signature is consistent with the ROM signature and is regarded as a built-in application.
1. Switch the installation position and add or delete the -s parameter;
2. Do not use the same signature as ROM when packaging.
INSTALL_FAILED_MEDIA_UNAVAILABLE Installation location not available Generally, it is sdcard. Confirm that the sdcard is available or installed into the built-in storage
INSTALL_FAILED_VERIFICATION_TIMEOUT Verifying installation package timed out
INSTALL_FAILED_VERIFICATION_FAILURE Failed to verify the installation package
INSTALL_FAILED_PACKAGE_CHANGED The application does not match what the caller expects
INSTALL_FAILED_UID_CHANGED The application has been installed before, which is inconsistent with the UID allocated this time Clear residual files from previous installations
INSTALL_FAILED_VERSION_DOWNGRADE A later version of this app is already installed Use the - d parameter
INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE An application with the same name that the target SDK supports runtime permission has been installed. The version to be installed does not support runtime permission
INSTALL_PARSE_FAILED_NOT_APK The specified path is not a file or is not in apk end
INSTALL_PARSE_FAILED_BAD_MANIFEST Unable to resolve androidmanifest XML file
INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION The parser encountered an exception
INSTALL_PARSE_FAILED_NO_CERTIFICATES The installation package is not signed
INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES The app is installed and the signature is inconsistent with the APK file Uninstall the application on the device before installing it
INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING CertificateEncodingException encountered while parsing APK file
INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME There is no or invalid package name in the manifest file
INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID Invalid shared user ID specified in manifest file
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED A structural error was encountered while parsing the manifest file
INSTALL_PARSE_FAILED_MANIFEST_EMPTY The operational tag (instrumentation or application) cannot be found in the manifest file
INSTALL_FAILED_INTERNAL_ERROR Installation failed due to system problems
INSTALL_FAILED_USER_RESTRICTED Users are restricted from installing apps Open "USB installation" in the developer option. If it has been opened, close it first and then open it.
INSTALL_FAILED_DUPLICATE_PERMISSION The app tried to define an existing permission name
INSTALL_FAILED_NO_MATCHING_ABIS The application contains native code that is not supported by the application binary interface of the device
INSTALL_CANCELED_BY_USER The application installation needs to be confirmed on the device, but the device is not operated or cancelled Agree to install on the equipment
INSTALL_FAILED_ACWF_INCOMPATIBLE The application is incompatible with the device
INSTALL_FAILED_TEST_ONLY The files compiled by Android Studio are APK files Recompile through Gradle's assemblydebug or assemblyrelease, or Generate Signed APK
does not contain AndroidManifest.xml Invalid APK file
is not a valid zip file Invalid APK file
Offline The device is not connected successfully Connect the device to the adb successfully first
unauthorized The device is not authorized to allow debugging
error: device not found No devices connected successfully Connect the device to the adb successfully first
protocol failure Device disconnected Connect the device to the adb successfully first
Unknown option: -s Installation to sdcard is not supported under Android 2.2 Do not use the - s parameter
No space left on device Insufficient space Clean up space
Permission denied ... sdcard ... sdcard not available
signatures do not match the previously installed version; ignoring! The app is already installed and has inconsistent signatures Uninstall the application on the device before installing it

reference resources: PackageManager.java

Introduction to the internal principle of adb install

adb install is actually completed in three steps:

  1. push apk file to / data/local/tmp.

  2. Call pm install to install.

  3. Delete the corresponding apk file under / data/local/tmp.

Therefore, if necessary, you can also manually perform the installation process step by step according to this step.

Uninstall application

Command:

adb uninstall [-k] <packagename>

< packagename > indicates the package name of the application, and the - k parameter is optional. It indicates that the application is unloaded but the data and cache directory are retained.

Command example:

adb uninstall com.qihoo360.mobilesafe

Means to uninstall 360 mobile guard.

Clear application data and cache

Command:

adb shell pm clear <packagename>

< packagename > indicates the name of the application package. The effect of this command is equivalent to clicking "clear cache" and "clear data" in the application information interface of settings.

Command example:

adb shell pm clear com.qihoo360.mobilesafe

It means to clear the data and cache of 360 mobile guard.

View foreground Activity

Command:

adb shell dumpsys activity activities | grep mResumedActivity

Output example:

mResumedActivity: ActivityRecord{8079d7e u0 com.cyanogenmod.trebuchet/com.android.launcher3.Launcher t42}

Among them, com cyanogenmod. trebuchet/com. android. launcher3. The launcher is the Activity currently in the foreground.

The above commands may not be available under Windows. You can try ADB shell dumpsys activities | findstr mresumedactivity or ADB shell "dumpsys activities | grep mresumedactivity".

View running Services

Command:

adb shell dumpsys activity services [<packagename>]

The < packagename > parameter is not required. Specifying < packagename > means to view the Services related to a package name, and not specifying means to view all Services.

< packagename > it is not necessary to give the complete package name. For example, run ADB shell dumpsys activity Services org Mazhuang, then the package name is org mazhuang. demo1,org.mazhuang.demo2 and org Mazhuang123 and other related Services will be listed.

View app details

Command:

adb shell dumpsys package <packagename>

The output contains a lot of information, including Activity Resolver Table, Registered ContentProviders, package name, userId, installed file resource code, version information, permission information, grant status, signature version information, etc.

< packagename > indicates the name of the application package.

Output example:

Activity Resolver Table:
  Non-Data Actions:
      android.intent.action.MAIN:
        5b4cba8 org.mazhuang.guanggoo/.SplashActivity filter 5ec9dcc
          Action: "android.intent.action.MAIN"
          Category: "android.intent.category.LAUNCHER"
          AutoVerify=false

Registered ContentProviders:
  org.mazhuang.guanggoo/com.tencent.bugly.beta.utils.BuglyFileProvider:
    Provider{7a3c394 org.mazhuang.guanggoo/com.tencent.bugly.beta.utils.BuglyFileProvider}

ContentProvider Authorities:
  [org.mazhuang.guanggoo.fileProvider]:
    Provider{7a3c394 org.mazhuang.guanggoo/com.tencent.bugly.beta.utils.BuglyFileProvider}
      applicationInfo=ApplicationInfo{7754242 org.mazhuang.guanggoo}

Key Set Manager:
  [org.mazhuang.guanggoo]
      Signing KeySets: 501

Packages:
  Package [org.mazhuang.guanggoo] (c1d7f):
    userId=10394
    pkg=Package{55f714c org.mazhuang.guanggoo}
    codePath=/data/app/org.mazhuang.guanggoo-2
    resourcePath=/data/app/org.mazhuang.guanggoo-2
    legacyNativeLibraryDir=/data/app/org.mazhuang.guanggoo-2/lib
    primaryCpuAbi=null
    secondaryCpuAbi=null
    versionCode=74 minSdk=15 targetSdk=25
    versionName=1.1.74
    splits=[base]
    apkSigningVersion=2
    applicationInfo=ApplicationInfo{7754242 org.mazhuang.guanggoo}
    flags=[ HAS_CODE ALLOW_CLEAR_USER_DATA ALLOW_BACKUP ]
    privateFlags=[ RESIZEABLE_ACTIVITIES ]
    dataDir=/data/user/0/org.mazhuang.guanggoo
    supportsScreens=[small, medium, large, xlarge, resizeable, anyDensity]
    timeStamp=2017-10-22 23:50:53
    firstInstallTime=2017-10-22 23:50:25
    lastUpdateTime=2017-10-22 23:50:55
    installerPackageName=com.miui.packageinstaller
    signatures=PackageSignatures{af09595 [53c7caa2]}
    installPermissionsFixed=true installStatus=1
    pkgFlags=[ HAS_CODE ALLOW_CLEAR_USER_DATA ALLOW_BACKUP ]
    requested permissions:
      android.permission.READ_PHONE_STATE
      android.permission.INTERNET
      android.permission.ACCESS_NETWORK_STATE
      android.permission.ACCESS_WIFI_STATE
      android.permission.READ_LOGS
      android.permission.WRITE_EXTERNAL_STORAGE
      android.permission.READ_EXTERNAL_STORAGE
    install permissions:
      android.permission.INTERNET: granted=true
      android.permission.ACCESS_NETWORK_STATE: granted=true
      android.permission.ACCESS_WIFI_STATE: granted=true
    User 0: ceDataInode=1155675 installed=true hidden=false suspended=false stopped=true notLaunched=false enabled=0
      gids=[3003]
      runtime permissions:
        android.permission.READ_EXTERNAL_STORAGE: granted=true
        android.permission.READ_PHONE_STATE: granted=true
        android.permission.WRITE_EXTERNAL_STORAGE: granted=true
    User 999: ceDataInode=0 installed=false hidden=false suspended=false stopped=true notLaunched=true enabled=0
      gids=[3003]
      runtime permissions:


Dexopt state:
  [org.mazhuang.guanggoo]
    Instruction Set: arm64
      path: /data/app/org.mazhuang.guanggoo-2/base.apk
      status: /data/app/org.mazhuang.guanggoo-2/oat/arm64/base.odex [compilation_filter=speed-profile, status=kOatUpToDa
      te]

View app installation path

Command:

adb shell pm path <PACKAGE>

Output application installation path

Output example:

adb shell pm path ecarx.weather

package:/data/app/ecarx.weather-1.apk

Interaction with Applications

It mainly uses the AM < command > command. The commonly used < command > commands are as follows:

command purpose
start [options] <INTENT> Start the Activity specified by < intent >
startservice [options] <INTENT> Start the Service specified by < intent >
broadcast [options] <INTENT> Send the broadcast specified by < intent >
force-stop <packagename> Stop < packagename > related processes

The < Intent > parameter is very flexible and corresponds to the Intent in the code when writing Android programs.

The options used to determine the intent object are as follows:

parameter meaning
-a <ACTION> Specify an action, such as Android intent. action. VIEW
-c <CATEGORY> Specify category, such as Android intent. category. APP_ CONTACTS
-n <COMPONENT> Specify the full component name, which is used to specify which Activity to start, such as com example. app/. ExampleActivity

< intent > can also contain data, just like the Bundle when writing code:

parameter meaning
--esn <EXTRA_KEY> null value (only key name)
-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> string value
--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> boolean value
--ei <EXTRA_KEY> <EXTRA_INT_VALUE> integer value
--el <EXTRA_KEY> <EXTRA_LONG_VALUE> long value
--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> float value
--eu <EXTRA_KEY> <EXTRA_URI_VALUE> URI
--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE> component name
--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...] integer array
--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...] long array

Start application / activate Activity

Specify the Activity name to start

Command format:

adb shell am start [options] <INTENT>

For example:

adb shell am start -n com.tencent.mm/.ui.LauncherUI

Indicates that the wechat main interface is activated.

adb shell am start -n org.mazhuang.boottimemeasure/.MainActivity --es "toast" "hello, world"

It means calling org mazhuang. boottimemeasure/. Mainactivity and pass it string data key value pair toast - hello, world.

Start without specifying Activity name (start main Activity)

Command format:

adb shell monkey -p <packagename> -c android.intent.category.LAUNCHER 1

For example:

adb shell monkey -p com.tencent.mm -c android.intent.category.LAUNCHER 1

Indicates that the wechat main interface is activated.

Call up Service

Command format:

adb shell am startservice [options] <INTENT>

For example:

adb shell am startservice -n com.tencent.mm/.plugin.accountsync.model.AccountAuthenticatorService

Indicates that a Service of wechat has been activated.

Another typical use case is that if the virtual key should be displayed on the device, but it is not displayed, you can try this:

adb shell am startservice -n com.android.systemui/.SystemUIService

Stop Service

Command format:

adb shell am stopservice [options] <INTENT>

Send broadcast

Command format:

adb shell am broadcast [options] <INTENT>

You can broadcast to all components or only to specified components.

For example, broadcast boot to all components_ COMPLETED:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

As another example, only to org mazhuang. boottimemeasure/. Bootcompletedreceiver broadcast BOOT_COMPLETED:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -n org.mazhuang.boottimemeasure/.BootCompletedReceiver

This kind of usage is very practical when testing. For example, it is difficult to create a broadcast scene. You can consider sending a broadcast in this way.

It can send both predefined broadcasts and customized broadcasts. The following are the predefined broadcast and normal trigger timing of some systems:

action Trigger timing
android.net.conn.CONNECTIVITY_CHANGE Network connection changes
android.intent.action.SCREEN_ON The screen lights up
android.intent.action.SCREEN_OFF Screen off
android.intent.action.BATTERY_LOW If the power is low, a low power prompt box will pop up
android.intent.action.BATTERY_OKAY The power is restored
android.intent.action.BOOT_COMPLETED Equipment startup completed
android.intent.action.DEVICE_STORAGE_LOW Storage space too low
android.intent.action.DEVICE_STORAGE_OK Storage space recovery
android.intent.action.PACKAGE_ADDED New apps installed
android.net.wifi.STATE_CHANGE WiFi connection status changes
android.net.wifi.WIFI_STATE_CHANGED WiFi status changes to on / off / starting / turning off / unknown
android.intent.action.BATTERY_CHANGED The battery level changes
android.intent.action.INPUT_METHOD_CHANGED The system input method has changed
android.intent.action.ACTION_POWER_CONNECTED External power connection
android.intent.action.ACTION_POWER_DISCONNECTED External power supply disconnected
android.intent.action.DREAMING_STARTED The system begins to sleep
android.intent.action.DREAMING_STOPPED The system stops sleeping
android.intent.action.WALLPAPER_CHANGED Wallpaper changes
android.intent.action.HEADSET_PLUG Plug in headphones
android.intent.action.MEDIA_UNMOUNTED Unmount external media
android.intent.action.MEDIA_MOUNTED Mount external media
android.os.action.POWER_SAVE_MODE_CHANGED Power saving mode on

(the above broadcasts can be triggered by adb)

Force stop application

Command:

adb shell am force-stop <packagename>

Command example:

adb shell am force-stop com.qihoo360.mobilesafe

It means to stop all processes and services of 360 security guard.

Tighten memory

Command:

adb shell am send-trim-memory  <pid> <level>

pid: process ID
level:
HIDDEN,RUNNING_MODERATE,BACKGROUND,
RUNNING_LOW,MODERATE,RUNNING_CRITICAL,COMPLETE

Command example:

adb shell am send-trim-memory 12345 RUNNING_LOW

Indicates issuing level = running to the process with pid=12345_ Low tighten memory command.

file management

Copy files to a computer device

Command:

adb pull <File path in the device> [Directory on computer]

The directory parameters on the computer can be omitted and copied to the current directory by default.

Example:

adb pull /sdcard/sr.mp4 ~/tmp/

*Tips: * the file path on the device may need root permission to access. If your device has been root, you can first use the adb shell and su command to obtain root permission in the adb shell, first cp /path/on/device /sdcard/filename to copy the file to sdcard, and then adb pull /sdcard/filename /path/on/pc.

Copy files from the computer to the device

Command:

adb push <File path on PC> <Directory in the device>

Example:

adb push ~/sr.mp4 /sdcard/

*Tips: * the normal permissions of the file path on the device may not be written directly. If your device has been root, you can first adb push /path/on/pc /sdcard/filename, and then the adb shell and su obtain the root permission in the adb shell, and then cp /sdcard/filename /path/on/device.

Analog key / input

In the adb shell, there is a very practical command called input, through which you can do some interesting things.

The complete help information of the input command is as follows:

Usage: input [<source>] <command> [<arg>...]

The sources are:
      mouse
      keyboard
      joystick
      touchnavigation
      touchpad
      trackball
      stylus
      dpad
      gesture
      touchscreen
      gamepad

The commands and default sources are:
      text <string> (Default: touchscreen)
      keyevent [--longpress] <key code number or name> ... (Default: keyboard)
      tap <x> <y> (Default: touchscreen)
      swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll <dx> <dy> (Default: trackball)

For example, using the ADB shell input keyevent < keycode > command, different keycodes can achieve different functions. For a complete list of keycodes, see KeyEvent , the excerpt I find interesting is as follows:

keycode meaning
3 HOME key
4 Return key
5 Open dial up app
6 Hang up
24 Volume Up
25 lower the volume
26 Power key
27 Take photos (need in camera application)
64 Open browser
82 Menu key
85 Play / pause
86 stop playing
87 Play the next song
88 Play previous song
122 Move the cursor to the beginning of the line or the top of the list
123 Move the cursor to the end of the line or the bottom of the list
126 Resume playback
127 Pause playback
164 Mute
176 Open system settings
187 Switch application
207 Open contact
208 Open calendar
209 Turn on music
210 Open calculator
220 Reduce screen brightness
221 Increase screen brightness
223 System sleep
224 Light up the screen
231 Open voice assistant
276 If there is no wakelock, let the system sleep

Here are some usage examples of the input command.

Power key

Command:

adb shell input keyevent 26

The execution effect is equivalent to pressing the power key.

Menu key

Command:

adb shell input keyevent 82

HOME key

Command:

adb shell input keyevent 3

Return key

Command:

adb shell input keyevent 4

Volume control

Increase volume:

adb shell input keyevent 24

lower the volume:

adb shell input keyevent 25

Mute:

adb shell input keyevent 164

Media control

Play / pause:

adb shell input keyevent 85

Stop playback:

adb shell input keyevent 86

Play next:

adb shell input keyevent 87

Play the previous song:

adb shell input keyevent 88

Resume playback:

adb shell input keyevent 126

Pause playback:

adb shell input keyevent 127

On / off screen

You can switch on and off the screen through the analog power key described above, but if you explicitly want to turn on or off the screen, you can use the following methods.

Light up the screen:

adb shell input keyevent 224

Off screen:

adb shell input keyevent 223

Slide unlock

If the lock screen has no password and is unlocked through sliding gesture, it can be unlocked through input swipe.

Command (the parameters are based on the model Nexus 5, and the upward sliding gesture unlocking is taken as an example):

adb shell input swipe 300 1000 300 500

The parameters 300, 1000, 300, 500 respectively represent the starting point x coordinate, the starting point y coordinate, the ending point x coordinate, and the ending point y coordinate.

Enter text

When the focus is in a text box, you can enter text through the input command.

Command:

adb shell input text hello

Now hello appears in the text box.

view log

The log of Android system is divided into two parts. The bottom Linux kernel log is output to / proc/kmsg, and the Android log is output to / dev/log.

Android log

Command format:

[adb] logcat [<option>] ... [<filter-spec>] ...

Common usage is listed as follows:

Filter logs by level

Android logs are divided into the following priorities:

  • V - Verbose (minimum, maximum output)
  • D - Debug
  • I - Info
  • W - Warning
  • E - Error
  • F - Fatal
  • S -- Silent (highest, nothing output)

Filtering logs by a certain level will output logs of that level and above.

For example, command:

adb logcat *:W

The Warning, Error, Fatal, and Silent logs are output.

(Note: under macOS, you need to add double quotation marks to the parameter with * as tag, such as adb logcat "*:W", otherwise you will report no matches found: *:W.)

Filter logs by tag and level

< filter spec > can be composed of multiple < tag > [: priority].

For example, command:

adb logcat ActivityManager:I MyApp:D *:S

It means that the log above Info level of tag ActivityManager, the log above Debug level of tag MyApp and the Silent level of other tags are output (that is, other tag logs are shielded).

Log format

You can specify the log output format with the ADB logcat - V < Format > option.

Log supports the following < Format >:

  • brief

    Default format. The format is:

    <priority>/<tag>(<pid>): <message>
    

    Example:

    D/HeadsetStateMachine( 1785): Disconnected process message: 10, size: 0
    
  • process

    The format is:

    <priority>(<pid>) <message>
    

    Example:

    D( 1785) Disconnected process message: 10, size: 0  (HeadsetStateMachine)
    
  • tag

    The format is:

    <priority>/<tag>: <message>
    

    Example:

    D/HeadsetStateMachine: Disconnected process message: 10, size: 0
    
  • raw

    The format is:

    <message>
    

    Example:

    Disconnected process message: 10, size: 0
    
  • time

    The format is:

    <datetime> <priority>/<tag>(<pid>): <message>
    

    Example:

    08-28 22:39:39.974 D/HeadsetStateMachine( 1785): Disconnected process message: 10, size: 0
    
  • threadtime

    The format is:

    <datetime> <pid> <tid> <priority> <tag>: <message>
    

    Example:

    08-28 22:39:39.974  1785  1832 D HeadsetStateMachine: Disconnected process message: 10, size: 0
    
  • long

    The format is:

    [ <datetime> <pid>:<tid> <priority>/<tag> ]
    <message>
    

    Example:

    [ 08-28 22:39:39.974  1785: 1832 D/HeadsetStateMachine ]
    Disconnected process message: 10, size: 0
    

The specified format can be used together with the above filter. For example:

adb logcat -v long ActivityManager:I *:S

Clear log

adb logcat -c

Kernel log

Command:

adb shell dmesg

Output example:

<6>[14201.684016] PM: noirq resume of devices complete after 0.982 msecs
<6>[14201.685525] PM: early resume of devices complete after 0.838 msecs
<6>[14201.753642] PM: resume of devices complete after 68.106 msecs
<4>[14201.755954] Restarting tasks ... done.
<6>[14201.771229] PM: suspend exit 2016-08-28 13:31:32.679217193 UTC
<6>[14201.872373] PM: suspend entry 2016-08-28 13:31:32.780363596 UTC
<6>[14201.872498] PM: Syncing filesystems ... done.

[14201.684016] in brackets represents the time after the kernel starts to boot, in seconds.

Through the kernel log, we can do some things, such as measuring the kernel startup time. The time in front of the line of Freeing init memory in the kernel log after the system is started is.

View device information

model

Command:

adb shell getprop ro.product.model

Output example:

Nexus 5

Battery condition

Command:

adb shell dumpsys battery

Input example:

Current Battery Service state:
  AC powered: false
  USB powered: true
  Wireless powered: false
  status: 2
  health: 2
  present: true
  level: 44
  scale: 100
  voltage: 3872
  temperature: 280
  technology: Li-poly

Where scale represents the maximum power and level represents the current power. The above output indicates that 44% of the power is left.

Screen resolution

Command:

adb shell wm size

Output example:

Physical size: 1080x1920

The screen resolution of the device is 1080px * 1920px.

If it has been modified with the command, the output may be:

Physical size: 1080x1920
Override size: 480x1024

It indicates that the screen resolution of the device was originally 1080px * 1920px, but is currently modified to 480px * 1024px.

Screen density

Command:

adb shell wm density

Output example:

Physical density: 420

The screen density of the device is 420dpi.

If it has been modified with the command, the output may be:

Physical density: 480
Override density: 160

It indicates that the screen density of the device was originally 480dpi and is currently modified to 160dpi.

Display parameters

Command:

adb shell dumpsys window displays

Output example:

WINDOW MANAGER DISPLAY CONTENTS (dumpsys window displays)
  Display: mDisplayId=0
    init=1080x1920 420dpi cur=1080x1920 app=1080x1794 rng=1080x1017-1810x1731
    deferred=false layoutNeeded=false

Where mDisplayId is the display number, init is the initial resolution and screen density, and the height of app is smaller than that in init, indicating that there is a virtual key at the bottom of the screen, with a height of 1920 - 1794 = 126px, or 42dp.

android_id

Command:

adb shell settings get secure android_id

Output example:

51b6be48bac8c569

IMEI

In Android 4.4 and below, IMEI can be obtained through the following command:

adb shell dumpsys iphonesubinfo

Output example:

Phone Subscriber Info:
  Phone Type = GSM
  Device ID = 860955027785041

The Device ID is IMEI.

In Android 5.0 and above, the output of this command is empty, which must be obtained by other means (root permission is required):

adb shell
su
service call iphonesubinfo 1

Output example:

Result: Parcel(
  0x00000000: 00000000 0000000f 00360038 00390030 '........8.6.0.9.'
  0x00000010: 00350035 00320030 00370037 00350038 '5.5.0.2.7.7.8.5.'
  0x00000020: 00340030 00000031                   '0.4.1...        ')

The effective content extracted is IMEI. For example, here is 860955027785041.

reference resources: adb shell dumpsys iphonesubinfo not working since Android 5.0 Lollipop

Android system version

Command:

adb shell getprop ro.build.version.release

Output example:

5.0.2

IP address

Every time you want to know the IP address of the device, you have to "set" - "about mobile phone" - "status information" - "IP address". It's annoying, isn't it? It can be easily viewed through adb.

Command:

adb shell ifconfig | grep Mask

Output example:

inet addr:10.130.245.230  Mask:255.255.255.252
inet addr:127.0.0.1  Mask:255.0.0.0

Then 10.130.245.230 is the IP address of the device.

On some devices, this command is not output. If the device is connected to WiFi, you can use the following command to view the LAN IP:

adb shell ifconfig wlan0

Output example:

wlan0: ip 10.129.160.99 mask 255.255.240.0 flags [up broadcast running multicast]

or

wlan0     Link encap:UNSPEC
          inet addr:10.129.168.57  Bcast:10.129.175.255  Mask:255.255.240.0
          inet6 addr: fe80::66cc:2eff:fe68:b6b6/64 Scope: Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:496520 errors:0 dropped:0 overruns:0 frame:0
          TX packets:68215 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3000
          RX bytes:116266821 TX bytes:8311736

If the above commands still can't get the expected information, you can try the following commands (available in some system versions):

adb shell netcfg

Output example:

wlan0    UP                               10.129.160.99/20  0x00001043 f8:a9:d0:17:42:4d
lo       UP                                   127.0.0.1/8   0x00000049 00:00:00:00:00:00
p2p0     UP                                     0.0.0.0/0   0x00001003 fa:a9:d0:17:42:4d
sit0     DOWN                                   0.0.0.0/0   0x00000080 00:00:00:00:00:00
rmnet0   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet1   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet3   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet2   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet4   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet6   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet5   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rmnet7   DOWN                                   0.0.0.0/0   0x00000000 00:00:00:00:00:00
rev_rmnet3 DOWN                                   0.0.0.0/0   0x00001002 4e:b7:e4:2e:17:58
rev_rmnet2 DOWN                                   0.0.0.0/0   0x00001002 4e:f0:c8:bf:7a:cf
rev_rmnet4 DOWN                                   0.0.0.0/0   0x00001002 a6:c0:3b:6b:c4:1f
rev_rmnet6 DOWN                                   0.0.0.0/0   0x00001002 66:bb:5d:64:2e:e9
rev_rmnet5 DOWN                                   0.0.0.0/0   0x00001002 0e:1b:eb:b9:23:a0
rev_rmnet7 DOWN                                   0.0.0.0/0   0x00001002 7a:d9:f6:81:40:5a
rev_rmnet8 DOWN                                   0.0.0.0/0   0x00001002 4e:e2:a9:bb:d0:1b
rev_rmnet0 DOWN                                   0.0.0.0/0   0x00001002 fe:65:d0:ca:82:a9
rev_rmnet1 DOWN                                   0.0.0.0/0   0x00001002 da:d8:e8:4f:2e:fe

You can see the network connection name, enabled status, IP address, Mac address and other information.

Mac address

Command:

adb shell cat /sys/class/net/wlan0/address

Output example:

f8:a9:d0:17:42:4d

The Mac address of the LAN, mobile network or other connection information can be viewed through the adb shell netcfg command mentioned in the previous section "IP address".

CPU Information

Command:

adb shell cat /proc/cpuinfo

Output example:

Processor       : ARMv7 Processor rev 0 (v7l)
processor       : 0
BogoMIPS        : 38.40

processor       : 1
BogoMIPS        : 38.40

processor       : 2
BogoMIPS        : 38.40

processor       : 3
BogoMIPS        : 38.40

Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt
CPU implementer : 0x51
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0x06f
CPU revision    : 0

Hardware        : Qualcomm MSM 8974 HAMMERHEAD (Flattened Device Tree)
Revision        : 000b
Serial          : 0000000000000000

This is the CPU information of Nexus 5. We can see from the output that the hardware used is Qualcomm MSM 8974, and the processor number is 0 to 3, so it is quad core, and the architecture adopted is ARMv7 Processor rev 0 (v71).

Memory information

Command:

adb shell cat /proc/meminfo

Output example:

MemTotal:        1027424 kB
MemFree:          486564 kB
Buffers:           15224 kB
Cached:            72464 kB
SwapCached:        24152 kB
Active:           110572 kB
Inactive:         259060 kB
Active(anon):      79176 kB
Inactive(anon):   207736 kB
Active(file):      31396 kB
Inactive(file):    51324 kB
Unevictable:        3948 kB
Mlocked:               0 kB
HighTotal:        409600 kB
HighFree:         132612 kB
LowTotal:         617824 kB
LowFree:          353952 kB
SwapTotal:        262140 kB
SwapFree:         207572 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:        265324 kB
Mapped:            47072 kB
Shmem:              1020 kB
Slab:              57372 kB
SReclaimable:       7692 kB
SUnreclaim:        49680 kB
KernelStack:        4512 kB
PageTables:         5912 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:      775852 kB
Committed_AS:   13520632 kB
VmallocTotal:     385024 kB
VmallocUsed:       61004 kB
VmallocChunk:     209668 kB

Where, MemTotal is the total memory of the device and MemFree is the current free memory.

More hardware and system attributes

More hardware and system attributes of the device can be viewed through the following commands:

adb shell cat /system/build.prop

This will output a lot of information, including the "model" and "Android system version" mentioned in the previous sections.

The output also includes some other useful information, which can also be viewed separately through the ADB shell getprop < attribute name > command. Some attributes are listed as follows:

Attribute name meaning
ro.build.version.sdk SDK version
ro.build.version.release Android system version
ro.build.version.security_patch Android security patch level
ro.product.model model
ro.product.brand brand
ro.product.name Device name
ro.product.board Processor model
ro.product.cpu.abilist abi list supported by CPU [Note 1]
persist.sys.isUsbOtgEnabled Is OTG supported
dalvik.vm.heapsize Maximum memory per application
ro.sf.lcd_density Screen density

Section note 1:

The ROM customized by some small factories may have modified the attribute name of the abi list supported by the CPU. If ro product. cpu. The ability attribute name cannot be found. Try this:

adb shell cat /system/build.prop | grep ro.product.cpu.abi

Sample output:

ro.product.cpu.abi=armeabi-v7a
ro.product.cpu.abi2=armeabi

Modify settings

Note: after modifying the settings, running the recovery command may still display abnormal. You can run adb reboot to restart the device or restart it manually.

The principle of modifying settings is to modify / data / data / COM through the settings command android. providers. settings/databases/settings. The setting value stored in dB.

resolving power

Command:

adb shell wm size 480x1024

Indicates that the resolution is modified to 480px * 1024px.

Restore original resolution command:

adb shell wm size reset

Screen density

Command:

adb shell wm density 160

Indicates that the screen density is modified to 160dpi.

Restore original screen density command:

adb shell wm density reset

Display area

Command:

adb shell wm overscan 0,0,0,200

The four numbers represent the white pixels from the left, upper, right and lower edges respectively. The above command means to leave 200px white at the bottom of the screen.

Restore the original display area command:

adb shell wm overscan reset

Turn off USB debugging mode

Command:

adb shell settings put global adb_enabled 0

Recovery:

It can't be restored with the command. After all, if USB debugging is turned off, adb can't connect to Android devices.

Go to the device to restore manually: "Settings" - "developer options" - "Android debugging".

Allow / disable access to non SDK API s

Allow access to non SDK API s:

adb shell settings put global hidden_api_policy_pre_p_apps 1
adb shell settings put global hidden_api_policy_p_apps 1

Prohibit access to non SDK API s:

adb shell settings delete global hidden_api_policy_pre_p_apps
adb shell settings delete global hidden_api_policy_p_apps

Root permission is not required for the device.

Meaning of the last number of the command:

value meaning
0 It is forbidden to detect calls to non SDK interfaces. In this case, the logging function is disabled and the strict mode API, detectNonSdkApiUsage(), is invalidated. Not recommended.
1 Warning only - allow access to all non SDK interfaces, but keep the warning information in the log. You can continue to use the string mode API.
2 It is forbidden to call interfaces in dark gray list and blacklist.
3 It is forbidden to call interfaces in the blacklist, but it is allowed to call interfaces in the dark gray list.

Display and hide of status bar and navigation bar

The relevant settings mentioned in this section correspond to the "extended desktop" in Cyanogenmod.

Command:

adb shell settings put global policy_control <key-values>

< key values > can be composed of the following keys and their corresponding values. The format is < key1 > = < value1 >: < key2 > = < Value2 >.

key meaning
immersive.full Hide at the same time
immersive.status hide the status bar
immersive.navigation Hide navigation bar
immersive.preconfirms ?

The values corresponding to these keys can be combined with commas as as follows:

value meaning
apps All applications
* All interfaces
packagename Specify application
-packagename Exclude specified applications

For example:

adb shell settings put global policy_control immersive.full=*

Indicates that the status bar and navigation bar are hidden under all interfaces.

adb shell settings put global policy_control immersive.status=com.package1,com.package2:immersive.navigation=apps,-com.package3

Indicates that it is set in the package name com Package1 and com The status bar is hidden in the application of package 2, except that the package name is com The navigation bar is hidden in all applications of package 3.

Practical function

Screenshot

Save screenshot to computer:

adb exec-out screencap -p > sc.png

If the adb version is too old to use the exec out command, it is recommended to update the adb version at this time. If it cannot be updated, the following troublesome methods can be used:

Save the screenshot to the device first:

adb shell screencap -p /sdcard/sc.png

Then export the png file to your computer:

adb pull /sdcard/sc.png

You can use adb shell screencap -h to view the help information of the screencap command. Here are two meaningful parameters and their meanings:

parameter meaning
-p Specifies that the saved file is in png format
-d display-id Specify the screen number of the screenshot (in case of multiple screens)

If you specify a file name, use The - p parameter can be omitted at the end of png; Otherwise, you need to use the - p parameter. If the file name is not specified, the contents of the screenshot file will be output directly to stdout.

Another method is to save the screenshot of one line command to the computer:

Linux and Windows

adb shell screencap -p | sed "s/\r$//" > sc.png

Mac OS X

adb shell screencap -p | gsed "s/\r$//" > sc.png

This method requires the gnu sed command, which is available directly under Linux and under the bin folder of Git installation directory under Windows. If you really can't find the command, you can download it sed for Windows And set sed Add the folder where exe is located to the PATH environment variable.

On the Mac, using the sed command provided by the system will report an error:

sed: RE error: illegal byte sequence

You need to install GNU sed, and then use the gsed command:

brew install gnu-sed

Recording screen

Save the recording screen in mp4 format to / sdcard:

adb shell screenrecord /sdcard/filename.mp4

Press Ctrl-C when you need to stop. The default recording time and the maximum recording time are 180 seconds.

If you need to export to a computer:

adb pull /sdcard/filename.mp4

You can use adb shell screenrecord --help to view the help information of the screenrecord command. The following are common parameters and meanings:

parameter meaning
–size WIDTHxHEIGHT The size of the video, such as 1280x720, defaults to the screen resolution.
–bit-rate RATE The bit rate of video. The default is 4Mbps.
–time-limit TIME Recording duration, in seconds.
–verbose Output more information.

Remount the system partition to writable

Note: root permission is required.

/The system partition is mounted as read-only by default, but some operations, such as adding commands to the Android system and deleting self-contained applications, need to write to / system, so it needs to be re mounted as read-write.

Steps:

  1. Enter the shell and switch to root.

    Command:

    adb shell
    su
    
  2. View the current partition mounting status.

    Command:

    mount
    

    Output example:

    rootfs / rootfs ro,relatime 0 0
    tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,mode=755 0 0
    devpts /dev/pts devpts rw,seclabel,relatime,mode=600 0 0
    proc /proc proc rw,relatime 0 0
    sysfs /sys sysfs rw,seclabel,relatime 0 0
    selinuxfs /sys/fs/selinux selinuxfs rw,relatime 0 0
    debugfs /sys/kernel/debug debugfs rw,relatime 0 0
    none /var tmpfs rw,seclabel,relatime,mode=770,gid=1000 0 0
    none /acct cgroup rw,relatime,cpuacct 0 0
    none /sys/fs/cgroup tmpfs rw,seclabel,relatime,mode=750,gid=1000 0 0
    none /sys/fs/cgroup/memory cgroup rw,relatime,memory 0 0
    tmpfs /mnt/asec tmpfs rw,seclabel,relatime,mode=755,gid=1000 0 0
    tmpfs /mnt/obb tmpfs rw,seclabel,relatime,mode=755,gid=1000 0 0
    none /dev/memcg cgroup rw,relatime,memory 0 0
    none /dev/cpuctl cgroup rw,relatime,cpu 0 0
    none /sys/fs/cgroup tmpfs rw,seclabel,relatime,mode=750,gid=1000 0 0
    none /sys/fs/cgroup/memory cgroup rw,relatime,memory 0 0
    none /sys/fs/cgroup/freezer cgroup rw,relatime,freezer 0 0
    /dev/block/platform/msm_sdcc.1/by-name/system /system ext4 ro,seclabel,relatime,data=ordered 0 0
    /dev/block/platform/msm_sdcc.1/by-name/userdata /data ext4 rw,seclabel,nosuid,nodev,relatime,noauto_da_alloc,data=ordered 0 0
    /dev/block/platform/msm_sdcc.1/by-name/cache /cache ext4 rw,seclabel,nosuid,nodev,relatime,data=ordered 0 0
    /dev/block/platform/msm_sdcc.1/by-name/persist /persist ext4 rw,seclabel,nosuid,nodev,relatime,data=ordered 0 0
    /dev/block/platform/msm_sdcc.1/by-name/modem /firmware vfat ro,context=u:object_r:firmware_file:s0,relatime,uid=1000,gid=1000,fmask=0337,dmask=0227,codepage=cp437,iocharset=iso8859-1,shortname=lower,errors=remount-ro 0 0
    /dev/fuse /mnt/shell/emulated fuse rw,nosuid,nodev,relatime,user_id=1023,group_id=1023,default_permissions,allow_other 0 0
    /dev/fuse /mnt/shell/emulated/0 fuse rw,nosuid,nodev,relatime,user_id=1023,group_id=1023,default_permissions,allow_other 0 0
    

    Find the line with / system that we focus on:

    /dev/block/platform/msm_sdcc.1/by-name/system /system ext4 ro,seclabel,relatime,data=ordered 0 0
    
  3. Remount.

    Command:

    mount -o remount,rw -t yaffs2 /dev/block/platform/msm_sdcc.1/by-name/system /system
    

    Here, / dev / block / platform / MSM_ sdcc. 1 / by name / system is the file path we got from the output of the previous step.

If the output does not prompt an error, the operation is successful and you can do whatever you want to do with the files under / system.

View connected WiFi passwords

Note: root permission is required.

Command:

adb shell
su
cat /data/misc/wifi/*.conf

Output example:

network={
	ssid="TP-LINK_9DFC"
	scan_ssid=1
	psk="123456789"
	key_mgmt=WPA-PSK
	group=CCMP TKIP
	auth_alg=OPEN
	sim_num=1
	priority=13893
}

network={
	ssid="TP-LINK_F11E"
	psk="987654321"
	key_mgmt=WPA-PSK
	sim_num=1
	priority=17293
}

ssid is the name we see in WLAN settings, psk is the password, and key is the password_ Mgmt is a secure encryption method.

Set system date and time

Note: root permission is required.

Command:

adb shell
su
date -s 20160823.131500

It means to change the system date and time to 13:15:00 on August 23, 2016.

Restart the phone

Command:

adb reboot

Check whether the device is root

Command:

adb shell
su

At this time, if the command prompt is $, it means that you do not have root permission, and if # it means that you have root.

Use Monkey for stress test

Monkey can generate pseudo-random user events to simulate click, touch, gesture and other operations, and can conduct random stress test on the program under development.

Simple usage:

adb shell monkey -p <packagename> -v 500

Indicates that 500 pseudo-random events are sent to the application specified by < packagename >.

Monkey's detailed usage reference Official documents.

Turn WiFi on / off

Note: root permission is required.

Sometimes it is necessary to control the WiFi status of the device, which can be completed with the following instructions.

Turn on WiFi:

adb root
adb shell svc wifi enable

Turn off WiFi:

adb root
adb shell svc wifi disable

If the execution is successful, the output is null; If you execute this command without root permission, the execution will fail and the output is Killed.

Brush related commands

Restart to Recovery mode

Command:

adb reboot recovery

Restart from Recovery to Android

Command:

adb reboot

Restart to Fastboot mode

Command:

adb reboot bootloader

Update the system through sideload

If we download the system update package corresponding to the Android device to the computer, we can also complete the update through adb.

Take the update in Recovery mode as an example:

  1. Restart to Recovery mode.

    Command:

    adb reboot recovery
    
  2. On the Recovery interface of the device, enter apply update apply from ADB.

    Note: different Recovery menus may be different from this. Some level-1 menus have Apply update from ADB.

  3. Upload and update the system through adb.

    Command:

    adb sideload <path-to-update.zip>
    

Safety related commands

Enable / disable SELinux

Enable SELinux

adb root
adb shell setenforce 1

Disable SELinux

adb root
adb shell setenforce 0

Enable / disable dm_verity

Enable dm_verity

adb root
adb enable-verity

Disable dm_verity

adb root
adb disable-verity

More adb shell commands

Android system is based on Linux kernel, so many commands in Linux have the same or similar implementation in Android, which can be called in adb shell. The adb shell command has been used earlier in this document.

View process

Command:

adb shell ps

Output example:

USER     PID   PPID  VSIZE  RSS     WCHAN    PC        NAME
root      1     0     8904   788   ffffffff 00000000 S /init
root      2     0     0      0     ffffffff 00000000 S kthreadd
...
u0_a71    7779  5926  1538748 48896 ffffffff 00000000 S com.sohu.inputmethod.sogou:classic
u0_a58    7963  5926  1561916 59568 ffffffff 00000000 S org.mazhuang.boottimemeasure
...
shell     8750  217   10640  740   00000000 b6f28340 R ps

Meaning of each column:

Listing meaning
USER User
PID Process ID
PPID Parent process ID
NAME Process name

View real-time resource usage

Command:

adb shell top

Output example:

User 0%, System 6%, IOW 0%, IRQ 0%
User 3 + Nice 0 + Sys 21 + Idle 280 + IOW 0 + IRQ 0 + SIRQ 3 = 307

  PID PR CPU% S  #THR     VSS     RSS PCY UID      Name
 8763  0   3% R     1  10640K   1064K  fg shell    top
  131  0   3% S     1      0K      0K  fg root     dhd_dpc
 6144  0   0% S   115 1682004K 115916K  fg system   system_server
  132  0   0% S     1      0K      0K  fg root     dhd_rxf
 1731  0   0% S     6  20288K    788K  fg root     /system/bin/mpdecision
  217  0   0% S     6  18008K    356K  fg shell    /sbin/adbd
 ...
 7779  2   0% S    19 1538748K  48896K  bg u0_a71   com.sohu.inputmethod.sogou:classic
 7963  0   0% S    18 1561916K  59568K  fg u0_a58   org.mazhuang.boottimemeasure
 ...

Meaning of each column:

Listing meaning
PID Process ID
PR priority
CPU% Current instantaneous CPU percentage
S Process status (R = running, S = sleeping, T = tracking / stopping, Z = zombie process)
#THR Number of threads
VSS Virtual Set Size virtual memory consumption (including memory occupied by shared libraries)
RSS Resident Set Size physical memory actually used (including memory occupied by shared libraries)
PCY Scheduling policy priority, SP_BACKGROUND/SPFOREGROUND
UID User ID of the process owner
NAME Process name

The top command also supports some command line parameters. The detailed usage is as follows:

Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]
    -m num  How many processes are displayed at most
    -n num  How many times to refresh and exit
    -d num  Refresh interval (in seconds, default 5)
    -s col  Sort by column (available) col Value: cpu, vss, rss, thr)
    -t      Display thread information
    -h      Display help documents

View process UID

There are two options:

  1. adb shell dumpsys package <packagename> | grep userId=

    For example:

    $ adb shell dumpsys package org.mazhuang.guanggoo | grep userId=
       userId=10394
    
  2. After finding the pid of the corresponding process through ps command, ADB shell cat / proc / < pid > / status | grep UID

    For example:

    $ adb shell
    gemini:/ $ ps | grep org.mazhuang.guanggoo
    u0_a394   28635 770   1795812 78736 SyS_epoll_ 0000000000 S org.mazhuang.guanggoo
    gemini:/ $ cat /proc/28635/status | grep Uid
    Uid:    10394   10394   10394   10394
    gemini:/ $
    

other

The following is a brief description of other commonly used commands. The commands mentioned above will not be described separately:

command function
cat Display file contents
cd Switch directory
chmod Change the access mode / permission of the file
df View disk space usage
grep Filter output
kill Kill the process with the specified PID
ls List directory contents
mount View and management of Mount directory
mv Move or rename files
ps View running processes
rm Delete file
top View the resource usage of the process

common problem

Failed to start adb server

Error prompt

error: protocol fault (couldn't read status): No error

Possible causes

The 5037 port that the adb server process wants to use is occupied.

Solution

Locate the process occupying port 5037 and terminate it. Take Windows as an example:

netstat -ano | findstr LISTENING

...
TCP    0.0.0.0:5037           0.0.0.0:0              LISTENING       1548
...

Here 1548 is the process ID. end the process with the command:

taskkill /PID 1548

Then you can start adb again.

com.android.ddmlib.AdbCommandRejectedException

Create a new simulator in Android Studio, but you can't connect it with adb. Tips:

com.android.ddmlib.AdbCommandRejectedException: device unauthorized.
This adb server's $ADB_VENDOR_KEYS is not set
Try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.

It is not normal to install a terminal on the mobile phone and then execute su prompt without this command.

So delete the simulator and download and install it again. This time it will be normal.

The unofficial implementation of adb

  • fb-adb - A better shell for Android devices (for Mac).

Related commands

thank

Thank you for your selfless sharing and supplement (ranking in no order).

zxninglinhua55codeskyblueseasonyuufan123199zhEdward0x8BADFOODkeith666666shawnlinboys-xq
lucky9322.

Reference link

Tags: Android adb

Posted by jayskates on Sat, 07 May 2022 15:09:24 +0300