做Android开发的时候,经常会需要截取设备的屏幕甚至录制设备屏幕,来让同事知道提交的代码实现的功能,或者让他们知道产品中出现来什么问题。截取Android设备的屏幕有很多方法,比如在Nexus系列同时按下“电源”和“音量调低”按钮来截取,也可以用第三方程序来完成。通过另一部手机来拍照录像也是可行的方案。但是这些方法还需要想办法将文件传输到电脑上,又要多一步麻烦的操作。
Mac电脑上也有一些应用程序可以截屏Android设备,但是我更喜欢用终端指令,令人开心的是Android自带的 adb 已经提供了截取屏幕和录制屏幕的指定:
[codesyntax lang=”bash” lines=”normal”]
$ adb shell screencap /sdcard/screen.png $ adb shell screenrecord --verbose /sdcard/demo.mp4
[/codesyntax]
不过生成的文件依然保存在设备中,还需要用adb pull指定来转到电脑上
为了让整个过程更加的便捷,我将这些指令包裹在bash方法中,然后一个指令来完成截取和传输的工作。
截取Android设备当前屏幕并保存到执行指令的电脑目录上:
[codesyntax lang=”bash” lines=”normal”]
# capture screen of android device
andrdroidScreenCapture() {
curTime=`date +%Y-%m-%d-%H-%M-%S`
tmpeName="$curTime.png"
[[ -n $1 ]] && fileName=$1 || fileName=$tmpeName
devicePath="/sdcard/$tmpeName"
adb shell screencap -p $devicePath
adb pull $devicePath $fileName
adb shell rm $devicePath
}
[/codesyntax]
录取Android设备屏幕活动,结束后将视频文件保存到执行指令的电脑目录上:
[codesyntax lang=”bash” lines=”normal”]
export ADB_SHELL_SCREENRECORD_ARGS='--verbose --bit-rate 2000000'
# record screen of android device
androidScreenRecord() {
echo -e "\033[1m(press Ctrl-C to stop recording)\033[0m"
curTime=`date +%Y-%m-%d-%H-%M-%S`
tmpeName="$curTime.mp4"
[[ -n $1 ]] && fileName=$1 || fileName=$tmpeName
devicePath="/sdcard/$tmpeName"
adb shell screenrecord $ADB_SHELL_SCREENRECORD_ARGS $devicePath
sleep 1 # wait for video encoding finish
adb pull $devicePath $fileName
# Don't delete copy in device.
# adb shell rm $devicePath
open $fileName
}
[/codesyntax]
较短的指令别名,并通过提供的文件的扩展名来决定是截屏还是录制:
[codesyntax lang=”bash” lines=”normal”]
function asc() {
if [[ -z $1 ]]; then
echo "Please provide a filename."
echo "Provideing .png extension for capturing the device screen, and providing .mp4 for recording the device screen."
return
fi
if [[ $1 == *.png ]]; then
andrdroidScreenCapture $1
elif [[ $1 == *.mp4 ]]; then
androidScreenRecord $1
else
echo "Filename with unknow extension, only .png and .mp4 are supported"
fi
}
[/codesyntax]
完整脚本代码可以在Gist上找到,把它们加入到Mac电脑的~/.bash_profile中,连接上开启了“开发者模式”的Android设备就可以方便截图了。