Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Instrumentation HOME button

Any idea why sending the HOME key to an application running under Instrumentation does nothing?

import android.app.Instrumentation;
import android.view.KeyEvent;

public class MyInstrumentation extends Instrumentation {

  public void sendKeys() {
    // Works reliably
    this.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

    // Does nothing, nothing is printed to logcat
    this.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
  }
}

This is the same when using Robotium as well as when using Instrumentation directly. The behavior is the same on an emulator and a non-rooted device.

like image 240
Martin Konicek Avatar asked Dec 14 '22 20:12

Martin Konicek


1 Answers

The home button will not work within instrumentation, and even if it did it would leave you in a position that is not too favourable. Android Instrumentation can only instrument its own process which means that you would not be able to get back to your application once it had been sent away, and possibly worse would be slightly non deterministic as Android would be able to close your process if it so felt which would cause your tests to end.

That isn't much use to you though is it? I suspect you are trying to test something to do with the activity lifecycle which can be seen here. This can be tested via instrumentation but not in the easy way you wish it could. If you look at the API documents for the instrumentation class (here) you will see a whole lot of useful methods in the form of callActivityXXX(Activity activity) where XXX matches the lifecycle event you want to perform.

It is a bit more hardwork using these methods than the home relaunch I suspect you woudl like but it allows you to break down your testing to a lower level to ensure that your app is doing the right thing at each stage which will make it more robust as time goes on (say test it saves its state onPause and loads it again properly at onResume).

The next easiest method of doing your testing with instrumentation depends on if you are using an emulator or not, if this is only going to be run on an emulator you can use the orientation commands:

solo.setActivityOrientation(Solo.LANDSCAPE);
solo.setActivityOrientation(Solo.PORTRAINT);

Which will cause your activity to be destroyed and resumed testing some but not all states of the activity lifecycle.

like image 134
Paul Harris Avatar answered Jan 05 '23 08:01

Paul Harris