30 November 2024
Tech-Help
Understanding which activity is currently running on your Android device can be crucial for debugging and development purposes. This guide will walk you through various methods to determine the current activity using ADB (Android Debug Bridge) commands. Each method has its advantages, and your choice may depend on your operating system and Android version.
Using ADB to Find the Current Activity
One effective way to determine the currently running activity is by utilizing the dumpsys
command. Below are the steps and corresponding commands you can use:
Method 1: Using dumpsys window windows
This method involves using the mCurrentFocus
and mFocusedApp
attributes from the window
service:
adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
This command is useful for identifying the current focus on the screen, which includes activities like the lock screen or recent tasks list.
Method 2: Using dumpsys activity activities
For devices running Android Q and newer, the following command has proven effective:
adb shell "dumpsys activity activities | grep ResumedActivity"
This command will provide the ResumedActivity
, indicating the activity currently in the foreground.
Method 3: Using dumpsys activity top
For a detailed view of the activity stack, you can use:
adb shell dumpsys activity top | grep "ACTIVITY"
This command gives a list of activities, with the one in the foreground listed last.
Considerations for Different Operating Systems
When using these commands on Windows, ensure that you use double quotes around the command string. This ensures that the command is executed within the Android shell rather than your host OS.
Leveraging Automation with Repeato
While manual methods are effective, automating your testing process can save time and reduce errors. Our product, Repeato, a no-code test automation tool for iOS and Android, can significantly streamline this process. With features like ADB command execution and AI-driven test automation, Repeato allows for precise control and rapid testing iterations. This can be especially beneficial when dealing with complex activity transitions and ensuring that your app behaves as expected across different scenarios.
For more advanced testing techniques, visit our documentation.
Whether you’re debugging or developing new features, understanding the current activity state is crucial. By using the methods outlined above and integrating tools like Repeato, you can enhance your development workflow and ensure robust app performance.
Like this article? there’s more where that came from!
-
Resolving the “xcrun: error: invalid active developer path” Error on macOS
-
Adding Existing Frameworks in Xcode 4: A Comprehensive Guide
-
Disabling ARC for a Single File in Xcode: A Step-by-Step Guide
-
Resolving the Xcode-Select Active Developer Directory Error
-
Resolving the “Multiple Commands Produce” Error in Xcode 10
Android Debug Bridge (adb) is a robust command-line tool that allows you to communicate with a connected Android device. Using adb
commands, you can perform a variety of device actions, such as installing apps, granting permissions, profiling for performance, etc.
In this guide, you will learn the following:
- ADB Commands use cases in an App Automate session
- Achieve Equivalent functionalities without using ADB Commands
ADB Commands use cases
For security reasons, we launch the appium server on our platform with --relaxed-security
setting off. This means that we won’t be able to support execution of ADB shell commands using the mobile: shell
appium command. More details in Appium documentation. However, we provide custom implementation to run certain useful ADB commands on our Android devices.
This section provides details on how to run adb commands for the following use cases in an App Automate session:
- Log and Debug Firebase Analytics events
- Log Google Analytics events
- Set system-level preferences using settings commands
- Get diagnostic output for system services using dumpsys commands
- Get system and device properties using getprop commands
Currently, we support only those adb commands that have been mentioned in this guide.
Important:
Ensure OS version is specified using the os_version capability while using the browserstack.devicePreferences
capability in your tests.
Log and Debug Firebase Analytics events
Log Events
You can set verbose logging to monitor the logs of Firebase events using the following adb shell setprop
commands:
adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
In order to achieve this functionality in App Automate, use the browserstack.devicePreferences capability in your test sessions and set the log.tag.FA
and log.tag.FA-SVC
tags to VERBOSE
inside the setprop
object. The following code snippet demonstrates how to do this:
-
W3C Protocol
-
JSON Wire Protocol
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("log.tag.FA", "VERBOSE");
setProp.put("log.tag.FA-SVC", "VERBOSE");
devicePreferences.put("setprop", setProp);
browserstackOptions.put("devicePreferences", devicePreferences);
capabilities.setCapability("bstack:options", browserstackOptions);
var capabilities = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"log.tag.FA" : "VERBOSE",
"log.tag.FA-SVC" : "VERBOSE"
}
}
}
}
desired_cap = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"log.tag.FA" : "VERBOSE",
"log.tag.FA-SVC" : "VERBOSE"
}
}
}
}
desired_cap = {
"bstack:options"=> {
"devicePreferences"=> {
"setprop" => {
"log.tag.FA" => "VERBOSE",
"log.tag.FA-SVC" => "VERBOSE"
}
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("log.tag.FA", "VERBOSE");
setProp.Add("log.tag.FA-SVC", "VERBOSE");
devicePreferences.Add("setprop", setProp);
browserstackOptions.Add("devicePreferences", devicePreferences);
capabilities.AddAdditionalCapability("bstack:options", browserstackOptions);
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("log.tag.FA", "VERBOSE");
setProp.put("log.tag.FA-SVC", "VERBOSE");
devicePreferences.put("setprop", setProp);
capabilities.setCapability("browserstack.devicePreferences", devicePreferences);
var capabilities = {
"browserstack.devicePreferences": {
"setprop" : {
"log.tag.FA" : "VERBOSE",
"log.tag.FA-SVC" : "VERBOSE"
}
}
}
desired_cap = {
"browserstack.devicePreferences": {
"setprop" : {
"log.tag.FA" : "VERBOSE",
"log.tag.FA-SVC" : "VERBOSE"
}
}
}
desired_cap = {
"browserstack.devicePreferences"=> {
"setprop" => {
"log.tag.FA" => "VERBOSE",
"log.tag.FA-SVC" => "VERBOSE"
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("log.tag.FA", "VERBOSE");
setProp.Add("log.tag.FA-SVC", "VERBOSE");
devicePreferences.Add("setprop", setProp);
capabilities.AddAdditionalCapability("browserstack.devicePreferences", devicePreferences);
Upon setting this capability in your tests, logs for Firebase events will start appearing under device logs. You can capture the complete logs by using driver.manage().logs().get("logcat").filter(Level.ALL);
command and then filter out the firebase events for your app in your test.
Debug Events
You can enable the debug mode for Firebase Analytics on an Android device by using the following adb shell setprop
command:
adb shell setprop debug.firebase.analytics.app <PACKAGE_NAME>
To achieve this functionality in App Automate, use the browserstack.devicePreferences capability in your test sessions and set the debug.firebase.analytics.app
value to your package_name
inside the setprop
object. The following code snippet demonstrates how to do this:
-
W3C Protocol
-
JSON Wire Protocol
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("debug.firebase.analytics.app", "<your_package_name>");
devicePreferences.put("setprop", setProp);
browserstackOptions.put("devicePreferences", devicePreferences);
capabilities.setCapability("bstack:options", browserstackOptions);
var capabilities = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"debug.firebase.analytics.app" : "<your_package_name>"
}
}
}
}
desired_cap = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"debug.firebase.analytics.app" : "<your_package_name>"
}
}
}
}
desired_cap = {
"bstack:options"=> {
"devicePreferences"=> {
"setprop" => {
"debug.firebase.analytics.app" => "<your_package_name>"
}
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("debug.firebase.analytics.app", "<your_package_name>");
devicePreferences.Add("setprop", setProp);
browserstackOptions.Add("devicePreferences", devicePreferences);
capabilities.AddAdditionalCapability("bstack:options", browserstackOptions);
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("debug.firebase.analytics.app", "<your_package_name>");
devicePreferences.put("setprop", setProp);
capabilities.setCapability("browserstack.devicePreferences", devicePreferences);
var capabilities = {
"browserstack.devicePreferences": {
"setprop" : {
"debug.firebase.analytics.app" : "<your_package_name>"
}
}
}
desired_cap = {
"browserstack.devicePreferences": {
"setprop" : {
"debug.firebase.analytics.app" : "<your_package_name>"
}
}
}
desired_cap = {
"browserstack.devicePreferences"=> {
"setprop" => {
"debug.firebase.analytics.app" => "<your_package_name>"
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("debug.firebase.analytics.app", "<your_package_name>");
devicePreferences.Add("setprop", setProp);
capabilities.AddAdditionalCapability("browserstack.devicePreferences", devicePreferences);
Upon setting this capability in your tests, your test session will begin on a device where debug mode has been enabled. You can then navigate to DebugView to view your app’s events being logged in the DebugView report.
Log Google Analytics events
You can enable the log feature of Google Analytics events by using the following adb shell setprop
command:
adb shell setprop log.tag.GAv4 DEBUG
To achieve this functionality in App Automate, use the browserstack.devicePreferences capability in your test sessions and set the log.tag.GAv4
tag to any of the log filter types such as DEBUG
, VERBOSE
, INFO
etc inside the setprop
object. The following code snippet demonstrates how to do this:
-
W3C Protocol
-
JSON Wire Protocol
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("log.tag.GAv4", "DEBUG");
devicePreferences.put("setprop", setProp);
browserstackOptions.put("devicePreferences", devicePreferences);
capabilities.setCapability("bstack:options", browserstackOptions);
var capabilities = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"log.tag.GAv4" : "DEBUG"
}
}
}
}
desired_cap = {
"bstack:options": {
"devicePreferences": {
"setprop" : {
"log.tag.GAv4" : "DEBUG"
}
}
}
}
desired_cap = {
"bstack:options" => {
"devicePreferences"=> {
"setprop" => {
"log.tag.GAv4" => "DEBUG"
}
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("log.tag.GAv4", "DEBUG");
devicePreferences.Add("setprop", setProp);
browserstackOptions.Add("devicePreferences", devicePreferences);
capabilities.AddAdditionalCapability("bstack:options", browserstackOptions);
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, String> setProp = new HashMap<>();
setProp.put("log.tag.GAv4", "DEBUG");
devicePreferences.put("setprop", setProp);
capabilities.setCapability("browserstack.devicePreferences", devicePreferences);
var capabilities = {
"browserstack.devicePreferences": {
"setprop" : {
"log.tag.GAv4" : "DEBUG"
}
}
}
desired_cap = {
"browserstack.devicePreferences": {
"setprop" : {
"log.tag.GAv4" : "DEBUG"
}
}
}
desired_cap = {
"browserstack.devicePreferences"=> {
"setprop" => {
"log.tag.GAv4" => "DEBUG"
}
}
}
DesiredCapabilities capabilities = new DesiredCapabilities();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, string> setProp = new Dictionary<>();
setProp.Add("log.tag.GAv4", "DEBUG");
devicePreferences.Add("setprop", setProp);
capabilities.SetCapability("browserstack.devicePreferences", devicePreferences);
Upon setting this capability in your tests, logs for Google Analytics events will start appearing under device logs. You can capture the complete logs by using driver.manage().logs().get("logcat").filter(Level.ALL);
command and then filter out the Google Analytics events for your app in your test.
Set system-level preferences using settings commands
The adb shell settings put
commands can be used to set system-level device preferences such as disabling pop-up notifications, disabling location services, changing device orientation etc.
The following table lists all the adb shell settings put
commands that are supported in App Automate:
Command | Description | Allowed Values |
---|---|---|
adb shell settings put secure location_mode 0 |
Enable/Disable location services on an android device | Disable: 0 Enable: 3 |
adb shell settings put global heads_up_notifications_enabled 0 |
Enable/Disable pop-up notifications on an android device | Disable: 0 Enable: 1 |
adb shell settings put global always_finish_activities 0 |
Enable/Disable aggressive finishing of activities and processes | Disable: 0 Enable: 1 |
adb shell settings put system accelerometer_rotation 0 |
Enable/Disable auto-rotation of the device | Disable: 0 Enable: 1 |
adb shell settings put system user_rotation 3 |
Rotate the device | 0° clockwise rotation: 0 90° clockwise rotation: 1 180° clockwise rotation: 2 270° clockwise rotation: 3 |
Important:
The location_mode
setting can only be used on API level 19 (Android Version 4.4) to API level 28 (Android Version 9) devices.
To execute these commands, use the browserstack.devicePreferences capability in your tests and set the required settings to your desired values inside the appropriate setting type object. The following table shows the BrowserStack compatible JSON-object format for the settings:
Command | BrowserStack Compatible JSON input |
---|---|
adb shell settings put secure location_mode 0 |
{“browserstack.devicePreferences”: { “settings.secure”: { “locationMode” : 0}}} |
adb shell settings put global heads_up_notifications_enabled 0 |
{“browserstack.devicePreferences”: { “settings.global”: { “headsUpNotificationsEnabled” : 0}}} |
adb shell settings put global always_finish_activities 0 |
{“browserstack.devicePreferences”: { “settings.global”: { “alwaysFinishActivities” : 0}}} |
adb shell settings put system accelerometer_rotation 0 |
{“browserstack.devicePreferences”: { “settings.system”: { “accelerometerRotation” : 0}}} |
adb shell settings put system user_rotation 3 |
{“browserstack.devicePreferences”: { “settings.system”: { “userRotation” : 3}}} |
The following code snippet demonstrates how to run your tests on a device where all the above mentioned settings have been set:
-
W3C Protocol
-
JSON Wire Protocol
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, Integer> settingsGlobal = new HashMap<>();
settingsGlobal.put("headsUpNotificationsEnabled", 0);
settingsGlobal.put("alwaysFinishActivities", 0);
devicePreferences.put("settings.global", settingsGlobal);
HashMap<String, Integer> settingsSecure = new HashMap<>();
settingsSecure.put("locationMode", 0);
devicePreferences.put("settings.secure", settingsSecure);
HashMap<String, Integer> settingsSystem = new HashMap<>();
settingsSystem.put("accelerometerRotation", 0);
settingsSystem.put("userRotation", 3);
devicePreferences.put("settings.system", settingsSystem);
browserstackOptions.put("devicePreferences", devicePreferences);
capabilities.setCapability("bstack:options", browserstackOptions);
var capabilities = {
"bstack:options": {
"devicePreferences": {
"settings.global": {
"headsUpNotificationsEnabled": 0,
"alwaysFinishActivities" : 0
},
"settings.secure": {
"locationMode" : 0
},
"settings.system": {
"accelerometerRotation" : 0,
"userRotation" : 3
}
}
}
}
desired_cap = {
"bstack:options": {
"devicePreferences": {
"settings.global": {
"headsUpNotificationsEnabled": 0,
"alwaysFinishActivities" : 0
},
"settings.secure": {
"locationMode" : 0
},
"settings.system": {
"accelerometerRotation" : 0,
"userRotation" : 3
}
}
}
}
desired_cap = {
"bstack:options" => {
"devicePreferences" => {
"settings.global"=> {
"headsUpNotificationsEnabled"=> 0,
"alwaysFinishActivities" => 0
},
"settings.secure"=> {
"locationMode" => 0
},
"settings.system"=> {
"accelerometerRotation" => 0,
"userRotation" => 3
}
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, int> settingsGlobal = new Dictionary<>();
settingsGlobal.Add("headsUpNotificationsEnabled", 0);
settingsGlobal.Add("alwaysFinishActivities", 0);
devicePreferences.Add("settings.global", settingsGlobal);
Dictionary<string, int> settingsSecure = new Dictionary<>();
settingsSecure.Add("locationMode", 0);
devicePreferences.Add("settings.secure", settingsSecure);
Dictionary<string, int> settingsSystem = new Dictionary<>();
settingsSystem.Add("accelerometerRotation", 0);
settingsSystem.Add("userRotation", 3);
devicePreferences.Add("settings.system", settingsSystem);
browserstackOptions.Add("devicePreferences", devicePreferences);
capabilities.AddAdditionalCapability("bstack:options", browserstackOptions);
- Java
- Node.js
- Python
- Ruby
- C#
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> devicePreferences = new HashMap<String, Object>();
HashMap<String, Integer> settingsGlobal = new HashMap<>();
settingsGlobal.put("headsUpNotificationsEnabled", 0);
settingsGlobal.put("alwaysFinishActivities", 0);
devicePreferences.put("settings.global", settingsGlobal);
HashMap<String, Integer> settingsSecure = new HashMap<>();
settingsSecure.put("locationMode", 0);
devicePreferences.put("settings.secure", settingsSecure);
HashMap<String, Integer> settingsSystem = new HashMap<>();
settingsSystem.put("accelerometerRotation", 0);
settingsSystem.put("userRotation", 3);
devicePreferences.put("settings.system", settingsSystem);
capabilities.setCapability("browserstack.devicePreferences", devicePreferences);
var capabilities = {
"browserstack.devicePreferences": {
"settings.global": {
"headsUpNotificationsEnabled": 0,
"alwaysFinishActivities" : 0
},
"settings.secure": {
"locationMode" : 0
},
"settings.system": {
"accelerometerRotation" : 0,
"userRotation" : 3
}
}
}
desired_cap = {
"browserstack.devicePreferences": {
"settings.global": {
"headsUpNotificationsEnabled": 0,
"alwaysFinishActivities" : 0
},
"settings.secure": {
"locationMode" : 0
},
"settings.system": {
"accelerometerRotation" : 0,
"userRotation" : 3
}
}
}
desired_cap = {
"browserstack.devicePreferences"=> {
"settings.global"=> {
"headsUpNotificationsEnabled"=> 0,
"alwaysFinishActivities" => 0
},
"settings.secure"=> {
"locationMode" => 0
},
"settings.system"=> {
"accelerometerRotation" => 0,
"userRotation" => 3
}
}
}
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> devicePreferences = new Dictionary<string, object>();
Dictionary<string, int> settingsGlobal = new Dictionary<>();
settingsGlobal.Add("headsUpNotificationsEnabled", 0);
settingsGlobal.Add("alwaysFinishActivities", 0);
devicePreferences.Add("settings.global", settingsGlobal);
Dictionary<string, int> settingsSecure = new Dictionary<>();
settingsSecure.Add("locationMode", 0);
devicePreferences.Add("settings.secure", settingsSecure);
Dictionary<string, int> settingsSystem = new Dictionary<>();
settingsSystem.Add("accelerometerRotation", 0);
settingsSystem.Add("userRotation", 3);
devicePreferences.Add("settings.system", settingsSystem);
devicePreferences.Add("settings.global", settingsGlobal);
capabilities.AddAdditionalCapability("browserstack.devicePreferences", devicePreferences);
Get diagnostic output for system services using dumpsys commands
dumpsys is a tool that runs on Android devices and offers information on system services. adb shell dumpsys
commands provide vital diagnostic output for system services operating on a connected device.
The following table lists all the dumpsys
commands that can be used in an App Automate session:
-
Activities
-
UI Performance
-
Input
-
Device
-
Networks
-
Battery
-
Memory
-
Package
Command | Description |
---|---|
adb shell dumpsys activity -p <package_name> |
Provides complete activity history for the given package |
adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp' |
Prints current app’s opened activity |
adb shell dumpsys activity -p <package_name> activities |
Provides activity manager activities that contain main stack, running activities and recent tasks |
adb shell dumpsys activity -p <package_name> activities | grep -E ‘mResumedActivity’ |
Prints current app’s resumed activity |
adb shell dumpsys activity -p <package_name> services |
Provides list of services running for the given package |
adb shell dumpsys activity -p <package_name> providers |
Provides list of current content providers for the given package |
adb shell dumpsys activity -p <package_name> recents |
Provides list of recent tasks for the given package |
adb shell dumpsys activity -p <package_name> broadcasts |
Provides list of broadcast states for the given package |
adb shell dumpsys activity -p <package_name> intents |
Provides list of pending intents for the given package |
adb shell dumpsys activity -p <package_name> permissions |
Provides list of permissions for the given package |
adb shell dumpsys activity -p <package_name> processes |
Provides list of running processes for the given package |
Command | Description |
---|---|
adb shell dumpsys gfxinfo <package_name> |
Gathers UI performance data for a specified package name |
adb shell dumpsys gfxinfo <package_name> framestats |
Provides even more detailed frame timing information from recent frames |
adb shell dumpsys gfxinfo <package_name> reset |
Resets the framemetrics data |
Command | Description |
---|---|
adb shell dumpsys input |
Dumps the state of the system’s input devices, such as keyboards and touchscreens, and the processing of input events |
Command | Description |
---|---|
adb shell dumpsys cpuinfo |
Provides info on CPU usage |
adb shell dumpsys display |
Provides info on display |
adb shell dumpsys power |
Provides info on power statistics |
adb shell dumpsys alarm |
Provides info on alarm |
adb shell dumpsys location |
Provides info on location |
adb shell dumpsys window displays |
Provides info like pixel resolution, FPS, and DPI of the device’s display |
adb shell dumpsys telephony.registry |
Gives information about wireless communication related parameters |
adb shell dumpsys bluetooth_manager |
Gives information about connected bluetooth devices, mac addresses etc. |
Command | Description |
---|---|
adb shell dumpsys netstats |
Displays network connections for the Transmission Control Protocol for both incoming and outgoing requests |
adb shell dumpsys netstats detail |
Outputs additional information, such as detailed unique user ID (UID) information |
adb shell dumpsys connectivity |
Provides the internet status and connectivity mode(cellular or Wi-Fi) |
adb shell dumpsys netpolicy |
Generates a report that includes the current global background network restriction setting, package UIDs that are currently allowed to bypass Data Saver, and the network permissions of other known packages |
adb shell dumpsys network_management |
Provides all information about device network management |
Command | Description |
---|---|
adb shell dumpsys batterystats options |
Generates interesting statistical data about battery usage on a device, organized by unique user ID (UID) |
adb shell dumpsys batterystats --charged <package_name> |
Outputs battery usage statistics for a specified app package since the device was last charged |
adb shell dumpsys batterystats --checkin |
Output in machine-readable CSV format |
Command | Description |
---|---|
adb shell dumpsys procstats --hours <hour> |
Provides info on how your app is behaving over time—including how long it runs in the background and how much memory it uses during that time |
adb shell dumpsys meminfo <package_name|pid> |
Record a snapshot of how your app’s memory is divided between different types of RAM allocation |
adb shell dumpsys meminfo <package_name|pid> [-d] |
The -d flag prints more info related to Dalvik and ART memory usage |
Command | Description |
---|---|
adb shell dumpsys package <package_name> |
Provides all the info about your app, ex: Version name/code, first install time, last update time, requested permissions, etc |
Use the following code snippets to call the dumpsys
commands from your test script:
- Java
- Node.js
- Python
- Ruby
- C#
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"dumpsys gfxinfo <package_name>\"
}
}"
);
await driver.execute("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"dumpsys gfxinfo <package_name>\"
}
}"
);
driver.execute_script("browserstack_executor: {
\"action\":\"adbShell",
\"arguments\": {
\"command\" : \"dumpsys gfxinfo <package_name>\"
}
}"
);
caps["javascriptEnabled"] = "true" #include this capability for JavaScript Executors to work
driver.execute_script("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"dumpsys gfxinfo <package_name>\"
}
}"
);
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"dumpsys gfxinfo <package_name>\"
}
}"
);
The output of the above-mentioned dumpsys
commands would be captured under text logs on the App Automate dashboard.
Note:
For grep commands like adb shell dumpsys activity -p <package_name> activities | grep -E 'mResumedActivity'
, please ensure that the JSON is in one of the following formats:
driver.execute_script("browserstack_executor: {\"action\":\"adbShell\", \"arguments\": {\"command\" : \"dumpsys activity -p <package_name> activities | grep -E \\\"mResumedActivity\\\"\"}}")
OR
driver.execute_script('browserstack_executor: {"action":"adbShell", "arguments": {"command" : "dumpsys activity -p <package_name> activities | grep -E \"mResumedActivity\""}}')
Get system and device properties using getprop commands
The adb shell getprop
commands can be used to get system and device properties such as Sim Operator, device model, Android version etc.
The following table lists all the getprop
commands that can be called in an App Automate session:
Command | Description |
---|---|
adb shell getprop -T |
Provides a list of system property types |
adb shell getprop gsm.sim.operator.alpha |
Provides SIM Operator |
adb shell getprop ro.build.version.release |
Provides device android version |
adb shell getprop ro.boot.wifimacaddr |
Provides the WiFi Mac Address |
adb shell getprop ro.product.manufacturer |
Provides Android device manufacturer details |
adb shell getprop ro.vendor.product.model |
Provides Android device product number |
adb shell getprop ro.board.platform |
Provides Soc info |
adb shell getprop ro.oem_unlock_supported |
Provides OEM unlock status |
adb shell getprop ro.vendor.product.model |
Provides device model |
adb shell getprop ro.bootimage.build.fingerprint |
Provides Android device build fingerprint |
adb shell getprop ro.cdma.home.operator.alpha |
Provides SIM operator name |
adb shell getprop ro.system.build.version.sdk |
Provides API level |
Important:
adb shell getprop -T
command can only be used on Android devices with version 8.1 and above.
Use the following code snipptes to call the getprop
commands from your test script:
- Java
- Node.js
- Python
- Ruby
- C#
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"getprop ro.system.build.version.sdk\"
}
}"
);
await driver.execute("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"getprop ro.system.build.version.sdk\"
}
}"
);
driver.execute_script("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"getprop ro.system.build.version.sdk\"
}
}"
);
caps["javascriptEnabled"] = "true" #include this capability for JavaScript Executors to work
driver.execute_script("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"getprop ro.system.build.version.sdk\"
}
}"
);
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {
\"action\":\"adbShell\",
\"arguments\": {
\"command\" : \"getprop ro.system.build.version.sdk\"
}
}"
);
The output of the above-mentioned getprop
commands would be captured under text logs on the App Automate dashboard.
We’re sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We’re continuously improving our docs. We’d love to know what you liked
-
This page has exactly what I am looking for
-
This content & code samples are accurate and up-to-date
-
The content on this page is easy to understand
-
Other (please tell us more below)
Any additional feedback?
Thank you for your valuable feedback
Привет, Хабр! Меня зовут Александр Карпенко, я QA Engineer в inDrive. Я подготовил эту статью для начинающих QA-специалистов. Ниже расскажу, как использовать Android Debug Bridge (ADB) в тестировании мобильных приложений и нужен ли вообще этот инструмент.
Я думаю, базовые знания в тестировании у вас уже есть — поэтому не буду описывать процесс подготовки и настройки. Возможности ADB постоянно расширяются, но я поделюсь приемами, которые пригодятся ежедневно. Мой рассказ — о тестировании мобильных приложений, поэтому речь пойдет о macOS из-за возможности эффективно работать со всеми популярными мобильными платформами. На других ОС примеры могут незначительно отличаться, да простят меня адепты Windows.
Для начала коснемся самых базовых команд, без которых дальнейшее повествование будет нелогичным.
Вывод списка подключенных устройств и соединение с устройством
Обычно мы работаем с одним девайсом, но иногда подключаем несколько устройств — например, по TCP/IP. Тогда указываем вручную, на каком из девайсов нужно выполнить команду. Выводим список всех подключенных устройств, чтобы получить идентификатор:
adb devices
— выводит список подключенных устройств. С ключом -l
будет расширенный список свойств. Полезно, если подключено несколько устройств и сразу непонятно, какое нам нужно.
Чтобы указать ADB, с каким устройством нужно работать, следует прописать серийный номер устройства после ключа -s
:
adb -s <serial_number> <command>
, где <serial_number>
— серийный номер устройства из списка и <command>
— команда, которую надо выполнить на устройстве.
Например, установка приложения на конкретное устройство из списка:
adb -s 32312b96 install user/download/app.apk
.
Еще один частый сценарий — одновременная работа с реальным девайсом и эмулятором, например, в роли исполнителя и заказчика. В таком случае легко различать девайсы не по серийному номеру, а с помощью ключей -d -e
после команды adb
.
Например,
adb -d install user/download/app.apk
— команда будет выполнена на реальном устройстве с ключем -e
на эмуляторе.
Также мы можем подключиться к устройству по TCP/IP, когда оно использует ту же Wi-Fi-сеть. Для этого подключаем устройство к ПК кабелем и меняем режим работы на девайсе с USB на TCP/IP командой adb tcpip 5555
.
Вычисляем IP-адрес устройства любым доступным способом. Например, через настройки телефона в общей информации или с помощью команды
adb shell ifconfig wlan0
.
Если к этому моменту вы уже отключили девайс от ПК, не забудьте дополнительно указать S/N устройства. Подключаемся к нему:
adb connect ip_address:5555
.
Отключить устройство можно командой
adb disconnect ip_address:5555
.
adb disconnect
— отключить все наши TCP/IP устройства.
Для возврата в режим работы по USB используем команду
adb usb
(нижний регистр важен).
Установка и удаление приложения, поиск пакета на устройстве
Установка приложения осуществляется командой
adb install <apk_path>
, где <apk_path>
— абсолютный путь до нашего APK-файла приложения.
Приведу несколько полезных ключей после команды install, которые часто используются:
-d
— переустановка с понижением версии. В противном случае будет ошибка Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
.
-r
— переустановить приложение с сохранением data.
-g
— выдать при установке все пермишены, прописанные в манифесте приложения. Например, приложение, установленное с таким ключом, не будет запрашивать у вас разрешение на гео или доступ к хранилищу для загрузки фото.
Удаление приложения происходит уже по имени пакета. Для этого нужно знать, как приложение регистрируется в системе. Используем оболочку Shell и менеджер пакетов Package Manager (pm).
Следующей командой выведем список всех установленных приложений:
adb shell pm list packages
.
Можно отфильтровать список по имени приложения. Это понадобится, если список довольно большой, но мы знаем, какое слово присутствует в названии пакета:
adb shell pm list packages | grep com.myApp
.
Также можно сделать вывод в отдельный файл и там найти нужный пакет:
adb shell pm list packages > /Users/username/packages.txt
.
Теперь, когда мы знаем, как вычислить имя пакета приложения. Вернемся к тому, как удалить его с устройства. Сделать это можно командой
adb uninstall com.myApp
.
adb uninstall -k com.myApp
— удаление приложения с сохранением data и кэша.
Отдельно приведу команду, которая часто может пригодиться:
adb shell pm clear com.myApp
— почистить кеш и data приложения.
Загрузка APK файла с девайса
Думаю, это весьма редкий случай. Но, возможно, кому-то пригодится, как однажды пригодилось мне. Все установленные приложения хранят свой APK в папке /data/app. Поэтому, зная имя пакета, можно найти место, куда установлено приложение, и скачать оттуда его APK. Для этого выполним команду
adb shell pm path com.myApp
— получим директорию установки приложения.
Это может выглядеть не совсем презентабельно:
package:/data/app/~~YcTsnr19yQR6ENa0q2EMag==/com.myApp—IHasf91SDB0erQLagc8j0Q==/base.apk
Но именно в таком виде нам и нужен этот путь. Немного забежим вперед и посмотрим, как можно скопировать на ПК с телефона нужный нам файл. Сделать это можно командой adb pull <crazyPath> /Users/username/
, где <crazyPath>
— результат вывода нашей предыдущей команды. А /Users/username/
— путь на ПК, куда нужно скопировать наш файл.
Текстовые поля
Немного коснемся проверки текстовых полей. Например, нужно проверить ограничение на ввод максимального числа символов в поле. Если вы пользуетесь одним устройством, можно хранить разные наборы передаваемых данных на самом телефоне или в облаке. Но когда приходится проверять на разных девайсах, можно хранить данные для тестирования на ПК и передавать их на устройства следующими командами:
adb shell input text <text>
.
Например:
adb shell input text test%stest
— будет введена строка «test test». Пробелы заменяем спецсимволами %s
, иначе на устройство будет передана только часть до пробела. Если в передаваемом тексте мы используем спецсимволы, вроде !@#
, нужно выделять их обратным слэшем (\
).
Например, команда
adb shell input text test\!\@\#\$%stest
выведет на экран “test!@#$ test”
.
Важно: ADB не работает с кириллицей, получим NullPointerException.
Существует способ передачи буфера обмена:
adb shell input text $(pbpaste)
.
Нужно помнить, что некоторые символы могут не передаваться в том виде, в котором они отображаются на ПК. Проблему можно решить с помощью потокового редактора текста sed. Приведу пример расширенной команды, где мы заменяем все пробелы в буфере на нужные нам спецсимволы для корректной передачи текста на девайс:
adb shell input text $(pbpaste | sed -e 's/ /\%s/g')
pbpaste
— текст, который содержится в буфере.
ключ «-e»
— позволяет выполнить команды, которые необходимы для редактирования текста.
«s/что взять/на_что_поменять/опция»
— шаблон.
/g
— флаг для замены всех без исключения вхождений заданного шаблона.
Диплинки
Этот способ поможет проверить переходы по диплинкам на нужные экраны в следующих ситуациях:
-
Много экранов.
-
Не приходят пуши.
-
Пушей еще нет.
-
Проверка корректной работы приложения.
-
Проверка работы с некорректными пушами.
-
Переход по диплинку на экран, к которому нет доступа.
В Shell ADB мы можем выполнять команды с помощью Activity Manager (AM).
Стартуем нашу активити и передаем диплинк, который мы хотим проверить. Обычно в диплинке присутствует символ &, который разделяет экраны. Поэтому при открытии через терминал нужно поставить перед ними обратный слэш (\):
adb shell am start -W -a android.intent.action.VIEW -d
“myApp://open/client/trip\&last_trip=test” com.myApp
am
— вызов Activity Manager.
W
— ожидание загрузки перед выполнением команды.
a
— определяем, какое действие будет выполнено. В данном случае action.View.
d
— данные для запуска. В данном случае сам диплинк и далее приложение, через которое его следует открыть.
Возможно, при переносе команды в терминал придется переписать кавычки вручную или заменить на одинарные. Может ругаться на ошибку синтаксиса.
Создание скриншотов и запись видео с экрана устройства
Сделаем скриншот этой командой:
adb shell screencap -p <device_path/screenshot_name.png>
Например:
adb shell screencap -p /sdcard/screencap.png
— сделает скриншот экрана и сохранит файл с именем screencap.png на девайсе в папку /sdcard/screencap.png
.
Сохранить скрин на ПК можно так:
adb pull /sdcard/screencap.png
— по умолчанию файл копируется в директорию текущего пользователя /Users/username/screencap.png
.
Или можно сразу запускать всю команду целиком:
adb shell screencap -p /sdcard/screencap.png && adb pull /sdcard/screencap.png
.
На последних версиях ADB скриншот можно получить командой
adb exec-out screencap -p > screen.png
— и файл со скриншотом также появится в директории текущего пользователя на ПК.
Установленный по умолчанию путь можно изменить вручную, добавив его в конце команды:
adb exec-out screencap -p > downloads/test/screen.png
— и скриншот появится в папке /Users/username/downloads/test/screen.png.
Также при желании можно немного автоматизировать этот процесс, добавив алиас в bash_profile
. В macOS можно создать через Automator-службу и задать хоткей.
Для записи видео существует команда:
adb shell screenrecord <device_path>
Например:
adb shell screenrecord /sdcard/screenrecord.mp4
— команда начнет запись экрана устройства с использованием настроек по умолчанию в течении трех минут и сохранит результат записи в файле /sdcard/screenrecord.mp4
на устройстве.
Можно вручную прописать время записи ключом -time-limit time
(в секундах, правда запись все равно возможна не более 180 секунд).
Остановить запись раньше времени можно комбинацией клавиш CTRL+C.
Скопировать файл можно также через команду pull по аналогии со скриншотом.
Также можно посмотреть дополнительные возможности этой утилиты с помощью ключа --help
. К слову, она умеет изменять разрешение записи, битрейт, добавить дополнительные данные для багрепорта.
Полезно пользоваться ключом -bugreport
, который добавляет первым кадром в видео информацию о системе, на которой происходила запись.
Про то, как стянуть с девайса что-либо мы поговорили, теперь поговорим немного о том, как туда что-нибудь закинуть.
Открыли на ПК, изменили формат, содержание, закинули на телефон, проверили, что приложение корректно реагирует на неизвестные форматы, на превышение размера. Загрузить файл на телефон с ПК можно командой:
adb push /Users/username/file <device_path>
Выполним команду:
adb push /Users/username/screen.png sdcard
— в результате наш файл screen.png скопируется на телефон в раздел sdcard
.
Проверка восстановления состояния приложения после его убийства системой
Еще один пример из опыта связан с проверкой восстановления стейта приложения после его убийства системой. Сворачиваем приложение, убиваем процесс — это действие имитирует остановку процесса системой в случае нехватки памяти:
adb shell am kill com.myApp
Запускаем снова, смотрим, что ничего не сломалось.
Мы столкнулись с таким сценарием: пользователь сворачивает приложение, находясь на определенном экране. Через какое-то время система тормозит процесс и кэширует его стейт. Когда пользователь пытается развернуть приложение, получает краш. Это происходит при обращении к данным из кэша, так как фрагменты восстанавливают свой стек и состояние, но кэш уже пустой.
К сожалению, этот баг мы не поймали на тестировании, потому что не сталкивались с таким раньше, и он ушел в прод. Но теперь вы знаете, что такое возможно, и не допустите наших ошибок.
Логи
Работа с логами полезна, когда мы ищем причину краша приложения. Если нужно сохранить текущий буфер логов, сделать это можно командой:
adb logcat
— выводит логи в реальном времени.
adb logcat -d
— выводит лог на момент запуска команды, не дописывая реальные события на устройстве. Также можно вывести лог в отдельный файл командой: adb logcat -d > file.log
(файл создается в директории текущего пользователя).
А команда adb logcat >> file.log
будет писать лог сразу в файл, дописывая все реальные события на устройстве.
Существует несколько уровней по мере возрастания: V — Verbose, D — Debug, I — Info, W — Warn, E — Error, F — Fatal, S — Silent. Например:
adb logcat '*:E'
— будет выводить логи с ошибками и уровнем выше.
Теперь немного о форматировании вывода и фильтрах, с помощью ключа -v
можно изменить формат вывода в консоль:
adb logcat -v time
— выводит логи последовательно по времени записи.
adb logcat -v color
— отображает каждый уровень логов отдельным цветом, очень помогает при чтении.
adb logcat -v brief
— отображает приоритет, тег и PID процесса.
Каждое сообщение журнала имеет тег и связанный с ним приоритет. С их помощью можно уменьшить количество вывода в консоль:
adb logcat SwrveSDK:I '*:S'
— будет отображать наши отправляемые события аналитики в сервис Swrve. Параметр *:S
говорит о том, что вывод журнала ограничен выражением фильтра.
Ну и всегда можно использовать утилиту grep для фильтрования вывода:
adb logcat '*:E' -v color | grep com.myApp
По традиции, за более дополнительной информацией всегда можно обратиться к помощнику adb logcat --help
.
Теперь о том, как это использовать. Например, если баг воспроизвелся, а устройство не было подключено, можно сразу подключить его и перенаправить лог в файл.
Для последующего дебага перед сбором логов можно чистить буфер, чтобы исключить лишние данные. Сделать это можно командой: adb logcat -c
, дальше воспроизводим баг и делаемadb logcat -d
.
Для любителей покопаться в куче логов есть еще один инструмент — ADB bugreport. Позволяет создавать ZIP-архивы с полной отладочной информацией в простом текстовом формате (.txt)
.
adb bugreport /Users/username
— создает zip архив в указанной директории.
Копирует всю информацию об устройстве, такую как данные dumpstate
, dumpsys
и logcat
в указанную папку. По умолчанию отчеты об ошибках сохраняются в /bugreports
и могут быть просмотрены с помощью:
adb shell ls /bugreports/
Самая важная для нас информация хранится в bugreport—BUILD_ID—DATE.txt
Есть еще один интересный инструмент для работы с крашами — ANR, когда приложение не отвечает Application Not Responding. Запускаем его командой:
adb shell am monitor
, и далее воспроизводим наш краш. В консоль будет выведена информация о краше без лишней воды и три варианта продолжения работы нашего мониторинга: (c)ontinue: show crash dialog, (k)ill: immediately kill app, (q)uit: finish monitoring.
Эмуляторы
Вывод списка настроенных эмуляторов:
emulator -list-avds
Запуск нужного нам эмулятора:
emulator @avdname
.
При работе с эмуляторами бывает, что необходимо перезапустить службы. При этом сервер нужно запустить после старта эмулятора, но часто достаточно и одной команды: adb kill-server
. Если не помогло, выполняем весь сценарий:
emulator -list-avds
— выведем список настроенных эмуляторов.
adb kill-server
— останавливаем сервер.
emulator -avd avdname
(или emulator @avdname
) — где avdname — имя эмулятора.
adb start-server
— заново запускаем сервер.
adb devices
— выводим список подключенных устройств, наш потерянный эмулятор должен появиться.
Для самых ленивых, можно создать эмулятор из командной строки. Например, следующая команда создает эмулятор с именем “test”, используя системный x86-образ с API 25:
avdmanager create avd -n test -k "system—images;android-25;google_apis;x86"
Если нужного образа нет, можно предварительно установить его командой:
sdkmanager --install "system—images;android—25;google_apis;x86"
sdkmanager --list | grep system—images
— выведет список доступных для скачивания образов.
С эмуляторами также во время работы иногда возникают фантомные проблемы, и одна из частых команд, которая помогает это загрузка эмулятора на холодную без подтягивания автоматического снапшота, при этом на выходе снапшот будет сделан:
emulator @avdname -no-snapshot-load
Еще несколько полезных ключей при старте эмулятора:
-no-snapshot-save
— не будет автоматического сохранения снапшота.
-no-snapshot
— не будет ни загрузки, ни сохранения снапшота.
Если эмулятору по-прежнему плохо, можно очистить его с помощью ключа, который возвращает эмулятор в первоначальное состояние: -wipe-data
.
Создание снапшотов — весьма полезный инструмент для сохранения разных состояний девайса. Вручную это можно делать через настройки эмулятора, либо с помощью команды:
adb emu avd snapshot save test
— сохраняем состояние эмулятора, где test — имя снапшота, которое будет храниться на девайсе.
emulator @avdname -snapshot-list
— запускаем наш эмулятор с именем @avdname с выводом в консоль списка снапшотов
Далее можно загрузить сохраненный ранее снапшот командой:
adb emu avd snapshot load test
— где test
— имя сохраненного ранее снапшота.
adb emu avd snapshot delete test
— удаляет снапшот с именем test
.
Можно сразу запускать эмулятор с нужным нам снапшотом: emulator @avdname -snapshot test
.
Также с помощью команды pull
можно стащить снапшот с девайса:
adb emu avd snapshot pull test /Users/username/
.
С нашим эмулятором можно работать через консоль telnet
. Но для этого сначала надо ее установить. Самый простой способ — через менеджер пакетов brew
, если он у вас есть. А если нет, самое время узнать, что это и как им пользоваться. Итак, устанавливаем telnet
командой brew install telnet
.
Далее запускаем наш эмулятор. В другой вкладке терминала подключаемся к нему командой telnet localhost port
.
telnet localhost 5554
— подключиться к нашему эмулятору, использующего порт 5554.
После отработки команды мы можем делать всякие полезные штуки с нашим эмулятором, в том числе, работать с geo
. Например, команда geo fix 40.748840 —73.984279
установит нужное нам местоположение по указанным координатам.
Например, работа со снапшотами немного упрощается, команды из предыдущего раздела сокращаются до avd snapshot <command>
.
Изменение разрешения на девайсе
Для проверки корректности отображения элементов на экране устройства есть полезные команды менеджера окон (wm), позволяющие изменять разрешение и плотность пикселей. Так можно перебрать все необходимые варианты размеров экрана и посмотреть, как наше приложение будет адаптироваться под них:
adb shell wm size 1080x1920
— установить кастомное разрешение экрана, где ширина будет равна 1080, а высота — 1920.
adb shell wm size reset
— сбросить все наши изменения.
adb shell wm density X
— менять плотность пикселей, где минимальное значение — 72. Чем больше значение, тем крупнее элементы на экране.
adb shell wm density reset
— сбросить все наши изменения.
Если мы запустим наши команды без аргументов, нам вернется текущее разрешение экрана и плотность пикселей подключенного устройства или эмулятора.
Monkey
Отдельно можно упомянуть инструмент Monkey, который генерирует случайные пользовательские события на эмуляторе или устройстве: клики, касания и жесты, а также ряд событий системного уровня, что напоминает движения глупой мартышки. Можно использовать Monkey для стресс-тестирования.
adb shell monkey
— вывод всех параметров обезьянки.
Пример полного сценария: adb shell monkey--throttle 100--pct—syskeys 0 -p com.myApp -v 10
.
Ключ -throttle
— задержка между действиями в миллисекундах. Так как Monkey выполняет свои действия довольно быстро, этот ключ обычно используется, когда мы хотим визуально контролировать происходящее на экране.
Ключ -pct-syskeys
— определяет процент системных кнопок, которые будут нажаты в процессе сценария. В данном примере установлено значение 0, что говорит о том, что системные кнопки не будут нажиматься совсем.
Ключ -p
— имя пакета, который мы передаем.
Ключ -v
— количество действий, которые нужно выполнить.
Разрешения приложения
Работа с пермишенами заключается в их отзыве у приложения, потому что предоставление разрешение обычно идет через запрос самого приложения. Это делается быстро и просто, тогда как отзыв разрешения идет через системные настройки.
adb shell dumpsys package com.MyApp | grep permission
— выводит список из доступных разрешений приложения. Например, install permissions
— обязательные разрешение, которые выдаются при установки приложения. runtime permissions
— разрешения, которые запрашиваются в конкретный момент: например, при обращении к файловому хранилищу. Замечу, что если в списке requested permission нет какого-либо разрешения, выдать к нему доступ не получится.
Итак, чтоб отозвать разрешение у нашего приложения, нужно выполнить команду adb shell pm revoke packageName permissionName
.
adb shell pm revoke com.MyApp android.permission.CAMERA
— отзовет у приложения com.myApp доступ к камере. После возврата в приложение и попытке использовать через него камеру мы снова увидим запрос на предоставление разрешения.
Командой grant
мы выдаем разрешение приложению. Например,
adb shell pm grant com.myApp android.permission.CAMERA
— для нашего приложения будет выдан доступ на использование камеры телефона.
Батарея
Немного коснемся работы с батареей, а также затронем режим ожидания.
adb shell dumpsys battery
— вывод информации о батареи.
adb shell dumpsys battery set level X
— установка уровня заряда батареи, где X — процент заряда.
adb shell dumpsys battery unplug
— имитация отключения зарядки.
adb shell dumpsys battery reset
— сброс всех наших изменений.
Теперь поговорим про режимах ожидания. Начиная с Android 6.0, появилась функция Doze Mode. Она направлена на экономию заряда и продление срока службы батареи за счет ограничения активности приложений после того, как пользователь не взаимодействовал с устройством и оно не находилось на зарядке.
При этом система периодически выходит из Doze Mode для выполнения отложенных фоновых задач. Еще один схожий инструмент Android — App Standby. В отличие от Doze Mode, это состояние конкретного приложения, которое находится в фоне определенный период времени и после этого входит в режим Standby. Наша задача — убедиться в том, что приложение нормально восстанавливает свою работу после выхода из этих двух режимов энергосбережения.
Для перехода устройства в режим Doze Mode нужно выполнить следующие команды:
adb shell dumpsys battery unplug
— отключить зарядку.
adb shell dumpsys deviceidle step
— команду, возможно, придется выполнить несколько раз, пока она не вернет Stepped to deep: IDLE
.
После всех манипуляций с батареей лучше выполнить командуadb shell dumpsys battery reset
, вернув ее в исходное состояние.
Также есть команда для принудительного ввода устройства в Doze Mode: adb shell dumpsys deviceidle force-idle
, иногда перед этим нужно выполнить команду adb shell dumpsys deviceidle enable
.
Вывести обратно из состояния Doze Mode можно командойadb shell dumpsys deviceidle unforce
. Не забываем сбросить состояние батареи: adb shell dumpsys battery reset
.
Теперь немного про App Standby. Для перевода приложения в данный режим нужно выполнить следующие команды:
adb shell dumpsys battery unplug
— отключаем батарею, как и в предыдущем случае.
adb shell am set—inactive com.myApp true
— вводим приложение в режим App Standby.
Далее выводим наше приложение из режима App Standby командой adb shell am set-inactive com.myApp false
.
Проверить статус приложения можно командой adb shell am get-inactive com.myApp
.
Еще немного полезных команд
adb reboot
— перезагрузка устройства, актуально и для реального девайса.
adb shell dumpsys package com.myApp
— вывести полную информацию о конкретном приложении.
adb shell dumpsys meminfo com.myApp
— посмотреть использование памяти приложением на девайсе от занимаемого места до отображения баз данных, используемых этим приложением.
adb shell getprop
— получить список доступных свойств устройства: производитель, модель устройства, хардварные спецификации и другое.
Получить список доступных для приложения Activity: adb shell dumpsys package com.myApp | grep -i Activity
.
Получить имя запущенной активити: adb shell dumpsys window | grep Focused
.
Запустить выбранную активити приложения: adb shell am start -n com.myApp/.ActivityClass
— можно запускать любые установленные приложения, в том числе и системные. Например: adb shell am start -n com.android.settings/.Settings
— запустит наши настройки телефона.
Сделать вызов на указанный телефонный номер: adb shell am start -a android.intent.action.CALL tel:+790900000XX
.
Открыть страницу в браузере: adb shell am start -a android.intent.action.VIEW 'https://indriver.com'
В конце хочу сказать, что все возможности Android Debug Bridge невозможно запихнуть в одну статью, как и досконально изучить их работу. Постоянно что-то меняется: что работало сегодня, внезапно может перестать работать завтра. А потребности в знаниях тех или иных инструментов будут возникать по мере поиска решения конкретных задач.
Но могу с уверенностью сказать, что этого материала вам хватит для старта и даже больше. Удачи в ваших начинаниях и приятного погружения в интересный мир тестирования.
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Appearance settings
- What is ADB
- ADB Architecture
- ADB port is occupied
-
Basic usage
- Command syntax
- Specify the target device for the command
- start stop
- View adb version
- Run adbd as root
- Specify the network port of adb server
-
Device connection management
- Query connected devices/emulators
- USB connection
- Wireless connection (USB cable required)
- Wireless connection (no need to use USB cable)
-
Application Management
- View application list
- All applications
- system applications
- third-party usage
- Install APK
- Adb install internal principle introduction
- Uninstall the app
- Clear application data and cache
- View foreground activity
- View running Services
- View application details
-
Interact with the application
- Activating Activity
- Transfer Service
- Send broadcast
- Forcibly stop the application
- Disable apps and start
- Revoke the permissions of the application
-
File Management
- Copy the files in the device to the computer
- Copy files from computer to device
-
Simulation key/input
- Power button
- menu
- HOME key
- return key
- volume control
- Media Control
- Turn on/off the screen
- Slide to unlock
- Enter text
-
View log
- Android log
- Kernel log
-
View device information
- Model
- Battery status
- Screen Resolution
- Screen density
- Display parameters
- android_id
- IMEI
- Android system version
- IP address
- Mac address
- CPU information
- Memory information
- More hardware and system properties
-
Modify settings
- Resolution
- Screen density
- Display area
- Turn off USB debugging mode
- Display and hide status bar and navigation bar
- Return to normal mode
-
Useful functions
- Screenshots
- Record screen
- Remount.
- View connected WiFi passwords
- Set the system date and time
- restart cellphone
- Check if the device is rooted
- Use Monkey for stress testing
- Turn on/off WiFi
- Turn on/off data traffic
-
Flashing related commands
- Restart to Recovery mode
- Restart from Recovery to Android
- Restart to Fastboot mode
- Update the system via sideload
- More adb shell commands
- View process
- View real-time resource usage
- View process UID
- Other
-
Security related
- Enable SELinux
- Disable SELinux
- Enable dm_verity
- Disable dm_verity
-
common problem
- Failed to start adb server
*The content of this article is integrated from the Internet, welcome to reprint. *
I believe that friends who do Android development have used ADB commands, but they are only limited to installing application push files and device restarting. I don’t know the deeper ones. In fact, we can understand a little more. There are some uncommon scenarios we should at least Knowing that it can be done, for example, we know adb install but not adb shell am start. The former is used to install software, and the latter is used to open the software. A usage scenario of the latter makes me pay attention to him: the company customizes the Android system. When debugging the screen, it depends on whether the screen is full to verify that the driver is normal. This is a troublesome approach. It is to be installed and opened in the hands of Android developers with eclipse or other ide. Obviously, it is much more complicated than the driver who connects the data line and uses the adb command. Therefore, it is necessary to know more.
The following may be more cumbersome, I will try to be simple, please be patient and finish reading.
What is ADB
The full name of Adb is Android Debug Bridge: Android Debug Bridge. The picture below shows the official introduction of Adb by Android:
It can be seen that the original intention of Android is to use a tool such as adb to assist developers in debugging apk faster and better in the process of developing android applications, so adb has the ability to install and uninstall apk, copy and push files, view device hardware information, and view Functions such as applications occupying resources and executing shell commands on the device;
We can find the adb tool in the platform-tools directory of the android sdk installation directory;
The permission mechanism of the existing Android system is becoming more and more perfect. Many operations that hope to bypass the permission management mechanism are no longer available, but Adb can achieve it. In fact, Adb has a lot of authority to some extent, even on the latest version of the Android system. Because Adb is designed to facilitate debugging by developers, it is necessary to expose some interfaces outside of permissions. So many companies can use this feature to bypass the permission mechanism to do some operations on non-Root non-customized machines (the specific usage is mentioned below), of course, there are also various ways, such as connecting via mobile phone OTG, which will not be repeated here.
ADB Architecture
In order to facilitate understanding, we start with three instructions, we often use adb start-server, adb devices, adb kill-server.
Then we often see this output interface:
C:\Users\dell>adb devices
List of devices attached
* daemon not running. starting it now at tcp:5037 *
* daemon started successfully *
Enter fullscreen mode
Exit fullscreen mode
So there are three questions here, why is the server, the server corresponds to the server or the server? If the mobile phone is the client, does the server refer to the service opened on the computer. And what is this daemon?
ADB is a C/S architecture application, composed of three parts:
- Adb client running on the PC side:
The command line program «adb» is used to run adb commands from a shell or script. First, the «adb» program tries to locate the ADB server on the host. If the ADB server cannot be found, the «adb» program automatically starts an ADB server. Next, when the adbd of the device and the adb server on the pc side establish a connection, the adb client can send a service request to the ADB servcer; - Adb server running on the PC side:
ADB Server is a background process running on the host. Its function is to detect the connection and removal of the USB port sensing device, and the start or stop of the emulator instance. ADB Server also needs to send the request of the adb client to the corresponding adbd via usb or tcp; - The resident process adb demon (adbd) running on the device side:
The program «adbd» runs as a background process in the Android device or emulator system. Its function is to connect to the ADB server and provide some services for the client running on the host;
ADB port is occupied
A small partner said that he hoped that I would put the Adb startup problem at the top, because he often encountered the problem of adb unable to find the device, then I will put it in front, I think it is definitely not only she will encounter this situation .
5037 is the default port of adb. If port 5037 is occupied, we will be troubled by not finding the device when using the Adb command. This problem is often encountered for those who are not very familiar with Adb, so I will This usage is placed at the beginning of the article so that friends can find it easily;
The idea of solving this kind of port occupation problem is the same, three steps:
- Find the Pid of the process using the port;
C:\Windows\system32>netstat -aon|findstr 5037
TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 3172
Enter fullscreen mode
Exit fullscreen mode
- Find the corresponding process name through PID (easy to locate, you can skip);
C:\Windows\system32>tasklist /fi "PID eq 3172"
Image name PID session name session# memory usage
========================= ======== ================ = ========== ============
360MobileLink.exe 3172 Console 4 40,208 K
Enter fullscreen mode
Exit fullscreen mode
- Use the command to terminate the operation of the command;
C:\Users\wwx229495>taskkill /pid 3172 /f
Success: The process with PID 3172 has been terminated.
Enter fullscreen mode
Exit fullscreen mode
Sometimes, some rogue programs will copy a copy of Adb.exe to the windows environment variable, such as C://Windows/system32, at this time we can use Where
The Adb command finds out the path where adb is located and deletes it.
Basic usage
What can adb do? The answer is that all operations that can be performed on mobile phones can be implemented with adb. That is to say, if you play 6, your touch screen is completely broken, and the display is completely broken, just give you a motherboard, and you can still complete the actions you want to do. Of course, this is not recommended in general scenarios, efficiency is the priority.
The following content is transferred from the blog of a big cow on github. If there is any infringement, please inform and delete it immediately;
Late
Command syntax
The basic syntax of the adb command is as follows:
adb [-d|-e|-s ]
If there is only one device/emulator connected, you can omit the part [-d|-e|-s ] and use adb directly.
Specify the target device for the command
If there are multiple devices/emulators connected, you need to specify the target device for the command.
Parameters | 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/emulator with the corresponding serialNumber number as the command target |
When multiple devices/emulators are connected, the -s parameter is commonly used. The serialNumber can be obtained through the adb devices command. Such as:
$ adb devices
List of devices attached
cf264b8f device
emulator-5554 device
10.129.164.6:5555 device
Enter fullscreen mode
Exit fullscreen mode
Cf264b8f, emulator-5554 and 10.129.164.6:5555 in the output are serialNumber.
For example, you want to specify the device cf264b8f to run the adb command to obtain the screen resolution:
adb -s cf264b8f shell wm size
Enter fullscreen mode
Exit fullscreen mode
Another example is to install an application on the device 10.129.164.6:5555 (the format of serialNumber in this form is :, which is generally a wirelessly connected device or a third-party Android emulator such as Genymotion):
adb -s 10.129.164.6:5555 install test.apk
Enter fullscreen mode
Exit fullscreen mode
*In the 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 the adb server command:
adb start-server
Enter fullscreen mode
Exit fullscreen mode
(Generally, there is no need to manually execute this command. If you find that the adb server is not started when running the adb command, it will be automatically activated.)
Stop the adb server command:
adb kill-server
Enter fullscreen mode
Exit fullscreen mode
View adb version
adb version
Enter fullscreen mode
Exit fullscreen mode
Sample output
Android Debug Bridge version 1.0.36
Revision 8f855a3d9b35-android
Enter fullscreen mode
Exit fullscreen mode
Run adbd as root
The operating 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 the command through the adb server, and adbd parses and runs after receiving the command.
So if adbd is executed with normal permissions, some commands that require root permissions to execute cannot be directly executed with adb xxx. At this time, you can execute commands after adb shell and then su, or you can let adbd execute with root privileges, which can execute high-privileged commands at will.
command:
adb root
Enter fullscreen mode
Exit fullscreen mode
Normal output:
restarting adbd as root
Enter fullscreen mode
Exit fullscreen mode
Now run adb shell again and see if the command line prompt becomes #?
Some mobile phones cannot be executed with root privileges through the adb root command after rooting. For example, some Samsung models will prompt adbd cannot run as root in production builds. You can install adbd Insecure first, and then adb root Try it.
Correspondingly, if you want to restore adbd to non-root privileges, you can use the adb unroot command.
Specify the network port of adb server
adb -P <port> start-server
Enter fullscreen mode
Exit fullscreen mode
The default port is 5037.
Device connection management
Query connected devices/emulators
command:
adb devices
Enter fullscreen mode
Exit fullscreen mode
Sample output:
List of devices attached
cf264b8f device
emulator-5554 device
10.129.164.6:5555 device
Enter fullscreen mode
Exit fullscreen mode
The output format is [serialNumber] [state], serialNumber is what we often call SN, and the state is as follows:
offline —— Indicates that the device is not successfully connected or has no response.
device-The device is connected. Note that this state does not indicate that the Android system has been fully started and operable. The device instance can be connected to adb during the device startup process, but the system will be in an operable state after startup.
no device —— No device/emulator connection.
The above output shows that three devices/emulators are currently connected, and cf264b8f, emulator-5554 and 10.129.164.6:5555 are their SNs respectively. It can be seen from the name emulator-5554 that it is an Android emulator, and 10.129.164.6:5555, which is the serialNumber of the form :, is generally a wirelessly connected device or a third-party Android emulator such as Genymotion.
Common abnormal output:
No device/emulator is successfully connected.
List of devices attached
The device/emulator is not connected to adb or not responding.
List of devices attached
cf264b8f offline
USB connection
To use adb normally through USB connection, you need to ensure several points:
The hardware status is normal.
Including the Android device is in the normal boot state, the USB cable and various interfaces are intact.
Developer options and USB debugging mode for Android devices are turned on.
You can go to «Settings»-«Developer Options»-«Android Debugging» to view.
If you can’t find the developer option in the settings, you need to use an easter egg to show it: click the «version number» 7 times in «Settings»-«About Phone».
The device drive status is normal.
It seems that you don’t need to worry about this under Linux and Mac OS X. Under Windows, you may encounter a situation where you need to install a driver. To confirm this, you can right-click «Computer»-«Properties» and go to the «Device Manager» to view related devices Whether there is a yellow exclamation mark or question mark, if not, it means the drive status is good. Otherwise, you can download a mobile assistant program to install the driver first.
Confirm the status after connecting the computer and the device via the USB cable.
adb devices
Enter fullscreen mode
Exit fullscreen mode
If you can see
xxxxxx device
The connection is successful.
Wireless connection (USB cable required)
In addition to connecting the device and the computer via USB to use adb, you can also use a wireless connection-although there are steps to use USB during the connection process, your device can get rid of the limitation of the USB cable within a certain range after the connection is successful. !
Steps:
Connect the Android device and the computer to run adb to the same local area network, for example to the same WiFi.
Connect the device to the computer via a USB cable.
Make sure that the connection is successful (you can run adb devices to see if the device can be listed).
Let the device monitor TCP/IP connections on port 5555:
adb tcpip 5555
Enter fullscreen mode
Exit fullscreen mode
Disconnect the USB connection.
Find the IP address of the device.
Generally, it can be found in «Settings»-«About Phone»-«Status Information»-«IP Address», or you can use the adb command to view it using the method in the section View Device Information-IP Address below.
Connect the device by IP address.
adb connect <device-ip-address>
Enter fullscreen mode
Exit fullscreen mode
Here is the device IP address found in the previous step.
Confirm the connection status.
adb devices
Enter fullscreen mode
Exit fullscreen mode
If you can see
<device-ip-address>:5555 device
Enter fullscreen mode
Exit fullscreen mode
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 execute the step of adb connect <device-ip-address>
again;
If it still does not work, restart adb via adb kill-server and try again from the beginning.
Disconnect wireless connection
command:
adb disconnect <device-ip-address>
Enter fullscreen mode
Exit fullscreen mode
Wireless connection (no need to use USB cable)
Note: root permission is required.
The previous section «Wireless connection (requires USB cable)» is the method introduced in the official document, which requires the help of USB data cable to achieve wireless connection.
Since we want to achieve wireless connection, can all steps be wireless? The answer is yes.
Install a terminal emulator on the Android device.
Devices that have already been installed can skip this step. The download address of the terminal emulator I use is: Terminal Emulator for Android Downloads
Connect the Android device and the computer to run adb to the same local area network, for example to the same WiFi.
Open the terminal emulator on the Android device and run the commands in sequence:
su
setprop service.adb.tcp.port 5555
Enter fullscreen mode
Exit fullscreen mode
Find the IP address of the Android device.
Generally, it can be found in «Settings»-«About Phone»-«Status Information»-«IP Address», or you can use the adb command to view it using the method in the section View Device Information-IP Address below.
Connect the Android device via adb and IP address on the computer.
adb connect <device-ip-address>
Enter fullscreen mode
Exit fullscreen mode
Here is the device IP address found in the previous step.
If you can see the output connected to :5555, it means 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 emulator:
restart adbd
Enter fullscreen mode
Exit fullscreen mode
If restart does not work, try the following command:
stop adbd
start adbd
Enter fullscreen mode
Exit fullscreen mode
Application Management
View application 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]
Enter fullscreen mode
Exit fullscreen mode
That is, on the basis of adb shell pm list packages, you can add some parameters to filter and view different lists. The supported filter parameters are as follows:
Parameters | Display list |
---|---|
None | All applications |
-f | Display the apk file associated with the application |
-d | Only display disabled apps |
-e | Only show enabled apps |
-s | Only show system apps |
-3 | Only display third-party applications |
-i | Display the installer of the application |
-u | Include uninstalled apps |
<FILTER> |
Package name contains <FILTER> string |
All applications
command:
adb shell pm list packages
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
...
Enter fullscreen mode
Exit fullscreen mode
system applications
command:
adb shell pm list packages -s
Enter fullscreen mode
Exit fullscreen mode
third-party usage
command:
adb shell pm list packages -3
Enter fullscreen mode
Exit fullscreen mode
Applications whose package name contains a certain string
For example, to view the list of applications whose package name contains the string mazhuang, command:
adb shell pm list packages mazhuang
Enter fullscreen mode
Exit fullscreen mode
Of course, you can also use grep to filter:
adb shell pm list packages | grep mazhuang
Enter fullscreen mode
Exit fullscreen mode
Install APK
Command format:
adb install [-lrtsdg] <path_to_apk>
Enter fullscreen mode
Exit fullscreen mode
parameter:
Adb install can be followed by some optional parameters to control the behavior of installing APK. The available parameters and their meanings are as follows:
Parameters | Meaning |
---|---|
-l | Install the application to the protected directory /mnt/asec |
-r | Allow overwrite installation |
-t | Allow to install the application specified by application android:testOnly="true" in AndroidManifest.xml |
-s | Install the application to the sdcard |
-d | Allow downgrade to overwrite installation |
-g | Grant all runtime permissions |
After running the command, if you see output similar to the following (the status is Success), the installation is successful:
[100%] /data/local/tmp/1.apk
pkg: /data/local/tmp/1.apk
Success
Enter fullscreen mode
Exit fullscreen mode
The above is the output of the latest version of adb of v1.0.36, which will show the progress percentage of pushing the apk file to the phone.
Using the old version of adb, the output is like this:
12040 KB/s (22205609 bytes in 1.801s)
pkg: /data/local/tmp/SogouInput_android_v8.3_sweb.apk
Success
Enter fullscreen mode
Exit fullscreen mode
And if the status is Failure, the installation failed, for example:
[100%] /data/local/tmp/map-20160831.apk
pkg: /data/local/tmp/map-20160831.apk
Failure [INSTALL_FAILED_ALREADY_EXISTS]
Enter fullscreen mode
Exit fullscreen mode
Common installation failure output codes, meanings and possible solutions are as follows:
Output | Meaning | Solution |
---|---|---|
INSTALL_FAILED_ALREADY_EXISTS | The application already exists, or uninstalled but not uninstalled cleanly |
adb install , use the -r parameter, or first adb uninstall <packagename> and then install |
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 | Not enough 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 | The application with the same name has been installed before, but the data is not removed when uninstalling; or the application has been installed, but the signature is inconsistent | First adb uninstall <packagename> then install |
INSTALL_FAILED_SHARED_USER_INCOMPATIBLE | The requested shared user exists but the signature is inconsistent | |
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 be deleted when replacing | |
INSTALL_FAILED_DEXOPT | dex optimization verification failed or insufficient space | |
INSTALL_FAILED_OLDER_SDK | The device system version is lower than the application requirements | |
INSTALL_FAILED_CONFLICTING_PROVIDER | A content provider with the same name as the app already exists in the device | |
INSTALL_FAILED_NEWER_SDK | The device 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 | Contains native code of incompatible device CPU application binary interface | |
INSTALL_FAILED_MISSING_FEATURE | The application uses a feature that is 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 install it to the built-in storage; 2. Do not use the same signature as the ROM when packaging. |
INSTALL_FAILED_INVALID_INSTALL_LOCATION | 1. Cannot be installed to the specified location; 2. The application signature is consistent with the ROM signature and is regarded as a built-in application. |
1. Switch the installation location, add or delete the -s parameter;2. Do not use the same signature as the ROM when packaging. |
INSTALL_FAILED_MEDIA_UNAVAILABLE | The installation location is not available | Usually sdcard, confirm that the sdcard is available or install to the built-in storage |
INSTALL_FAILED_VERIFICATION_TIMEOUT | Verify installation package timeout | |
INSTALL_FAILED_VERIFICATION_FAILURE | Failed to verify the installation package | |
INSTALL_FAILED_PACKAGE_CHANGED | The application does not match the expectations of the calling program | |
INSTALL_FAILED_UID_CHANGED | The application has been installed before, and it is not consistent with the UID assigned this time | Clean up residual files from previous installations |
INSTALL_FAILED_VERSION_DOWNGRADE | A newer version of this app has been installed | Use the -d parameter |
INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE | The installed target SDK supports the application of the same name with runtime permissions, and the version to be installed does not support runtime permissions | |
INSTALL_PARSE_FAILED_NOT_APK | The specified path is not a file or does not end with .apk
|
|
INSTALL_PARSE_FAILED_BAD_MANIFEST | Unable to parse 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 has been installed, and the signature is inconsistent with the APK file | Uninstall the app on the device first, then install it |
INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING | CertificateEncodingException |
|
INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME | There is no or invalid package name in the manifest file | |
INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID | An invalid shared user ID is specified in the manifest file | |
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED | A structural error was encountered while parsing the manifest file | |
INSTALL_PARSE_FAILED_MANIFEST_EMPTY | The operable tag (instrumentation or application) could not 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 | |
INSTALL_FAILED_DUPLICATE_PERMISSION | The application tries to define an existing permission name | |
INSTALL_FAILED_NO_MATCHING_ABIS | The application contains native code not supported by the application binary interface of the device | |
INSTALL_CANCELED_BY_USER | App installation needs to be confirmed on the device, but the device is not operated or canceled | Agree to install on the device |
INSTALL_FAILED_ACWF_INCOMPATIBLE | The application is not compatible with the device | |
does not contain AndroidManifest.xml | Invalid APK file | |
is not a valid zip file | Invalid APK file | |
Offline | The device is not connected successfully | First connect the device to adb successfully |
unauthorized | The device is not authorized to allow debugging | |
error: device not found | There is no successfully connected device | First connect the device to adb successfully |
protocol failure | The device has been disconnected | First connect the device to adb successfully |
Unknown option: -s | Installation to sdcard is not supported under Android 2.2 | Do not use the -s parameter |
No space left on device | Not enough space | Clean up space |
Permission denied … sdcard … | sdcard is not available | |
signatures do not match the previously installed version; ignoring! | The app has been installed and the signatures are inconsistent | Uninstall the app on the device first, then install it |
when parsing APK file
Reference: [PackageManager.java]
Adb install internal principle introduction
adb install is actually completed in three steps:
- Push the apk file to /data/local/tmp.
- Call pm install to install.
- Delete the corresponding apk file under /data/local/tmp.
Therefore, when necessary, you can also follow this step to manually perform the installation process step by step.
Uninstall the app
command:
adb uninstall [-k] <packagename>
Enter fullscreen mode
Exit fullscreen mode
<packagename>
represents the package name of the application, and the -k parameter is optional, meaning that the application is uninstalled but the data and cache directory are retained.
Command example:
adb uninstall com.qihoo360.mobilesafe
Enter fullscreen mode
Exit fullscreen mode
Means to uninstall 360 Mobile Guard.
Clear application data and cache
command:
adb shell pm clear <packagename>
Enter fullscreen mode
Exit fullscreen mode
<packagename>
represents the application name package. The effect of this command is equivalent to clicking «Clear Cache» and «Clear Data» on the application information interface in the settings.
Command example:
adb shell pm clear com.qihoo360.mobilesafe
Enter fullscreen mode
Exit fullscreen mode
Means to clear the data and cache of 360 Mobile Guard.
View foreground activity
command:
adb shell dumpsys activity activities | grep mFocusedActivity
Enter fullscreen mode
Exit fullscreen mode
Sample output:
mFocusedActivity: ActivityRecord{8079d7e u0 com.cyanogenmod.trebuchet/com.android.launcher3.Launcher t42}
Enter fullscreen mode
Exit fullscreen mode
Among them, com.cyanogenmod.trebuchet/com.android.launcher3.Launcher
is the Activity currently in the foreground.
View running Services
command:
adb shell dumpsys activity services [<packagename>]
Enter fullscreen mode
Exit fullscreen mode
The <packagename>
parameter is not necessary. Specifying <packagename>
means viewing the Services related to a certain package name, and not specifying it means viewing all Services.
<packagename>
does not have to give a complete package name. For example, if you run adb shell dumpsys activity services org.mazhuang, then the package name org.mazhuang.demo1, org.mazhuang.demo2, org.mazhuang123 and other related Services will be listed come out.
View application details
command:
adb shell dumpsys package <packagename>
Enter fullscreen mode
Exit fullscreen mode
The output contains a lot of information, including Activity Resolver Table, Registered ContentProviders, package name, userId, path to file resource code after installation, version information, permission information and grant status, signature version information, etc.
<packagename>
represents the application package name.
Sample output:
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]
Enter fullscreen mode
Exit fullscreen mode
Interact with the application
Mainly use the am <command>
command, the commonly used <command>
are as follows:
command | Use |
---|---|
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 |
<INTENT>
The parameters are very flexible, and correspond to the Intent in the code when writing Android programs.
The options used to determine the intent object are as follows:
Parameters | Meaning |
---|---|
-a <ACTION> |
Specify the action, such as android.intent.action.VIEW
|
-c <CATEGORY> |
Specify category, such as android.intent.category.APP_CONTACTS
|
-n <COMPONENT> |
Specify the complete component name, which is used to clearly specify which Activity to start, such as com.example.app/.ExampleActivity
|
<INTENT>
can also carry data, just like Bundle when writing code:
Parameters | Meaning |
---|---|
--esn <EXTRA_KEY> |
null value (only key name) |
`-e | —es <EXTRA_KEY> <EXTRA_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 值 |
--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 数组 |
--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...] |
long 数组 |
Activating Activity
Command format:
adb shell am start [options] <INTENT>
Enter fullscreen mode
Exit fullscreen mode
E.g:
adb shell am start -n com.tencent.mm/.ui.LauncherUI
Enter fullscreen mode
Exit fullscreen mode
Indicates that the main interface of WeChat is activated.
adb shell am start -n org.mazhuang.boottimemeasure/.MainActivity --es "toast" "hello, world"
Enter fullscreen mode
Exit fullscreen mode
It means to call up org.mazhuang.boottimemeasure/.MainActivity and pass it the string data key-value pair toast-hello, world.
Transfer Service
Command format:
adb shell am startservice [options] <INTENT>
Enter fullscreen mode
Exit fullscreen mode
E.g:
adb shell am startservice -n com.tencent.mm/.plugin.accountsync.model.AccountAuthenticatorService
Enter fullscreen mode
Exit fullscreen mode
Indicates that a certain service of WeChat has been activated.
Send broadcast
Command format:
adb shell am broadcast [options] <INTENT>
Enter fullscreen mode
Exit fullscreen mode
It can be broadcast to all components or only to specified components.
For example, to broadcast BOOT_COMPLETED to all components:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
Enter fullscreen mode
Exit fullscreen mode
For another example, only broadcast BOOT_COMPLETED to org.mazhuang.boottimemeasure/.BootCompletedReceiver:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -n org.mazhuang.boottimemeasure/.BootCompletedReceiver
Enter fullscreen mode
Exit fullscreen mode
This type of usage is very practical when testing. For example, a broadcast scene is difficult to create. You can consider sending broadcasts in this way.
It can send the pre-defined broadcast of the system and also send the self-defined broadcast. The following is part of the system predefined broadcast and normal trigger timing:
action | Trigger timing |
---|---|
android.net.conn.CONNECTIVITY_CHANGE | Network connection has changed |
android.intent.action.SCREEN_ON | The screen lights up |
android.intent.action.SCREEN_OFF | The screen goes off |
android.intent.action.BATTERY_LOW | If the battery is low, a low battery prompt box will pop up |
android.intent.action.BATTERY_OKAY | The battery is restored |
android.intent.action.BOOT_COMPLETED | The device has started up |
android.intent.action.DEVICE_STORAGE_LOW | Storage space is too low |
android.intent.action.DEVICE_STORAGE_OK | Storage space recovery |
android.intent.action.PACKAGE_ADDED | A new application is installed |
android.net.wifi.STATE_CHANGE | The WiFi connection status has changed |
android.net.wifi.WIFI_STATE_CHANGED | WiFi status changes to enable/disable/starting/disabling/unknown |
android.intent.action.BATTERY_CHANGED | The battery level has changed |
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 started to sleep |
android.intent.action.DREAMING_STOPPED | The system stops sleeping |
android.intent.action.WALLPAPER_CHANGED | The wallpaper has changed |
android.intent.action.HEADSET_PLUG | Plug in headphones |
android.intent.action.MEDIA_UNMOUNTED | Unload external media |
android.intent.action.MEDIA_MOUNTED | Mount external media |
android.os.action.POWER_SAVE_MODE_CHANGED | Enable power saving mode |
(The above broadcasts can all be triggered by adb)
Forcibly stop the application
command:
adb shell am force-stop <packagename>
Enter fullscreen mode
Exit fullscreen mode
Command example:
adb shell am force-stop com.qihoo360.mobilesafe
Enter fullscreen mode
Exit fullscreen mode
Means to stop all the processes and services of 360 Security Guard.
Disable apps and start
Command example:
adb shell pm disable-user <packagename>
adb shell pm disable <packagename>
Enter fullscreen mode
Exit fullscreen mode
adb shell pm disable-user [options] <packagename>
Enter fullscreen mode
Exit fullscreen mode
Command example:
adb shell pm enable <packagename>
Enter fullscreen mode
Exit fullscreen mode
Revoke the permissions of the application
- Grant permissions to the app. Only optional permissions declared by the application can be granted
adb shell pm grant <packagename> <PACKAGE_PERMISSION>
Enter fullscreen mode
Exit fullscreen mode
For example: adb -d shell pm grant packageName android.permission.BATTERY_STATS
- Cancel app authorization
adb shell pm revoke <packagename> <PACKAGE_PERMISSION>
Enter fullscreen mode
Exit fullscreen mode
Option --user user_id: the user to be disabled
For example, grant permissions to the application. On devices running Android 6.0 (API level 23) and higher, the permission can be any permission declared in the application manifest. On devices running Android 5.1 (API level 22) and lower, it must be an optional permission defined by the application.
Disclaimer: The above order is an unconventional order. I am not responsible for any damage to your equipment, forcible stop, etc. You are performing this operation on your device, and you are responsible for it.
File Management
Copy the files in the device to the computer
command:
adb pull <file path in device> [directory on computer]
Enter fullscreen mode
Exit fullscreen mode
Among them, the directory parameter on the computer can be omitted, and the default is copied to the current directory.
example:
adb pull /sdcard/sr.mp4 ~/tmp/
Enter fullscreen mode
Exit fullscreen mode
*Tips: *The file path on the device may require root privileges to access. If your device has been rooted, you can use the adb shell and su commands to obtain root privileges in the adb shell, then cp /path/on/device /sdcard/filename Copy the file to sdcard, then adb pull /sdcard/filename /path/on/pc.
Copy files from computer to device
command:
adb push <file path on computer> <directory in device>
Enter fullscreen mode
Exit fullscreen mode
example:
adb push ~/sr.mp4 /sdcard/
Enter fullscreen mode
Exit fullscreen mode
*Tips: *The file path on the device may not be directly written by ordinary permissions. If your device has been rooted, you can first adb push /path/on/pc /sdcard/filename, and then adb shell and su in adb shell After obtaining root permissions, cp /sdcard/filename /path/on/device.
Simulation key/input
There is a very useful command called input in adb shell, 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)
Enter fullscreen mode
Exit fullscreen mode
For example, to simulate a click: //Click the position of the coordinate point x=50 y=250 on the screen.
adb shell input tap 50 250
For example, using the adb shell input keyevent command, different keycodes can achieve different functions. For the complete keycode list, see KeyEvent. The excerpts are as follows:
keycode | Meaning |
---|---|
3 | HOME key |
4 | Back key |
5 | Open the dial-up application |
6 | Hang up the call |
24 | Increase volume |
25 | Reduce the volume |
26 | Power button |
27 | Taking photos (need to be in the camera application) |
64 | Open the browser |
82 | Menu key |
85 | Play/Pause |
86 | Stop playing |
87 | Play the next song |
88 | Play the 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 contacts |
208 | Open the calendar |
209 | Open music |
210 | Open the calculator |
220 | Reduce screen brightness |
221 | Increase screen brightness |
223 | System hibernation |
224 | Light up the screen |
231 | Open the voice assistant |
276 | If there is no wakelock, let the system hibernate |
The following are some usage examples of input command.
Power button
db shell input keyevent 26
Enter fullscreen mode
Exit fullscreen mode
The effect is equivalent to pressing the power button.
menu
command:
adb shell input keyevent 82
Enter fullscreen mode
Exit fullscreen mode
HOME key
command:
adb shell input keyevent 3
Enter fullscreen mode
Exit fullscreen mode
return key
command:
adb shell input keyevent 4
Enter fullscreen mode
Exit fullscreen mode
volume control
Increase volume:
adb shell input keyevent 24
Enter fullscreen mode
Exit fullscreen mode
lower the volume:
adb shell input keyevent 25
Enter fullscreen mode
Exit fullscreen mode
Mute:
adb shell input keyevent 164
Enter fullscreen mode
Exit fullscreen mode
Media Control
play / Pause:
adb shell input keyevent 85
Enter fullscreen mode
Exit fullscreen mode
Stop play:
adb shell input keyevent 86
Enter fullscreen mode
Exit fullscreen mode
Play the next song:
adb shell input keyevent 87
Enter fullscreen mode
Exit fullscreen mode
Play the previous song:
adb shell input keyevent 88
Enter fullscreen mode
Exit fullscreen mode
Resume playback:
adb shell input keyevent 126
Enter fullscreen mode
Exit fullscreen mode
Pause playback:
adb shell input keyevent 127
Enter fullscreen mode
Exit fullscreen mode
Turn on/off the screen
The analog power button described above can be used to switch the screen on and off, but if you clearly want to turn on or off the screen, you can use the following method.
Light up the screen:
adb shell input keyevent 224
Enter fullscreen mode
Exit fullscreen mode
Turn off the screen:
adb shell input keyevent 223
Enter fullscreen mode
Exit fullscreen mode
Slide to unlock
If the lock screen does not have a password and is unlocked by swiping gestures, you can unlock it by input swipe.
Command (parameters are based on model Nexus 5, for example, swipe up gesture to unlock):
adb shell input swipe 300 1000 300 500
Enter fullscreen mode
Exit fullscreen mode
The parameters 300 1000 300 500 respectively represent the start point x coordinate, the start point y coordinate, the end point x coordinate, and the end point y coordinate.
Enter text
When the focus is on a text box, you can use the input command to enter text.
command:
adb shell input text hello
Enter fullscreen mode
Exit fullscreen mode
Now hello appears in the text box.
View log
The Android system log is divided into two parts, the underlying 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>] ...
Enter fullscreen mode
Exit fullscreen mode
Common usages are listed as follows:
Filter logs by level
Android logs are divided into the following priority (priority):
-V —— Verbose (lowest, most output)
-D —— Debug I —— Info
-W —— Warning
-E —— Error
-F—— Fatal
-S —— Silent (the highest, nothing is output)
Filtering logs by a certain level will output logs of that level and above.
For example, the command:
adb logcat *:W
Enter fullscreen mode
Exit fullscreen mode
Warning, Error, Fatal and Silent logs will be output.
(Note: Under macOS, you need to add double quotation marks to :W so that * as the tag parameter, such as adb logcat «:W», otherwise an error will be reported no matches found: *:W.)
Filter logs by tag and level
<filter-spec>
can be composed of multiple <tag>[:priority]
.
For example, the command:
adb logcat ActivityManager:I MyApp:D *:S
Enter fullscreen mode
Exit fullscreen mode
It means to output the log above Info of tag ActivityManager, output the log above Debug of tag MyApp, and the Silent log of other tags (that is, to block other tag logs).
Log Format
You can use the adb logcat -v <format>
option to specify the log output format.
The log supports the following types of <format>
:
-brief
The default format. The format is:
/():
Example:
D/HeadsetStateMachine( 1785): Disconnected process message: 10, size: 0
-process
The format is:
()
Example:
D( 1785) Disconnected process message: 10, size: 0 (HeadsetStateMachine)
-tag
The format is:
/:
Example:
D/HeadsetStateMachine: Disconnected process message: 10, size: 0
To
-raw
The format is:
Example:
Disconnected process message: 10, size: 0
-time
The format is:
/():
Example:
08-28 22:39:39.974 D/HeadsetStateMachine( 1785): Disconnected process message: 10, size: 0
-threadtime
The format is:
:
Example:
08-28 22:39:39.974 1785 1832 D HeadsetStateMachine: Disconnected process message: 10, size: 0
-long
The format is:
[ : /]
Example:
[08-28 22:39:39.974 1785: 1832 D/HeadsetStateMachine] Disconnected process message: 10, size: 0
The specified format can be used simultaneously with the above filtering. such as:
adb logcat -v long ActivityManager:I *:S
Enter fullscreen mode
Exit fullscreen mode
Clear log
adb logcat -c
Enter fullscreen mode
Exit fullscreen mode
Kernel log
command:
adb shell dmesg
Enter fullscreen mode
Exit fullscreen mode
Sample output:
<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.
Enter fullscreen mode
Exit fullscreen mode
The [14201.684016] in the brackets represents the time since the kernel started, in seconds.
Through the kernel log we can do some things, such as measuring the kernel startup time, find the time before the Freeing init memory line in the kernel log after the system is started.
View device information
Model
command:
adb shell getprop ro.product.model
Enter fullscreen mode
Exit fullscreen mode
Sample output:
Nexus 5
Battery status
command:
adb shell dumpsys battery
Enter fullscreen mode
Exit fullscreen mode
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
Enter fullscreen mode
Exit fullscreen mode
Among them, scale represents the maximum power, and level represents the current power. The output above indicates that 44% of the battery is left.
Screen Resolution
command:
adb shell wm size
Enter fullscreen mode
Exit fullscreen mode
Sample output:
Physical size: 1080x1920
Enter fullscreen mode
Exit fullscreen mode
The device screen resolution is 1080px * 1920px.
If it is modified using the command, the output may be:
Physical size: 1080x1920
Override size: 480x1024
Enter fullscreen mode
Exit fullscreen mode
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
Sample output:
Physical density: 420
The device screen density is 420dpi.
If it is modified using the command, the output may be:
Physical density: 480
Override density: 160
Indicates that the screen density of the device was originally 480dpi, but is currently modified to 160dpi.
Display parameters
command:
adb shell dumpsys window displays
Enter fullscreen mode
Exit fullscreen mode
Sample output:
WINDOW MANAGER DISPLAY CONTENTS (dumpsys window displays)
Display: mDisplayId=0
init=1080x1920 420dpi cur=1080x1920 app=1080x1794 rng=1080x1017-1810x1731
deferred=false layoutNeeded=false
Enter fullscreen mode
Exit fullscreen mode
Among them, mDisplayId is the display number, init is the initial resolution and screen density. The height of the app is smaller than that in init, which means that there are virtual buttons at the bottom of the screen. The height is 1920-1794 = 126px and 42dp.
android_id
command:
adb shell settings get secure android_id
Enter fullscreen mode
Exit fullscreen mode
Sample output:
51b6be48bac8c569
Enter fullscreen mode
Exit fullscreen mode
IMEI
In Android 4.4 and below versions, IMEI can be obtained by the following command:
adb shell dumpsys iphonesubinfo
Enter fullscreen mode
Exit fullscreen mode
Sample output:
Phone Subscriber Info:
Phone Type = GSM
Device ID = 860955027785041
The Device ID is IMEI.
Enter fullscreen mode
Exit fullscreen mode
In Android 5.0 and above, the output of this command is empty, and it must be obtained by other means (root permission is required):
adb shell
su
service call iphonesubinfo 1
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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...')
Enter fullscreen mode
Exit fullscreen mode
Extracting the effective content inside is the IMEI, for example, here is 860955027785041.
Reference: adb shell dumpsys iphonesubinfo not working since Android 5.0 Lollipop
Android system version
command:
adb shell getprop ro.build.version.release
Enter fullscreen mode
Exit fullscreen mode
Sample output:
5.0.2
IP address
Every time you want to know the IP address of the device, you have to «Settings»-«About Phone»-«Status Information»-«IP Address», which is annoying, right? It can be easily viewed through adb.
command:
adb shell ifconfig "| grep Mask"
Enter fullscreen mode
Exit fullscreen mode
Sample output:
inet addr:10.130.245.230 Mask:255.255.255.252
inet addr: 127.0.0.1 Mask: 255.0.0.0
Enter fullscreen mode
Exit fullscreen mode
Then 10.130.245.230 is the device IP address.
This command has no output on some devices. If the device is connected to WiFi, you can use the following command to view the local area network adb shell ifconfig wlan0 Example:
wlan0: ip 10.129.160.99 mask 255.255.240.0 flags [up broadcast running multicast]
Enter fullscreen mode
Exit fullscreen mode
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
Enter fullscreen mode
Exit fullscreen mode
If the above command still does not get the expected information, you can try the following command (available in some system versions):
adb shell netcfg
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
Enter fullscreen mode
Exit fullscreen mode
You can see information such as the network connection name, activation status, IP address, and Mac address.
Mac address
command:
adb shell cat /sys/class/net/wlan0/address
Enter fullscreen mode
Exit fullscreen mode
Sample output:
f8:a9:d0:17:42:4d
Enter fullscreen mode
Exit fullscreen mode
This is the local area network Mac address, 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
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
Enter fullscreen mode
Exit fullscreen mode
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 used is ARMv7 Processor rev 0 (v71).
Memory information
command:
adb shell cat /proc/meminfo
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
Enter fullscreen mode
Exit fullscreen mode
Among them, MemTotal is the total memory of the device, and MemFree is the current free memory.
More hardware and system properties
More hardware and system properties of the device can be viewed through the following commands:
adb shell cat /system/build.prop
Enter fullscreen mode
Exit fullscreen mode
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 command. Some properties 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 [Section 1] |
persist.sys.isUsbOtgEnabled | Whether to support OTG |
dalvik.vm.heapsize | Maximum memory limit for each application |
ro.sf.lcd_density | Screen density |
Section Note 1:
Some ROMs customized by small factories may have modified the attribute name of the abi list supported by the CPU. If you can’t find it with the ro.product.cpu.abilist attribute name, you can try:
adb shell cat /system/build.prop | grep ro.product.cpu.abi
Enter fullscreen mode
Exit fullscreen mode
Sample output:
ro.product.cpu.abi=armeabi-v7a
ro.product.cpu.abi2=armeabi
Enter fullscreen mode
Exit fullscreen mode
Modify settings
*Note: After modifying the settings, running the recovery command may still display abnormalities. You can run adb reboot to restart the device, or manually restart. *
The principle of modifying settings is mainly to modify the setting values stored in /data/data/com.android.providers.settings/databases/settings.db through the settings command.
Resolution
command:
adb shell wm size 480x1024
Enter fullscreen mode
Exit fullscreen mode
Means to modify the resolution to 480px * 1024px.
Restore the original resolution command:
adb shell wm size reset
Enter fullscreen mode
Exit fullscreen mode
Screen density
command:
adb shell wm density 160
Enter fullscreen mode
Exit fullscreen mode
Means to modify the screen density to 160dpi.
Restore the original screen density command:
adb shell wm density reset
Enter fullscreen mode
Exit fullscreen mode
Display area
command:
adb shell wm overscan 0,0,0,200
Enter fullscreen mode
Exit fullscreen mode
The four numbers respectively indicate the margin pixels from the left, top, right, and bottom edges. The above command means to leave the bottom of the screen 200px blank.
Restore the original display area command:
adb shell wm overscan reset
Enter fullscreen mode
Exit fullscreen mode
Turn off USB debugging mode
command:
adb shell settings put global adb_enabled 0
restore:
It can’t be restored with commands, after all, if USB debugging is turned off, adb cannot connect to the Android device.
Go to the device to manually restore it: «Settings»-«Developer Options»-«Android Debugging».
Display and hide status bar and navigation bar
The related settings mentioned in this section correspond to «Extended Desktop» in Cyanogenmod.
command:
adb shell settings put global policy_control <key-values>
Enter fullscreen mode
Exit fullscreen mode
<key-values>
can be composed of the following keys and their corresponding values, in the format of <key1>=<value1>:<key2>=<value2>
.
key | Meaning |
---|---|
immersive.full | Hide at the same time |
immersive.status | Hide the status bar |
immersive.navigation | Hide the navigation bar |
immersive.preconfirms | ? |
The values corresponding to these keys can be combined with commas as the following values:
value | Meaning |
---|---|
apps |
All applications |
* |
All interfaces |
packagename |
Specify application |
-packagename |
Exclude specific applications |
E.g:
adb shell settings put global policy_control immersive.full=*
Enter fullscreen mode
Exit fullscreen mode
Indicates that the status bar and navigation bar are hidden at the same time in all interfaces.
adb shell settings put global policy_control immersive.status=com.package1,com.package2:immersive.navigation=apps,-com.package3
Enter fullscreen mode
Exit fullscreen mode
It means setting to hide the status bar in applications with package names com.package1 and com.package2, and hide the navigation bar in all applications except package names com.package3.
Return to normal mode
What if I don’t want to be full screen?
adb shell settings put global policy_control null
Enter fullscreen mode
Exit fullscreen mode
Useful functions
Screenshots
Save screenshot to computer:
adb exec-out screencap -p> sc.png
Enter fullscreen mode
Exit fullscreen mode
If the adb version is older and the exec-out command cannot be used, it is recommended to update the adb version at this time. If you cannot update, you can use the following troublesome methods:
First save the screenshot to the device:
adb shell screencap -p /sdcard/sc.png
Enter fullscreen mode
Exit fullscreen mode
Then export the png file to the computer:
adb pull /sdcard/sc.png
Enter fullscreen mode
Exit fullscreen mode
You can use adb shell screencap -h to view the help information of the screencap command. The following are two meaningful parameters and their meanings:
Parameters | Meaning |
---|---|
-p | Specify the save file as png format |
-d display-id | Specify the screen number of the screenshot (if there are multiple screens) |
Actually, if the specified file name ends with .png, you can omit the -p parameter; otherwise, you need to use the -p parameter. If you do not specify the file name, the content of the screenshot file will be directly output to stdout.
Another way to take a screenshot of a one-line command and save it to the computer:
Linux and Windows
adb shell screencap -p | sed "s/\r$//"> sc.png
Enter fullscreen mode
Exit fullscreen mode
Mac OS X
adb shell screencap -p | gsed "s/\r$//"> sc.png
Enter fullscreen mode
Exit fullscreen mode
This method needs to use the gnu sed command, which is available directly under Linux, and under the bin folder of the Git installation directory under Windows. If you really cannot find the command, you can download sed for Windows and add the folder where sed.exe is located to the PATH environment variable.
However, using the sed command that comes with the system under Mac will report an error:
sed: RE error: illegal byte sequence
Enter fullscreen mode
Exit fullscreen mode
Need to install gnu-sed, and then use the gsed command:
brew install gnu-sed
Enter fullscreen mode
Exit fullscreen mode
Record screen
The recorded screen is saved to /sdcard in mp4 format:
adb shell screenrecord /sdcard/filename.mp4
Enter fullscreen mode
Exit fullscreen mode
Press Ctrl-C when you need to stop, the default recording time and maximum recording time are both 180 seconds.
If you need to export to a computer:
adb pull /sdcard/filename.mp4
Enter fullscreen mode
Exit fullscreen mode
You can use adb shell screenrecord —help to view the help information of the screenrecord command. The following are common parameters and their meanings:
Parameters | Meaning |
---|---|
—size WIDTHxHEIGHT | The size of the video, such as 1280x720 , the default is the screen resolution. |
—bit-rate RATE | The bit rate of the video, the default is 4Mbps. |
—time-limit TIME | Recording duration, in seconds. |
—verbose | Output more information. |
Remount the system partition as 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, deleting its own applications, etc. require writing to /system, so you need to remount it as read-write.
step:
Enter the shell and switch to root user authority.
command:
adb shell
su
Enter fullscreen mode
Exit fullscreen mode
View the current partition mounting status.
command:
mount
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
Enter fullscreen mode
Exit fullscreen mode
Find the line with /system that we are concerned about:
/dev/block/platform/msm_sdcc.1/by-name/system /system ext4 ro,seclabel,relatime,data=ordered 0 0
Enter fullscreen mode
Exit fullscreen mode
Remount.
command:
mount -o remount,rw -t yaffs2 /dev/block/platform/msm_sdcc.1/by-name/system /system
Enter fullscreen mode
Exit fullscreen mode
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 with the files under /system.
View connected WiFi passwords
*Note: root permission is required. *
command:
adb shell
su
cat /data/misc/wifi/*.conf
Enter fullscreen mode
Exit fullscreen mode
Sample output:
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
}
Enter fullscreen mode
Exit fullscreen mode
ssid is the name we see in the WLAN settings, psk is the password, and key_mgmt is the security encryption method.
Set the system date and time
*Note: root permission is required. *
command:
adb shell
su
date -s 20160823.131500
Enter fullscreen mode
Exit fullscreen mode
Means to change the system date and time to 13:15:00 on August 23, 2016.
restart cellphone
command:
adb reboot
Enter fullscreen mode
Exit fullscreen mode
Check if the device is rooted
command:
adb shell
su
Enter fullscreen mode
Exit fullscreen mode
At this time, the command line prompt is $, which means that there is no root authority, and # means that it is rooted.
Use Monkey for stress testing
Monkey can generate pseudo-random user events to simulate clicks, touches, gestures and other operations, and can perform random stress tests on programs under development.
Simple usage:
adb shell monkey -p <packagename> -v 500
Enter fullscreen mode
Exit fullscreen mode
It means to send 500 pseudo-random events to the application specified by <packagename>
.
For detailed usage of Monkey, refer to the official documentation.
Turn on/off WiFi
Note: root permission is required.
Sometimes you need to control the WiFi status of the device, you can use the following commands to complete.
Turn on WiFi:
adb root
adb shell svc wifi enable
Enter fullscreen mode
Exit fullscreen mode
Turn off WiFi:
adb root
adb shell svc wifi disable
Enter fullscreen mode
Exit fullscreen mode
Set wifi priority, use wifi first when there is network and wifi
adb shell svc wifi prefer
Enter fullscreen mode
Exit fullscreen mode
If the execution is successful, the output will be empty; if the command is executed without root permission, the execution will fail and the output will be Killed.
Turn on/off data traffic
svc data disable
Enter fullscreen mode
Exit fullscreen mode
This command can close the data connection, that is, the Internet traffic. Everyone knows that there are many switches to control the Internet, but most of them are realized by adding a suffix to the access point on the apn, but this command will not change any settings of the apn. The bottom layer closes the data connection. It should be the most thorough, and does not affect the apn settings. What is the difference between this and apndroid? When apndroid closes the Internet data, the downloading connection may not be forcibly closed (this is also mentioned in apndroid’s own instructions). For example, if you are downloading a 10M movie, if you download 1M, the download will not sound. Use apndroid to close the connection, maybe the download will continue, not immediately. But with this command, it clicked away without mercy.
adb shell svc data enable
Enter fullscreen mode
Exit fullscreen mode
This is to open the Internet data connection, which is the opposite of the previous command.
adb shell svc data prefer
Enter fullscreen mode
Exit fullscreen mode
This command is to control the data connection prior to wifi. We all know that under normal circumstances, when there is wifi, the data network connection will not be used. But this command is the opposite. If there is a data network, use data network traffic first, and use wifi when there is no data network.
Flashing related commands
Restart to Recovery mode
command:
adb reboot recovery
Enter fullscreen mode
Exit fullscreen mode
Restart from Recovery to Android
command:
adb reboot
Enter fullscreen mode
Exit fullscreen mode
Restart to Fastboot mode
command:
adb reboot bootloader
Enter fullscreen mode
Exit fullscreen mode
Update the system via 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:
Restart to Recovery mode.
command:
adb reboot recovery
Enter fullscreen mode
Exit fullscreen mode
Operate on the Recovery interface of the device to enter Apply update-Apply from ADB.
*Note: Different Recovery menus may be different from this. Some first-level menus have Apply update from ADB. *
*Upload and update the system via adb. *
command:
adb sideload <path-to-update.zip>
Enter fullscreen mode
Exit fullscreen mode
More adb shell commands
The Android system is based on the Linux kernel, so many commands in Linux have the same or similar implementations in Android and can be called in adb shell. The adb shell command has been used in the previous part of this document.
View process
adb shell ps
Enter fullscreen mode
Exit fullscreen mode
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
Enter fullscreen mode
Exit fullscreen mode
Meaning of each column:
Column name | Meaning |
---|---|
USER | Owned user |
PID | Process ID |
PPID | Parent process ID |
NAME | Process name |
View real-time resource usage
adb shell top
Enter fullscreen mode
Exit fullscreen mode
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
...
Enter fullscreen mode
Exit fullscreen mode
Meaning of each column:
Column name | Meaning |
---|---|
PID | Process ID |
PR | Priority |
CPU% | The percentage of CPU occupied at the current instant |
S | Process status (R=run, S=sleep, T=track/stop, Z=zombie process) |
#THR | Number of threads |
VSS | Virtual Set Size virtual memory consumption (including memory occupied by shared libraries) |
RSS | Resident Set Size actually uses physical memory (including memory occupied by shared libraries) |
PCY | Scheduling strategy 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 shows how many processes at most
-n num exit after refreshing how many times
-d num refresh interval (unit: second, default value 5)
-s col Sort by a column (available col values: cpu, vss, rss, thr)
-t display thread information
-h show help document
Enter fullscreen mode
Exit fullscreen mode
View process UID
There are two options:
adb shell dumpsys package <packagename> | grep userId=
Enter fullscreen mode
Exit fullscreen mode
Such as:
$ adb shell dumpsys package org.mazhuang.guanggoo | grep userId=
userId=10394
Enter fullscreen mode
Exit fullscreen mode
After finding the pid of the corresponding process through the ps command, adb shell cat /proc/<pid>/status | grep Uid
Such as:
$ 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:/$
Enter fullscreen mode
Exit fullscreen mode
Other
The following is a brief description of other commonly used commands. The commands that have been specifically mentioned above will not be explained separately:
Command | Features |
---|---|
cat | Display file content |
cd | Change directory |
chmod | Change file access mode/access permissions |
df | Check disk space usage |
grep | Filter output |
kill | Kill the process of the specified PID |
ls | List the contents of the directory |
mount | View and manage mount directories |
mv | Move or rename files |
ps | View the running process |
rm | Delete files |
top | Check the resource usage of the process |
Security related
Enable SELinux
Enable SELinux
adb root
adb shell setenforce 1
Enter fullscreen mode
Exit fullscreen mode
Disable SELinux
adb root
adb shell setenforce 0
Enter fullscreen mode
Exit fullscreen mode
Enable dm_verity
adb root
adb enable-verity
Enter fullscreen mode
Exit fullscreen mode
Disable dm_verity
adb root
adb disable-verity
Enter fullscreen mode
Exit fullscreen mode
common problem
Failed to start adb server
Error message
error: protocol fault (couldn't read status): No error
Enter fullscreen mode
Exit fullscreen mode
possible reason
The 5037 port that the adb server process wants to use is occupied.
solution
Find the process occupying port 5037, and then terminate it. Take Windows as an example:
netstat -ano | findstr LISTENING
...
TCP 0.0.0.0:5037 0.0.0.0:0 LISTENING 1548
...
Enter fullscreen mode
Exit fullscreen mode
Here 1548 is the process ID, end the process with the command:
taskkill /PID 1548
Enter fullscreen mode
Exit fullscreen mode
Then start adb and there is no problem.