I declare the following KeyEvents inside of my base testing class for an automation suite I'm running on an Android device for an application.
private static final KeyEvent pressPowerDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);
private static final KeyEvent pressPowerUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_POWER);
I then figure out what activity is being run inside of the Android Test context, and cast that context to an activity to fire the events:
if (_context instanceof Activity) {
Activity activity = (Activity) _context;
activity.dispatchKeyEvent(pressPowerDown);
activity.dispatchKeyEvent(pressPowerUp);
Upon examining the device during the automation, the KeyEvent mentioned above does not fire. I read about KeyListeners and simulating KeyEvents, but what I want to do here doesn't completely fall into either one of those categories (not using Robot, but an internal testing framework with its own Activity).
My original thought was that I needed to refocus the activity, but now I'm starting to think that I need some sort of KeyListener, which I'm not sure where to put, given that this is a test suite, not an interface class; it doesn't have any kind of interfaces associated with it at all!
If anyone knows how to create and fire KeyEvents inside of other programs, given that we don't have access to their internal mechanisms (the internal test tool cannot be modified - only the running state of the current test suite), it'd be greatly appreciated.
EDIT: I tested to see if KeyEvent is ever consumed after attempting to fire it three times:
System.out.println("Was the event consumed? " + activity.dispatchKeyEvent(pressPowerUp))
It was never fired, leading me to believe we need some kind of listener. If anyone has any idea how to implement a listener within a class, or if I'm allowed to declare a listener class and override the "dispatchKeyEvent" method, it'd be a great help.