Android’s user interface is easy to use, but what if you need to automate interaction with a device, for example to provision 400 new devices, remotely? Thankfully, Android has a number of useful shell commands that can be scripted using adb, for things like taking and restoring backups, changing system settings, installing, starting and removing apps, enabling and disabling wifi or cell data, accessing databases, and more.
Let’s examine a few of these commands. You’ll need to have adb installed; if you don’t already have it, try one of these tutorials on installing adb. Some of these commands require root access, but others work even on unrooted devices. Let’s start with something simple.
Most Android devices have a key combo to grab a screenshot, but say we want to automate it, or get the screenshot remotely. Let’s take a snapshot of the screen from a Linux host and save it as screen.png in the current directory.
adb shell screencap -p | sed 's/\r$//' > screen.png
Or from a Mac:
adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png
(Unfortunately the above command is a bit complicated due to linefeed translation that occurs along the way; read this if you’re interested in the details.)
Screenshots are nice, but what if you want to capture something dynamic happening on the screen? Try this:
adb shell screenrecord /sdcard/capture.mp4
adb pull /sdcard/capture.mp4 capture.mp4
Now you have an MP4 file in your host’s current directory that you can play using your preferred video player.
Here’s one that compresses the video more, and spits out more info while recording:
adb shell screenrecord --bit-rate 1000000 --verbose /sdcard/capture.mp4
Screenrecord has several other options to play with:
adb shell screenrecord --help
Usage: screenrecord [options] <filename>
Records the device's display to a .mp4 file.
Set the video size, e.g. "1280x720". Default is the device's main
display resolution (if supported), 1280x720 if not. For best results,
use a size supported by the AVC encoder.
Set the video bit rate, in megabits per second. Default 4Mbps.
Set the maximum recording time, in seconds. Default / maximum is 180.
Rotate the output 90 degrees.
Display interesting information on stdout.
Show this message.
Recording continues until Ctrl-C is hit or the time limit is reached.