Skip to content

Instantly share code, notes, and snippets.

@michaelsanford
Last active August 29, 2015 14:03
Show Gist options
  • Save michaelsanford/029eef643f49e409ddf3 to your computer and use it in GitHub Desktop.
Save michaelsanford/029eef643f49e409ddf3 to your computer and use it in GitHub Desktop.
Android screenshot (Glass, Wear, mobile)
#!/usr/bin/env bash
##
# Screencaps, pulls, and deletes the png from a device.
#
# gcap [w | a | device identifier]
#
# For debugging over Bluetooth (i.e., Android Wear), see
# https://developer.android.com/training/wearables/apps/bt-debugging.html
#
# Instructions:
# https://medium.com/@msanford/taking-android-screenshots-652d6794f679
##
set -o nounset # Exit on unset variable
set -o errexit # Exit on first error
TARGET_DEVICE=${1:-""}
ETIME=$(date +"%s")
# Options
TARGET_PATH=~/Desktop
capture() {
local dev=${1}
local file="screen-${dev}-${ETIME}.png"
if [[ "${dev}" == *localhost* ]]; then
file="screen-wear-${ETIME}.png"
fi
local dest=${TARGET_PATH}/${file}
echo "Capping ${dev} to ${dest}..."
adb -s "${dev}" shell /system/bin/screencap -p "/sdcard/${file}" || {
# Cap failed, inform and break
if [[ $? -eq 255 ]]; then
echo "Could not communicate with specified device [${dev}]; exiting !"
else
echo "Unknown error occured for [${dev}]; exiting !"
fi
exit $?
}
# Pull cap and clean up the SD card (if dest pulled)
adb -s "${dev}" pull "/sdcard/${file}" "${dest}" && \
adb -s "${dev}" shell rm "/sdcard/${file}"
}
if [ "${TARGET_DEVICE}" = "" ]; then
# If no device is provided, use the first one, which is adb's default
# behaviour but we need to acquire the device identifier for the file name.
DEVICE=$(adb devices | sed -n 2p | awk '{print $1}')
capture "${DEVICE}"
elif [ "${TARGET_DEVICE}" = "w" ]; then
# "w" represents an Android Wear device, teathered over bluetooth.
# If not teathered, this section is irrelevant.
DEVICE=$(adb devices | grep "localhost" | awk '{print $1}')
capture "${DEVICE}"
elif [ "${TARGET_DEVICE}" = "a" ]; then
# "a" loop over all connected devices and cap them
DEVICE_ARRAY=$(adb devices | awk '{print $1}' | tail -n +2)
for dev in "${DEVICE_ARRAY[@]}"; do
capture "${dev}"
done
else
# We assume a device identifier has been passed, so use that directly
capture "${TARGET_DEVICE}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment