Share this page

# Mobile code samples (Java SDK)

In this topic:

## Tap a button on a mobile device

This example taps a button on an AUT and verifies that the required string is displayed in an edit field.

                        @Test
    public void mobileButtonTest() throws Exception {
    	// Lock device by its UFT Mobile name.
    	Device device = MobileLab.lockDeviceByName("MyDevice");

    	// Describe the AUT.
    	Application app = device.describe(Application.class, new ApplicationDescription.Builder()
    		.identifier("com.sample.UICatalog").build());

    	// Launch or restart the app.
    	app.restart();

    	// Describe the table in the app's front screen.
    	// Select the 15th item in the table to open a screen with a button.
    	app.describe(Table.class, new TableDescription.Builder().className("Table").resourceId("list").build()).select(14); // Index is 0-based.

    	// Describe a button in the application.
    	Button button = app.describe(Button.class, new ButtonDescription.Builder()
    		.className("Button")
    		.resourceId("button1")
    		.text("Tap Me").build());

    	// Tap the button to change the text in an EditField to "You Tapped Me".
    	button.tap();

    	// Describe the EditField.
    	EditField editField = app.describe(EditField.class, new EditFieldDescription.Builder()
    		.className("Input")
    		.resourceId("editText1").build());

    	// Verify the text.
    	Verify.areEqual("You Tapped Me", editField.getText(), "MobileButtonTest - Verify Buttons's Text", "Verify the button contains the text 'You Tapped Me'.");

    	device.unlock(); // unlock the device at the end of the test
    }

Back to top

## Perform a search in a WebView

This example demonstrates use of a WebView using Mobile and Web technologies by accessing the Google search page in a WebView and performing a search.

    @Test

                    public void webViewTest() throws Exception {

     // Lock device by its UFT Mobile name.

     Device device = MobileLab.lockDeviceByName("MyDevice");

     // Describe the AUT.

     Application app = device.describe(Application.class, new ApplicationDescription.Builder()

      .identifier("com.sample.UICatalog").build());

     // Launch or restart the app.

     app.restart();

     // Describe the Table on the front screen.

     // Select the 17th item in the table to open a screen with a WebView of google.com.

     app.describe(Table.class, new TableDescription.Builder().className("Table").resourceId("list").build()).select(16); // Index is 0-based.

     // Describe the page in the WebView.

     com.hp.lft.sdk.web.Page webViewPage = app.describe(WebView.class, new WebViewDescription.Builder()

      .className("WebView")

      .resourceId("webview")

      .mobileCenterIndex(0).build())

      .describe(com.hp.lft.sdk.web.Page.class, new com.hp.lft.sdk.web.PageDescription());

     // Describe the Web EditField of the Google search.

     com.hp.lft.sdk.web.EditField searchEditField = webViewPage.describe(com.hp.lft.sdk.web.EditField.class,

      new com.hp.lft.sdk.web.EditFieldDescription.Builder().type("search").tagName("INPUT").name("q").build());

     // Enter some text in the edit field.

     searchEditField.setValue("Some Text");

     // Describe the search Web button.

     com.hp.lft.sdk.web.Button searchGoButton = webViewPage.describe(com.hp.lft.sdk.web.Button.class,

      new com.hp.lft.sdk.web.ButtonDescription.Builder().buttonType("submit").tagName("BUTTON").name("btnG").build());

     // Click the button to perform the search.

     searchGoButton.click();

    }

Back to top

## Iterate through connected devices

This example show how to iterate through all the mobile devices using the getDeviceList method

If a device named "MyDevice" is found, the sample locks it, and then unlocks it.

    @Test

                    public void mobileDevicesListTest() throws Exception {

     // Iterate through all the mobile devices using the getDeviceList method

     for (DeviceInfo deviceInfo : MobileLab.getDeviceList()) {

      System.out.printf("The device ID is: %s, and its name is: %s", deviceInfo.getId(), deviceInfo.getName());

      if (deviceInfo.getName().equals("MyDevice")){

       Device device = MobileLab.lockDeviceByInfo(deviceInfo);

       // Do some stuff here

       // .

       // .

       // .

       // And finally release this device's lock

       device.unlock();

      }

     }

    }

