sdkmanager "platform-tools" "emulator" "system-images;android-34;google_apis;x86_64"$ANDROID_SDK_ROOT/emulator、$ANDROID_SDK_ROOT/platform-tools 加入 PATH。| 操作 | 命令 | 說明 |
|---|---|---|
| 列出可用系統映像 | sdkmanager --list | grep system-images | 或 avdmanager list (舊) |
| 列出已安裝映像 | sdkmanager --list_installed | grep system-images | |
| 建立 AVD | avdmanager create avd -n Pixel8_API34 -k "system-images;android-34;google_apis;x86_64" -d "pixel_8" --force | -d 指定裝置定義 (可用 avdmanager list device 查看) |
| 列出已建立 AVD | avdmanager list avd 或 emulator -list-avds | |
| 啟動 AVD (前景) | emulator -avd Pixel8_API34 | 終端機會佔用,輸出日誌 |
| 啟動 AVD (背景/無頭) | emulator -avd Pixel8_API34 -no-window -no-audio -no-boot-anim -gpu swiftshader_indirect & | CI/CD 適用,-no-window 無 GUI |
| 指定啟動參數 | emulator -avd Pixel8_API34 -netdelay gsm -netspeed edge -scale 0.8 -memory 2048 -partition-size 4096 | 網路模擬、縮放、記憶體、資料分區大小 |
| 快照管理 | emulator -avd Pixel8_API34 -snapshot-list / -snapshot snap_name / -no-snapshot-load -no-snapshot-save | 快速儲存/恢復狀態 |
| 刪除 AVD | avdmanager delete avd -n Pixel8_API34 | 刪除 ~/.android/avd/Pixel8_API34.avd 目錄 |
| 查看模擬器進程 | adb devices (顯示 emulator-5554 等) | |
| 關閉模擬器 | adb -s emulator-5554 emu kill 或 Ctrl+C (前景模式) |
-gpu host / swiftshader_indirect / angle_indirect:GPU 加速模式,Mac/Windows 建議 host,Linux CI 建議 swiftshader_indirect。-camera-back emulated / -camera-front webcam0:模擬相機。-writable-system:系統分區可寫 (需 root,配合 adb root adb remount)。-selinux disabled:暫時關閉 SELinux 測試。-feature -Vulkan:停用 Vulkan 相容性測試。-prop persist.adb.tcp.port=5555:啟用 TCP/IP ADB (需重啟)。| 問題 | 原因/解決 |
|---|---|
| 啟動卡在 "Boot animation" / 黑屏 | 關閉 Hyper-V / Windows Hypervisor Platform (關閉後需重啟);或啟用 WHPX (-feature +Whpx);確認 BIOS 開啟 VT-x/SVM。 |
| emulator: ERROR: x86 emulation requires hardware acceleration | 安裝 Intel HAXM (Intel CPU) 或啟用 WHPX (Windows 10 1803+),AMD CPU 需開啟 SVM + Windows Hypervisor Platform。 |
| 無法連網 | 檢查宿主機網路、DNS、代理;模擬器預設 10.0.2.2 對應宿主機 localhost。 |
| 磁碟空間不足 | emulator -avd X -wipe-data 清理快照;遷移 AVD 目錄到大磁碟 (ANDROID_AVD_HOME 環境變數)。 |
| 鍵盤不輸入 | Extended controls → Settings → "Send keyboard shortcuts to virtual device" 勾選;或使用軟鍵盤。 |
#!/bin/bash
set -e
AVD_NAME="ci_pixel8_api34"
# 1. 確保 AVD 存在
if ! emulator -list-avds | grep -q "^${AVD_NAME}$"; then
echo "Creating AVD..."
avdmanager create avd -n "$AVD_NAME" -k "system-images;android-34;google_apis;x86_64" -d "pixel_8" --force
fi
# 2. 啟動無頭模擬器
emulator -avd "$AVD_NAME" -no-window -no-audio -no-boot-anim -gpu swiftshader_indirect -no-snapshot-load &
EMU_PID=$!
# 3. 等待啟動完成 (boot_completed)
adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done'
echo "Emulator ready."
# 4. 執行測試
./gradlew connectedAndroidTest
# 5. 關閉
adb -s emulator-5554 emu kill
wait $EMU_PID
熟練命令列操作 AVD,讓本地開發、CI/CD、自動化測試流程更順暢。