Monday 5 August 2013

Appium android example program for windows using java - native app

To perform the automation using appium for the native android app just .apk file is enough. No need of developers code at all.

When we write the appium script for automation we need to specify the package name and activity name. We can get package and all activity names from the .apk file itself. For this we need to convert .apk file to java class files. See here to perform that.


I used following environments to accomplish this example program,


  • Windows7
  • Android SDK
  • JDK
  • Eclipse
  • TestNG

Install and start the appium server:


Appium server for windows platform is just a zip folder. It contains all the packages needed for appium such as node, webdriver etc. We no need to install any APIs additionally

  • Download the latest AppiumForWindows.zip from here
  • Unzip the AppiumForWindows.zip
  • Click on the appium.exe present in the unzipped appium folder. It will be opened up as below,


Appium Server For Windows

  • Now click on the 'Launch' button, It will start the server at 127.0.0.1:4723 as below,

Appium server is started

  • Then run the below program once the android emulator is ready.

Appium example program for android


package com.qa.test;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class androidExample {
WebDriver driver = null;
         
        @BeforeMethod
         public void setup() {
                File appDir = new File("E://AndroidApps");
File app = new File(appDir, "myApp.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "4.2.2");
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOWS");
                // Here we mention the app's package name, to find the package name we  have to convert .apk file into java class files
capabilities.setCapability("app-package","com.myApp.activity");
                //Here we mention the activity name, which is invoked initially as app's first page.
capabilities.setCapability("app-activity","LoginActivity");
//capabilities.setCapability("app-wait-activity","LoginActivity,NewAccountActivity");
capabilities.setCapability("app", app.getAbsolutePath());

driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);

         }

       @Test
public void loginTest() throws Exception {
driver.findElement(By.xpath("//EditText[@text='Email Address']")).sendKeys("tester@gmail.com");
driver.findElement(By.xpath("//LinearLayout/EditText[2]")).sendKeys("Testerpwd");
driver.findElement(By.xpath("//CheckBox")).click();
driver.findElement(By.xpath("//Button[@text='Login']")).click();

WebDriverWait wait = new WebDriverWait(driver,80);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//Button[@text='Logout']")));
driver.findElement(By.xpath("//Button[@text='Logout']")).click();

        }

       @AfterMethod
        public void tearDown() {
               driver.quit();
        }

}

Running this program will install the app in the emulator if it is not present already. If the app is installed already it will open and perform the automation steps.

If your app is already opened with some other activity(e.g. my profile page) appium will be waiting for the specified activity (com.myApp.activity.LoginActivity) when you run the automation script. In this case automation script will fail, since the app is opened with some other activity.

So it is better to start the appium server with an option full reset. Perform the following steps in appium GUI server,
  • Check the option 'Perform Full Reset'
  • Go to File > Preferences and check the option 'Reset Application State After Each Session'
When you use these options in the GUI server, you might also need to specify the app path, package and Activity name as below,

Start server with full reset

This will uninstall the app once your tests are completed and will install the app into emulator when the test starts initially.

Note:
  • Here I used the uiautomatorviewer to find the element hierarchy and then I constructed the xpath manually. To learn about constructing the xpath, please go here
  • You should set ANDROID_HOME and path for Android SDK in environment variable
  • Emulator adb device should have API level greater than or equal to 17


71 comments:

  1. Great post. Thank you

    ReplyDelete
  2. Can you do the same or iOS + java please? Thanks!

    ReplyDelete
    Replies
    1. Hi,

      You can find the appium iOS example here. http://automatium.blogspot.in/2013/05/sample-ios-script-using-appium-for.html.

      Thanks,
      Elang.

      Delete
    2. Thanks for sharing this Information, Got to learn new things from your Blog on appium.
      Ref link : http://thecreatingexperts.com/appium-training-in-chennai/

      Delete
    3. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about APPIUM.
      http://thecreatingexperts.com/appium-training-in-chennai/

      Delete
  3. Hi

    Thanks for such a nice info,,

    I am totally new in Appium, and I was following each and every step as mentioned in your blog for setting up on my windows machine , but when I am clicking on the Launch button , it shows the Cmd screen and disappear,,

    My second question is in your code you are using a file location for the apk file,, can you please also provide the .apk file so that I can easily run the above code,,,

    I mean to say how without a .apk file i run the above code and if there is any link regarding appium learning, will be thankful to you.. for sharing.

    ReplyDelete
    Replies
    1. Hi mintu,

      For the first question, am not sure. Download the latest AppiumForWindows.zip and try. Again if you have any issues install the node.js manually.

      For the second question, I can not give the APK file. Because it is confidential.

      And you need the APK file, which may or may not be installed in emulator. In test you have to give the path of APK file to be installed and you have to give the package and activity names to invoke that app.

      Thanks,
      Elango.

      Delete
    2. You can fine the sample appium-android code here https://github.com/appium/appium/tree/master/sample-code/examples/java/testng/src/test/java/com/saucelabs/appium

      There are some sample apps too I guess.

      Delete
    3. Thanks for the reply,,

      I am able to run the code on emulator and Phone. But I am not able to run the appium inspector, can you please post a blog on how to run the appium inspector and create the xpaths.

      Delete
    4. Hi, Appium inspector is not working in Windows I guess. By using UIAutomatorViewer you can see the all the element views. From that you have to construct the xpath manually. To learn about xpath construction look here http://automatium.blogspot.in/2013/05/construction-of-xpath-and-css-selectors.html.

      Delete
  4. Hi

    Can you please tell the type of project which we need to create in eclipse for Android example program?

    ReplyDelete
    Replies
    1. Just create a project as 'Java Project'.

      Delete
    2. Thanks Elangovan. Its working for me now.

      Delete
  5. hi..
    getting this error-Android Source Generator: [myapp] AndroidManifest.xml file not found

    ReplyDelete
  6. Hi, I followed the same steps as mentioned. While launching appium server and then running the project, i am getting an error telling that adb could not be launched and it could not be found on the path. But its found and also added the same in the environmental variable. Can you please suggest how to fix it?

    ReplyDelete
    Replies
    1. Is your Emulator's API Level greater than 17?

      Delete
  7. The API level is 17. Is that alright?

    ReplyDelete
  8. Does this program have a main method?

    ReplyDelete
  9. Hi Elangovan,

    I am trying to automate my sample android application using Appium for windows. I am facing two problems:

    1. In my app, I have username & password field and Login button. For invalid username/password scenario, I get popup/error dialog containing OK button on it to dismiss the popup but I am not able to click on OK button.

    driver.findElement(By.xpath("//LinearLayout/EditText[1]")).sendKeys("g@abc.com");
    driver.findElement(By.xpath("//LinearLayout/EditText[2]")).sendKeys("pass123");
    driver.findElement(By.xpath("//Button[@text='Log in']")).click();
    //To click on OK button on error dialog
    driver.findElement(By.xpath("//Button[@text='OK']")).click();

    Please suggest the solution for this issue.

    2. Appium is not detecting any elements after navigating from one screen(activity) to another screen and flashing back error.

    ReplyDelete
    Replies
    1. Hi,

      Any update on this? I am stucked at this part and not able to navigate from one screen to another. Please share some sample code for navigating from one screen to another.

      Thanks

      Delete
    2. What error message you are getting?. What is your action to navigate into another screen?. In appium, there is no any concepts like navigation to particular page or window AFAIK.

      Delete
    3. Hi Elangovan,

      I just tried your sample code in my test project and its working for me now.

      Thank you so much for your valuable support.

      Regards,
      Shashikant

      Delete
    4. Hi Elangovan,

      I have tried to click on Ok button using driver.swicthTo().alert(); command, but its still showing me Not implemented error to me. Please suggest me some solution so that I can handle alert popup as well.

      Regards,
      Shashikant

      Delete
    5. Shashikant,

      There is no need for switching at all. Without using the driver.swicthTo().alert() line just click on the OK button.

      Thanks,
      Elango.

      Delete
    6. I tried again without using switch and its absolutely working fine but earlier it was not working. Anyways many thanks once again.

      Shashikant

      Delete
  10. Hi Elangovan,
    This is the error that i am getting
    error: Failed to start an Appium session, err was: Error: Could not find adb in tools, platform-tools, or build-tools; do you have android SDK installed?
    Please tell me what the actual problem is?

    ReplyDelete
  11. Hi Elango,

    I am facing issues with scrolling. Please share some example code to scroll page.

    Thanks,
    Bharath L

    ReplyDelete
    Replies
    1. Hi Bharath,

      This is the code which I used to scroll to the bottom. point is (0,0)

      JavascriptExecutor js = (JavascriptExecutor)driver;
      HashMap flickObject = new HashMap();
      flickObject.put("endX", 0);
      flickObject.put("endY", 0);
      flickObject.put("touchCount", 1);
      js.executeScript("mobile: flick", flickObject);

      Thanks,
      Elango.

      Delete
    2. Many thanks Elango . The code works perfect .
      Kalakkitinga!!

      Thanks,
      Bharath L.

      Delete
  12. Hi Vii lakshmi,

    Three things you need to verify.
    1. Check you have configured the environmental variable is setuped.
    2. Copy all the files from tools folder to platform-tools folder
    3. Check with command prompt with following command and verify active devices are present adb devices

    Try above steps and provide your feedback

    ReplyDelete
  13. Hi Elangovan,
    Is it possible to tap he 'Done' key of Android keypad. I am struggling with it

    ReplyDelete
  14. Found this very helpful..Thanks..

    ReplyDelete
  15. Hi Elango,

    Is there any way to get support below Android API Level 17? I want to run same test suite for lower end Android devices.

    Regards,
    Shashikant

    ReplyDelete
  16. Hi Elangovan,

    1. Can u Suggest me which Android Emulator should I use and please also say the installation procedure.

    2. I am using Two Eclipse(one I am using for Selenium and the second one from Android SDK), Which is recommended for coding.?

    Regards,
    Abdul

    ReplyDelete
  17. Hi,
    I have tried with this example but I am unable to run the java program. I am getting the error as unable to start new appium session.
    Can you please suggest me why I am not able to run?

    Jaideep

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. How to run above Android appium program? When we try to create it as Java project, it fails to recognize the selenium libraries. What I need to do ? Do I need download all the libraries like Windriver, selenium or others and set the environment variable, then run it in eclipse? All other steps are fine and I can see the result as expected. Please suggest.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Hi Elangovan,

    I am new to appium and in the learning phase.

    I am running above program in java project.

    The log on the server is:

    info: Welcome to Appium v0.11.3 (REV 4a0cb4cc9e974d8d584ae98fef41eee0c067c081)
    info: Appium REST http interface listener started on 127.0.0.1:4723
    info - socket.io started
    debug: Appium request initiated at /wd/hub/session
    debug: Request received with params: {"desiredCapabilities":{"platform":"MAC","a
    pp":"C:\\Users\\saibandi.ORADEV\\workspace\\Test\\MyFirstApp\\bin\\MyFirstApp.ap
    k","browserName":"","app-package":"com.example.myfirstapp","device":"Android","a
    pp-activity":"MainActivity","version":"4.2"}}
    info: Using local app from desiredCaps: C:\Users\saibandi.ORADEV\workspace\Test\
    MyFirstApp\bin\MyFirstApp.apk
    info: Creating new appium session 7f6fa61d-fc32-4acd-bb83-e1d9fa754de6
    info: Starting android appium
    debug: Using fast reset? false
    info: Preparing device for session
    info: Checking whether app is actually present
    info: Checking whether adb is present


    afterwards its not showing anything.It just stopped there...
    What may be the problem..?

    Could you please help me to get out of this.

    ReplyDelete
    Replies
    1. Emulator adb device should have API level greater than or equal to 17. Did you check this?

      Delete
    2. Log is still same as above mentioned in appium but after eclipsed stopped I am getting below log :

      info: Welcome to Appium v0.12.0 (REV a9d21807874190ae6d19f8251375cfe4da7b2ae5)
      info: Appium REST http interface listener started on 127.0.0.1:4723
      info - socket.io started
      debug: Appium request initiated at /wd/hub/session
      debug: Request received with params: {"desiredCapabilities":{"platform":"WINDOWS
      ","app":"C:\\Android\\Gmail.apk","browserName":"","app-package":"com.myApp.activ
      ity","device":"Android","app-activity":"LoginActivity","version":"4.4"}}
      info: Using local app from desiredCaps: C:\Android\Gmail.apk
      info: Creating new appium session 4bc61719-5586-4a2a-830c-f4b223766189
      info: Starting android appium
      debug: Using fast reset? false
      info: Preparing device for session
      info: Checking whether app is actually present
      info: Checking whether adb is present
      POST /wd/hub/session 200 600005ms
      debug: Appium request initiated at /wd/hub/session
      debug: Request received with params: {"desiredCapabilities":{"platform":"WINDOWS
      ","app":"C:\\Android\\Gmail.apk","browserName":"","app-package":"com.myApp.activ
      ity","device":"Android","app-activity":"LoginActivity","version":"4.4"}}
      info: Using local app from desiredCaps: C:\Android\Gmail.apk
      error: Failed to start an Appium session, err was: Error: Requested a new sessio
      n but one was in progress
      info: Responding to client with error: {"status":33,"value":{"message":"A new se
      ssion could not be created. (Original error: Requested a new session but one was
      in progress)","origValue":"Requested a new session but one was in progress"},"s
      essionId":"4bc61719-5586-4a2a-830c-f4b223766189"}
      POST /wd/hub/session 500 23ms - 278b

      Delete
  22. Hi,
    I have android 4.4 API level 19
    I have downloaded gmail apk.
    Could you please help me out.or share me any docs so that I can proceed step by step or sample code.

    Please let me know what to put for app package and activity name.
    Do we need to convert .apk into java class files ?

    ReplyDelete
  23. Hi,

    I am trying the above as u mentioned but i was not able to run it, i am getting the error "Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure."

    ReplyDelete
  24. Hi..

    when the run the test in the appium console its showing as:

    checking whether adb is present

    after this its showing nothing.

    I have set the path and android home as well..and when i hit the command adb manually its showing the available devices.

    i am using API 19. tried different appium versions..none of them worked..

    pls help

    ReplyDelete
  25. Hi Elangovan,

    I have tried the steps u have told but still getting this "can't able to create new session"..
    Can u let me know wat i am missing....i have struggled many times by checking the name scenario..pls let me know the solution for this...

    I am stuck with running the script testing web App in Eclipse using Appium.I have been using "flipkart.apk" application for testing.

    Machine : Windows 7

    But i am getting the below error : 
    org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Command failed: can't install 'F:\Tools\Appium' because it's not a file
    ) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 38.70 seconds
    Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
    System info: host: 'sk-sys-114', ip: '192.168.2.45', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_51'

    Can u guys help me to figure out the way to run my first App test in Windows 7 using Appium... :(

    ReplyDelete
  26. Hi Elangovan,

    How can we start and launch the appium server with all arguments using Runtime exec("");

    ReplyDelete
  27. Hi Elangovan,

    Can you post sample code to select a option for a Select drop down (spinners) for a android naive app(I am using appium).

    Thanks

    ReplyDelete
  28. Hi everyone,

    I am new to Appium. I have followed all the steps mentioned Here. But I still dont Know that how to Link my Appium with Eclipse And run test on the Appium.

    Need your Help, Please Post steps,

    Thanks in advance.

    ReplyDelete
  29. Running your program in eclipse will automatically connect to the appium. The below code finds where the appium is running,

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

    ReplyDelete
  30. Hi

    I am new to appium. I am trying to automate web applicationb on android. Please let me know the jars which needs to be added apart from selenium.jar. any suggestion would be of great help.

    Thanks and regards
    M.karthik

    ReplyDelete
  31. Hi,

    In My Appium Android Setting page, Launch AVD is displaying empty drop down. i have already created 3 AVD manager.

    is there any help would apperciate.

    TR,
    Rajesh. S

    ReplyDelete
  32. I am also a greenhand of java,but now my work is to develop java program.Your content is very good and really help me solve some problems.Now i meet another question,i am generating barcode in java,can you give me some sample codes in java class?

    ReplyDelete
  33. hi, I am new to Appium, could any one help me out for the following scenario
    Open Settings app - Scroll to end of the list - And click "About phone" option

    Scrolled to "about phone" using scrollTo after that I need to click but unable to do that.. How can I achieve?

    ReplyDelete
  34. is it necessary to have a main method?As when i am clicking on run showing showing no recent launch is there.

    ReplyDelete
  35. hii Elangovan . can u please tell me. im new to appium. i have created android application , i need to generate report for the test done in appium, how we can generate it??? .
    After opening appium inspector if i click tap button it is showing Error"Error performing Tap action: A exception with null response was thrown sending an HTTP request to the remote webdriver server for URL " why is this showing error??????

    ReplyDelete
  36. Hi Elangovan,

    I tried the scroll down script, it is working fine. what are the values we need to change for scrollup?

    ReplyDelete
  37. How to find elements in Whatsapp. Is there any tools??Anybody help me to proceed Pls..

    ReplyDelete
  38. Hi Elangovan,

    I have been following ur blogs regularly. I have been facing issue in Appium.
    When i upload apk file, package and activity name is not detected and not able to run on eclipse.

    Please can you help me on thsis

    ReplyDelete
  39. APPIUM Training in Chennai
    We provide best APPIUM training in Chennai with real time Scenarios .Our training institute has the best trainer who has around 5+ years in core automation. Here the training is practical and real time based.If you want to learn the APPIUM you should have the basic knowledge in Coding.So don’t worry if you don’t have we will teach you from the basics.
    Contact us: 9677211551 , 9003085882
    Ref link : http://thecreatingexperts.com/appium-training-in-chennai/

    ReplyDelete
  40. Thanks for sharing this Information, Got to learn new things from your Blog on ANDROID .
    Ref link : http://thecreatingexperts.com/appium-training-in-chennai/

    ReplyDelete
  41. Hi @Elangovan first of all I want to say heartiest gratitude to you making things this simple. You saved my day, man.
    I want to make same program using JavaScript. Please advice the changes. Thanks in advance.

    ReplyDelete
  42. Can anyone help in writing the java script code for launcing the android application

    ReplyDelete
  43. Thanks for sharing this Information, Got to learn new things from your Blog on Appium.
    http://thecreatingexperts.com/appium-training-in-chennai/

    ReplyDelete
  44. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Texting API
    Text message marketing
    Digital Mobile Marketing
    Sms API
    Sms marketing

    ReplyDelete
  45. Really very informative and creative contents. This concept is a good way to enhance the knowledge.
    thanks for sharing. please keep it up.
    Appium Training in Gurgaon

    ReplyDelete
  46. Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes . Recently we tried SEO demo class of Apponix Technologies.
    https://www.apponix.com/seo/seo-training-institute-in-bangalore.html

    ReplyDelete
  47. Thanks for sharing such an informative post with us and for more further queries please do get in touch with our expert technician. contact MYOB Support .

    ReplyDelete
  48. I read your article .Good performece of your article. I am telling you a best institute of seo tranning i also go in this institute near gurgaon

    ReplyDelete