Back to top

## Lock and automatically unlock a device at the end of a session

This example locks a device by choosing a device with the Android OS, version later than 4.4.0.

It then taps a button on an AUT and verifies that the required string is displayed in an edit field.

It then unlocks the device at the end of the session.

                        @Test
    public void mobileDeviceCapabilitiesTest() throws Exception {
    	// Lock device by its UFT Mobile name.
    	Device device = MobileLab.lockDevice(new DeviceDescription.Builder().
    	osType("ANDROID").osVersion(">4.4.0").build());

    	// Describe the AUT.
    	Application app = device.describe(Application.class, new ApplicationDescription.Builder()
    		.identifier("com.sample.UICatalog").build());

    	// Launch or restart the app.
    	app.restart();

    	// Describe the table in the app's front screen.
    	// Select the 15th item in the table to open a screen with a button.
    	app.describe(Table.class, new TableDescription.Builder().className("Table").resourceId("list").build()).select(14); // Index is 0-based.

    	// Describe a button in the application.
    	Button button = app.describe(Button.class, new ButtonDescription.Builder()
    		.className("Button")
    		.resourceId("button1")
    		.text("Tap Me").build());

    	// Tap the button to change the text in an EditField to "You Tapped Me".
    		button.tap();

    	// Describe the EditField.
    	EditField editField = app.describe(EditField.class, new EditFieldDescription.Builder()
    		.className("Input")
    		.resourceId("editText1").build());

    	// Verify the text.
    	Verify.areEqual("You Tapped Me", editField.getText(), "MobileButtonTest - Verify Buttons's Text", "Verify the button contains the text 'You Tapped Me'.");

    	device.unlock(); // unlock the device at the end of the test
    }

Back to top

## Collect accumulated device vitals data

This example retrieves the CPU and free memory data of a device, accumulated while it was locked.

                         @Test
    public void mobileDeviceVitalsTest() throws Exception {

    	DeviceSessionOptions sessionOptions = new DeviceSessionOptions().setCollectVitals(new DeviceVitalsCollectOptions()
    		.setCollectCPU(true).setCollectFreeMemory(true));

    	// Lock device by its UFT Mobile name.
    	Device device = MobileLab.lockDevice(new DeviceDescription.Builder().
    	id("5e9d9a9a17f131aa4389c92ef986fcef9481112f").build(), sessionOptions);

    	// ... do something

    	// get the collected vitals
    	String vitals = device.getVitals();

    	// process vitals
    	String[] vitalLines = vitals.split("\n\r");
    	for (String vitalLine : vitalLines){
    		String[] vitalLineParts = vitalLine.split(" ");
    		System.console().writer().println("at: " + vitalLineParts[2] + ": " + vitalLineParts[0] + " = " + vitalLineParts[1]);
    	}
    }

Back to top

## Camera simulation

This section includes two examples:

