I am looking at ways to automate testing of an Android app widget. Part of the test is thus obviously to put the widget on the Home screen. I came up with a solution, but it's a bit too hackish for my taste so I wonder if there's any better way.
My requirement is for this to work on the emulator, using an external script. Right now I use a simple bash script, but the method I use should work with a monkeyrunner script too:
First I define a function to send keys to the emulator, as already indicated on SO:
function send() { ( nc -w 2 localhost 5554 <<EOL
event send $*
quit
EOL
) | grep -E -v "OK|KO|Android Console" ; }
and
function send_many() { for i in $* ; do send EV_KEY:$i:1 EV_KEY:$i:0 ; done ; }
The send() function is equivalent to calling MonkeyDevice.send(..., DOWN_AND_UP).
Now I can reliabily send a key sequence to open the menu, select Add (A key), go up twice and down once to select "Widget", select my widget (it happens to be the first one in the list), wait a second or two for the widget configuration UI to show up and select its install button in it:
$ send_many KEY_MENU KEY_A KEY_UP KEY_UP KEY_DOWN KEY_ENTER KEY_ENTER
$ sleep 2s
$ send_many KEY_UP KEY_RIGHT KEY_ENTER
Finally I wrap that all that in a script that iterates through a bunch of AVDs (e.g. "test_avd_N" where N is an API number from 3..12), closes any running emulator, opens a new one, wait for it to start and runs the test scripts. I prepare all the AVDs using snapshots and use the emulator -no-snapshot-save option to keep the snapshot intact between runs.
So overall it works but it's quite unsightly. I wonder what I could improve here.