How can I perform launching and stopping my server using Java code? Currently I am doing this process manually.
Advertisement
Answer
There are 3 ways to achieve the scenario.
1)Using AppiumDriverLocalService
JavaScript
x
public void startServer() {
//Set Capabilities
cap = new DesiredCapabilities();
cap.setCapability("noReset", "false");
//Build the Appium service
builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(4723);
builder.withCapabilities(cap);
builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
builder.withArgument(GeneralServerFlag.LOG_LEVEL,"error");
//Start the server with the builder
service = AppiumDriverLocalService.buildService(builder);
service.start();
}
public void stopServer() {
service.stop();
}
2)Using Appium.js with Node.exe
JavaScript
public void startServer() {
CommandLine cmd = new CommandLine("C:\Program Files (x86)\Appium\node.exe");
cmd.addArgument("C:\Program Files (x86)\Appium\node_modules\appium\bin\Appium.js");
cmd.addArgument("--address");
cmd.addArgument("127.0.0.1");
cmd.addArgument("--port");
cmd.addArgument("4723");
DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
try {
executor.execute(cmd, handler);
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void stopServer() {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("taskkill /F /IM node.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
3)Start Appium server using Command Prompt
JavaScript
public void startServer() {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("cmd.exe /c start cmd.exe /k "appium -a 127.0.0.1 -p 4723 --session-override -dc "{""noReset"": ""false""}""");
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void stopServer() {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("taskkill /F /IM node.exe");
runtime.exec("taskkill /F /IM cmd.exe");
} catch (IOException e) {
e.printStackTrace();
}
}<br/>
I found it helpful.Hope it helps. Source: http://www.automationtestinghub.com/3-ways-to-start-appium-server-from-java/