packagecom.github.uiautomator.stub;importandroid.content.Context;importandroid.content.Intent;importandroid.os.RemoteException;importandroid.support.test.InstrumentationRegistry;importandroid.support.test.filters.LargeTest;importandroid.support.test.filters.SdkSuppress;importandroid.support.test.runner.AndroidJUnit4;importandroid.support.test.uiautomator.By;importandroid.support.test.uiautomator.Configurator;importandroid.support.test.uiautomator.UiDevice;importandroid.support.test.uiautomator.Until;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.googlecode.jsonrpc4j.JsonRpcServer;importorg.junit.After;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;/*** Use JUnit test to start the uiautomator jsonrpc server.
*
*@authorxiaocong@gmail.com*/@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion= 18)public classStub {private final String TAG = "UIAUTOMATOR";private static final int LAUNCH_TIMEOUT = 5000;int PORT = 9008;
AutomatorHttpServer server= newAutomatorHttpServer(PORT);
@Beforepublic void setUp() throwsException {
launchService();//这是关键核心代码,把AutomatorService使用jsonRpcServer进行反射处理
server.route("/jsonrpc/0", new JsonRpcServer(new ObjectMapper(), new AutomatorServiceImpl(), AutomatorService.class));
server.start();
}private voidlaunchPackage(String packageName) {
Log.i(TAG,"Launch " +packageName);
UiDevice device=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
Context context=InstrumentationRegistry.getContext();final Intent intent =context.getPackageManager()
.getLaunchIntentForPackage(packageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
device.wait(Until.hasObject(By.pkg(packageName).depth(0)), LAUNCH_TIMEOUT);
device.pressHome();
}private void launchService() throwsRemoteException {
UiDevice device=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
Context context=InstrumentationRegistry.getContext();
device.wakeUp();//Wait for launcher
String launcherPackage =device.getLauncherPackageName();
Boolean ready= device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);if (!ready) {
Log.i(TAG,"Wait for launcher timeout");return;
}
Log.d("Launch service");
context.startService(new Intent("com.github.uiautomator.ACTION_START"));//Reset Configurator Wait Timeout
Configurator configurator =Configurator.getInstance();
configurator.setWaitForSelectorTimeout(0L);//BUG(uiautomator): setWaitForIdleTimeout is useless//Refs:https://www.ydkf.me/archives/22
}
@Afterpublic voidtearDown() {
server.stop();
Context context=InstrumentationRegistry.getContext();
context.startService(new Intent("com.github.uiautomator.ACTION_STOP"));
}
@Test
@LargeTestpublic void testUIAutomatorStub() throwsInterruptedException {while(server.isAlive()) {
Thread.sleep(100);
}
}
}