LoginSignup
1
0
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

adbを用いて複数のAndroidデバイス接続時にスクリーンショットを取る方法

Last updated at Posted at 2024-01-27

はじめに

端末のスクリーンショットを撮る機会って、意外とありますよね。
PCにandroid端末を接続していると、adbコマンドを使って、簡単にスクリーンショットを撮ることができます。

adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png

参考: https://qiita.com/TNaruto/items/b2407f5668e15e42bedd

問題点

しかし、複数の端末を接続していると、下記のようなエラーが出てしまいます。

adb: more than one device/emulator
adb: error: failed to get feature set: more than one device/emulator
adb: more than one device/emulator

これは、adbコマンドが複数の端末を認識してしまい、
どの端末に対してスクリーンショットを撮るか判断できないためです。

解決策

そこで、端末を指定してあげることで、エラーを回避することができます。

adb -s emulator-5554 shell screencap -p /sdcard/screenshot.png
adb -s emulator-5554 pull /sdcard/screenshot.png
adb -s emulator-5554 shell rm /sdcard/screenshot.png

指定する端末名はadb devicesコマンドで確認できます。

解決策の問題点

普段の開発だと、エミュレーター + 実機などのように
複数台繋ぐことが多い方もいらっしゃると思います。
(少なくとも自分はそうです。)
毎回、端末を指定するのは、ちょっと面倒です。

解決策の問題点の解決策

そういった方のために、下記のようなシェルスクリプトを作成しました。
(ほとんど、copilotによる自動生成ですが…)
これで、複数の端末を接続していても、スクリーンショットを撮ることができます。
もちろん、1台しか接続していない場合でも、問題なく動作します。

3行目のsave_dirには、
スクリーンショットを保存するディレクトリを指定してください。

#!/bin/zsh
# 保存するディレクトリ
save_dir="/Users/XXXX/Documents/screenshot"

devices=()
while IFS= read -r line; do
    if [[ $line == *device* ]]; then
        devices+=("${line%%[[:space:]]*}")
    fi
done < <(adb devices | tail -n +2)

if [[ ${#devices[@]} -eq 0 ]]; then
    echo "端末が接続されていません。"
    exit 1
fi

if [[ ${#devices[@]} -eq 1 ]]; then
    selected_device="${devices[1]}"
fi

if [[ ${#devices[@]} -gt 1 ]]; then
    for ((i=1; i<=${#devices[@]}; i++)); do
        echo "$i: ${devices[$i]}"
    done
    echo -n "端末を選択してください: "
    read choice

    if [[ $choice =~ ^[0-9]+$ ]]; then
        if [[ $choice -ge 0 && $choice -le ${#devices[@]} ]]; then
            selected_device="${devices[$choice]}"
            echo "選択された端末: $selected_device"
        else
            echo "無効な選択です。"
        fi
    else
        echo "無効な入力です。数値を入力してください。"
    fi
fi

file_name="${selected_device}_$(date "+%Y%m%d%H%M%S").png"
adb -s $selected_device shell screencap -p /sdcard/sc.png
adb -s $selected_device pull /sdcard/sc.png $save_dir/$file_name
adb -s $selected_device shell rm /sdcard/sc.png
echo "スクリーンショットを保存しました。"

お役に立てれば幸いです。

詰まったところ

zshは、配列が1から始まるんですね。知りませんでした。
参考: https://egawata.hatenablog.com/entry/2017/07/31/000942

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0