How to start Appium Server in macOS via Java code?

For that you could use below code.

Tip-

Type which appium command in Mac Terminal to get appiumPath

package com.test;

import io.appium.java_client.AppiumBy;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import io.appium.java_client.remote.AutomationName;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class StartAppiumServer {

    private Process appiumProcess;
    private String appiumHost="127.0.0.1";
    private int appiumPort=4723;

    @BeforeClass
    public void startAppiumServer() throws IOException, InterruptedException {
        System.out.println("My before class.");
        // Replace "path/to/appium" with the actual path to your Appium executable
        String appiumPath = "/opt/homebrew/bin/appium"; // Replace with your actual path
        // here this " --address 127.0.0.1 --port 4723" been parameterized
        String command = appiumPath + " --address " + appiumHost + " --port " + appiumPort;
        appiumProcess = Runtime.getRuntime().exec(command);

        // Wait for Appium server to be up and running instead of using  Thread.sleep(45000);
        waitForAppiumServer(appiumHost, appiumPort);
        System.out.println("Appium servier is started.");
    }

    @Test
    void androidLaunchTest() throws MalformedURLException, InterruptedException {

        UiAutomator2Options options = new UiAutomator2Options();
        options.setAutomationName(AutomationName.ANDROID_UIAUTOMATOR2);
        options.setPlatformName("Android"); //optional
        options.setPlatformVersion("10"); //Optional
        options.setDeviceName("emulator-5554");
        options.setApp(System.getProperty("user.dir") + "/apps/mydemoapp.apk");
        options.setNoReset(false); // This will reset the app
        // options.setAppPackage("com.saucelabs.mydemoapp.rn");
        // options.setAppActivity("com.saucelabs.mydemoapp.rn.MainActivity");


       // Here this been parametrized "http://127.0.0.1:4723"
        String url = "http://" + appiumHost + ":" + appiumPort;
        AndroidDriver driver = new AndroidDriver(new URL(url), options);
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // Set implicit wait to 10 seconds
        WebElement okButton = driver.findElement(AppiumBy.id("android:id/button1"));
        okButton.click();
        WebElement allowButton = driver.findElement(AppiumBy.id("com.android.permissioncontroller:id/permission_allow_button"));
        allowButton.click();
        WebElement swipeToSeeMoreButton = driver.findElement(AppiumBy.id("com.myapp.qa:id/swipe_more_text"));
        swipeToSeeMoreButton.click();

    }

    private void waitForAppiumServer(String host, int port) throws InterruptedException, IOException {
        int maxWaitTime = 30; // Adjust as needed (seconds)
        int waitTime = 0;
       // Here sends a GET request to http://127.0.0.1:4723/status
        while (waitTime < maxWaitTime) {
            try {
                URL url = new URL("http://" + host + ":" + port + "/status");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    System.out.println("Appium server is up and running.");
                    return;
                }
            } catch (IOException e) {
                // Handle connection exceptions (e.g., ConnectException, SocketTimeoutException)
                System.out.println("Appium server is not yet available: " + e.getMessage());
            }

            Thread.sleep(2000); // Wait for 2 seconds before retrying
            waitTime += 2;
        }

        throw new RuntimeException("Appium server failed to start within the timeout");
    }
    @AfterClass
    public void stopAppiumServer() {
        if (appiumProcess != null) {
            appiumProcess.destroy();
        }
    }

}
0
Subscribe to my newsletter

Read articles from Sameera De Silva directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sameera De Silva
Sameera De Silva