- Image upload
- Video upload

                    package com.hpe.demo;

    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.File;
    import java.io.IOException;

    import javax.imageio.ImageIO;

    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;

    import com.hp.lft.sdk.*;
    import com.hp.lft.sdk.mobile.Application;
    import com.hp.lft.sdk.mobile.ApplicationDescription;
    import com.hp.lft.sdk.mobile.Device;
    import com.hp.lft.sdk.mobile.MobileLab;
    import com.hp.lft.verifications.*;

    import unittesting.*;

    public class LeanFTMobileCameraSimulationExamples extends UnitTestClassBase {

    	public LeanFTMobileCameraSimulationExamples() {
    	//Change this constructor to private if you supply your own public constructor
    	}

    	@BeforeClass
    	public static void setUpBeforeClass() throws Exception {
    		instance = new LeanFTMobileCameraSimulationExamples();
    		globalSetup(LeanFTMobileCameraSimulationExamples.class);
    	}

    	@AfterClass
    	public static void tearDownAfterClass() throws Exception {
    		globalTearDown();
    	}

    	@Before
    	public void setUp() throws Exception {
    	}

    	@After
    	public void tearDown() throws Exception {
    	}

    	@Test
    	public void mobileCameraSimulationExampleTestWithImageUpload() throws GeneralLeanFtException {

    		// First - lock the device you want to use
    		Device device = MobileLab.lockDeviceById("MyDeviceId");

    		// Next, we will upload a media file to the device
    		BufferedImage img = null;
    		try{
    			img = ImageIO.read(new File("C:\\Temp\\abcde.png"));
    		} catch (IOException e) {
    		        // Do the necessary error handling here

                           // .

                           // .

                           // .
    		}
    		String mediaId = "abcde.png";
    		ImageFormat imageFormat = ImageFormat.PNG;
    		device.uploadMedia((RenderedImage)img, imageFormat, mediaId);

    		// Launch the application to use
    		Application app = device.describe(Application.class,
    				new ApplicationDescription.Builder().identifier("com.sample.UICatalog").version("2.0").packaged(true).build());
    		app.launch();

    		// Start the camera simulation mode
    		app.startCameraSimulationMode(mediaId);

    		// Now if the application under test shows an image from the camera, it should show the image we uploaded.              // .

                   // . Add testing steps

                   // .

                   // Stop the camera simulation mode
    		app.stopCameraSimulationMode();

    		// Stop the application
    		app.kill();
    		// Add cleanup steps if required
    	}

    @Test
    public void mobileCameraSimulationExampleTestWithVideoUpload() throws GeneralLeanFtException, IOException {

    	// First - lock the device you want to use
    	Device device = MobileLab.lockDeviceById("MyDeviceId");

    	// Next, upload a media file to the device
    	String mediaId = "android22.mp4";
    	VideoData vd = new VideoData("C:\\Temp\\android22.mp4");
    	device.uploadMedia(vd, mediaId);

    	// Launch the application to use
    	Application app = device.describe(Application.class,
    				new ApplicationDescription.Builder().identifier("com.sample.UICatalog").version("2.0").packaged(true).build());
    	app.launch();

    	// Start the camera simulation mode
    	app.startCameraSimulationMode(mediaId);

    	// Now if the application under test shows a video from the camera, it should show the video we uploaded.      // .

           // . Add steps to the test

           // .

           // Stop the camera simulation mode
    	app.stopCameraSimulationMode();

    	// Stop the application
    	app.kill();
    	// Add cleanup steps if required
    	}

    }

Back to top

## Simulate fingerprint authentication

This example shows how to simulate fingerprint authentication.

                    @Test
    public void mobileSimulateAuthenticationExampleTest() throws Exception {
    	// Lock device by its UFT Mobile name.
    	Device device = MobileLab.lockDeviceByName("MyDevice");

    	// Describe the fingerprint authentication dialog AUT
    	Application fingerprintDialog = device.describe(Application.class, new ApplicationDescription.Builder()
    		.identifier("com.ll.fingerprintdialog").packaged(true).build());

    	// Launch or restart the app.
    	fingerprintDialog.launch();

    	// This sample AUT has a purchase button which will pop up an authentication dialog, describe
    	// this button in the application.
    	Button purchase = fingerprintDialog.describe(Button.class, new ButtonDescription.Builder()
    		.className("Button")
    		.mobileCenterIndex(0)
    		.nativeClass("android.widget.Button")
    		.resourceId("com.ll.fingerprintdialog:id/purchase_button")
    		.text("Purchase").build());

    	// Tap the button to change the text in an EditField to "You Tapped Me".
    	purchase.tap();

    	// Simulate a successful authentication
    	fingerprintDialog.simulateAuthentication().succeed();

    	// The above authentication simulation can also simulate a failure of the authentication. Each of the following ones can be used:
    	//
    	// Each of the next lines shows a simulation of authentication failure, with different reasons. For additional information please refer to the UFT Developer documentation
    	// fingerprintDialog.simulateAuthentication().fail(SimulateAuthFailReason.LOCKOUT);
    	// fingerprintDialog.simulateAuthentication().fail(SimulateAuthFailReason.NOT_RECOGNIZED);
    	// fingerprintDialog.simulateAuthentication().fail(SimulateAuthFailReason.NOT_REGISTERED);
    	// fingerprintDialog.simulateAuthentication().fail(SimulateAuthFailReason.FINGERPRINT_INCOMPLETE);
    	// fingerprintDialog.simulateAuthentication().fail(SimulateAuthFailReason.SENSOR_DIRTY);
    	// fingerprintDialog.simulateAuthentication().cancel(SimulateAuthCancelOrigin.USER);
    	// fingerprintDialog.simulateAuthentication().cancel(SimulateAuthCancelOrigin.SYSTEM);
    }

