Start Appium session programmatically

If you like to automate routine actions and you don't want to launch Appium session manually each and every time, you may find helpful this post. This is just a short example of how to launch Appium session from your java code.

First of all you need an instance of AppiumDriverLocalService. Apart from that, you need to specify paths to nodejs and nodejs Appium package, Appium server address and port. And the code itself will look like this:

 private static final String APPIUM_SERVER_ADDRESS = "0.0.0.0";
 private static final int APPIUM_SERVER_PORT = 4723;
 private static final String PATH_TO_NODEJS = "/home/olyv/nodejs/bin/node";
 private static final String PATH_TO_NODEJS_APPIUM = "/home/olyv/nodejs/bin/appium";

 private void startAppiumServerIfNotRunning(AppiumDriverLocalService appiumService) {
    if (!appiumService.isRunning()) {
        appiumService.start();
    }
 }
    
 private AppiumDriverLocalService getAppiumService() {
    return AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
            .usingDriverExecutable(new File((PATH_TO_NODEJS)))
            .withAppiumJS(new File((PATH_TO_NODEJS_APPIUM)))
            .withIPAddress(APPIUM_SERVER_ADDRESS)
            .usingPort(APPIUM_SERVER_PORT));
 }

You can notice that here we are checking if session is already running: appiumService.isRunning(). If we don't check it and launch another yet session, exception will be thrown and and program execution ends.

And that's all you need to launch a new Appium session from script.

Comments