Several things were done in the following code to make it work 1) set focus on the button in the UIThread, 2) disable keyguard so that you can send the keyEvent
public class MainWindowTest extends
ActivityInstrumentationTestCase2 {
private Instrumentation mInstrumentation;
private MainWindow mActivity;
private Button mButton;
private TextView mSensorReadView;
public MainWindowTest() {
super("com.kaipic.lightmeter", MainWindow.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstrumentation = getInstrumentation();
setActivityInitialTouchMode(false);
mActivity = getActivity();
mButton = (Button) mActivity.findViewById(R.id.read_button);
mSensorReadView = (TextView) mActivity.findViewById(R.id.sensor_read_text_view);
}
public void testClickButton() {
assertEquals("", mSensorReadView.getText());
mActivity.runOnUiThread(new Runnable() {
public void run() {
mButton.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
assertEquals("1", mSensorReadView.getText());
}
}
...
public class MainWindow extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
disableKeyGuardForTesting();
setContentView(R.layout.main);
Button readButton = (Button) findViewById(R.id.read_button);
readButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView sensor_read_text_view = (TextView) findViewById(R.id.sensor_read_text_view);
sensor_read_text_view.setText("1");
}
});
}
private void disableKeyGuardForTesting() {
KeyguardManager keyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
keyGuardManager.newKeyguardLock("com.kaipic.lightmeter.MainWindow").disableKeyguard();
}
}
in the AndroidManifest.xml you also need to have the following code under the tag manifest
<uses-permission name="android.permission.DISABLE_KEYGUARD" />
No comments:
Post a Comment