Back to top

## Simulate barcode or QR code authentication

This example shows how to simulate barcode or QR code authentication.

                    @Test
    public void mobileSimulateQRBarcodeScanExampleTest() throws Exception {
    	// Lock device by its UFT Mobile name.
    	Device device = MobileLab.lockDeviceByName("MyDevice");

    	// Describe the AUT
    	Application qrBarcodeApp = device.describe(Application.class, new ApplicationDescription.Builder()
    		.identifier("com.company.QRBarcodeSample").packaged(true).build());

    	// Upload the barcode or QR code image
    	String mediaId = "QRBarcodeImage1";
    	BufferedImage barcodeImage = null;
    	try {
    		barcodeImage = ImageIO.read(new File("QRBarcodeImage.jpg"));
    	} catch (IOException e) {
    		// Do some error handling here if the image load fails.
    	}
    	device.uploadMedia(barcodeImage, ImageFormat.JPG, mediaId);

    	// Launch or restart the app.
    	qrBarcodeApp.launch();

    	// Simulate the barcode scan
    	qrBarcodeApp.simulateBarcodeScan(mediaId);
    }

Back to top

## Service Virtualization integration

This example uses a Service Virtualization scenario to simulate a date change in a weather application.

    @Test

    // Lock a device and enable Service Virtualization for this session.
    public void test() throws GeneralLeanFtException, IOException {
    	Device device = MobileLab.lockDevice(new DeviceDescription.Builder().id("ZX1G22BL6L").build(), new DeviceSessionOptions().setDeviceSource(DeviceSource.MOBILE_CENTER).setEnableServiceVirtualization(true));
    	File serviceFile = new File( "C:\\AutomationSuite\\AllMethods\\sv\\svservicefile\\sv-lab-weather.json");

    	FileInputStream fis = new FileInputStream(serviceFile);
    	byte[] data = new byte[(int) serviceFile.length()];
    	fis.read(data);
    	fis.close();

    	String str = new String(data, "UTF-8");

    	// Upload the Service Virtualization service and scenario.
    	String serviceId = device.svUploadService(str);

    	String scenarioId = device.svUploadScenario(serviceId, "C:\\AutomationSuite\\AllMethods\\sv\\svscenariofiles");

    	Application forecastieApplication = device.describe(Application.class, new ApplicationDescription.Builder()
    		.identifier("com.casticalabs.forecastie")
    		.packaged(false).build());

    	forecastieApplication.install();
    	// at this point if you click the refresh icon in the AUT you should get an error
           //

    	device.svStartScenario(scenarioId);

    	//
           // at this point if you click the refresh icon in the AUT you should get some info from SV (date should be updated)
           //

    	device.svStopScenario(scenarioId);

    	//
           // at this point if you click the refresh icon in the AUT you should get an error again
           //
    }

Back to top

Tips to improve your search results... UFT Developer Java SDK Reference Version 15.0-15.0.2 UFT Developer SDK Reference All View Local Help Center View Online Help Center back Go back in browser history forward Go forward in browser history Remove search highlights next topic Go to next topic previous topic Go to previous topic Print the current topic Version: