In order to programmatically start and stop an Android Emulator from Powershell, have a look at the Powershell script I’ve created below. This post assumes you already have the Android SDK, AVD and emulators set up on your machine. It is also assumed that you will only have one emulator instance at a time, to keep things simple.
# Variables
$emulatorExe = ".\emulator.exe"
$androidEmulator= "nexus_emulator"
$partitionSize = "512"
$emulatorPath = "C:\Program Files (x86)\Android\android-sdk\emulator\emulator.exe"
# START EMULATOR
Write-Host "Starting the Emulator..."
Start-Process -FilePath $emulatorPath -ArgumentList "-avd $androidEmulator -partition-size $partitionSize"
# DO STUFF HERE
Start-Sleep -s 10
# STOP EMULATOR
Write-Host "Stopping the Emulator..."
cmd /c "adb -e emu kill"
What this PS1 script will do is start up the emulator with the given variables:
- $emulatorExe – The location of emulator.exe on your machine
- $androidEmulator – Name of the emulator you want to open
- $partitionSize – Internal storage allocated to your emulator
- $emulatorPath – Path to where your emulator is located
It will then start up another process (outside of the current script process), for running the emulator with the provided variables:
Start-Process -FilePath $emulatorPath -ArgumentList "-avd $androidEmulator -partition-size $partitionSize"
The script will then sleep for 10 seconds before stopping the emulator. (Feel free to modify as you see fit, or perform actions between starting/stopping the emulator. This is only used as an example to show starting and stopping an emulator through powershell.
Afterwards, we will stop the emulator using the following command:
Programmatically starting/stopping an Android emulator is especially useful for test automation (UI Tests), when ran on build servers. You may want to look into setting this up in your project build script.