How can I create appium driver programmatically

I am working on Appium 2.0. I want targeted drivers (UiAutomator2 or XCUITest) to be installed programmatically while executing the test
How can I do that?

Take a look at capabilities and ‘automationName’ specifically. Specifying correct value there (XCUItest or UIAutomator2, for example) should get you what you are looking for.

I am sending these capabilities, this works in Appium 1.0
But in appium 2.0 we have to create drivers manually using command
appium driver install uiautomator2

but I do not want to do this manually but programattically

This is my entire code
AppiumServiceBuilder builder;
builder = new AppiumServiceBuilder().withArgument(() -> “–base-path”, “/wd/hub”).withArgument(() -> “–plugins”, “images”);
builder.usingDriverExecutable(new File(“path_to_nodejs\node.exe”));
builder.withAppiumJS(new File(“path_to_appium\appium”));
HashMap<String, String> environment = new HashMap();
environment.put(“PATH”, “/usr/local/bin:” + System.getenv(“PATH”));
service = AppiumDriverLocalService.buildService(builder);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“appium:platformName”, “Android”);
capabilities.setCapability(“deviceName”, “Android Emulator”);
capabilities.setCapability(“appium:automationName”, “UiAutomator2”);
capabilities.setCapability(“app”, “app_path\Learn_Android_With_Source_Code.apk”);

    androidDriver = new AndroidDriver<AndroidElement>(service.getUrl(), capabilities);
    androidDriver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    return androidDriver;

Why it would be necessary to install a driver every time a new test starts? I assume it is actually possible to request drivers install upon appium package installation

Ok that means driver has to be install manually when I installing appium on my machine.

But still if I wanted to do it programmatically how can it be done.
We have product which codeless automation tool and we are using APPIUM APIs underneath of Mobile test Automation. Currently we are bundling Appium 1.x with that product.
SO the question is if we want to move to Appium 2.0 how driver installation will taken place on clients end with appium 2.0 we can bundle appium server but how can driver installation happen