I'll teach you. _android Automation Practical Solution selection

Source: Internet
Author: User


Received a task of Android automation, looked at the hands of the guy: Ranorex,appium,uiautomator

Of course, the first to pick up the commercial trial, simple, you can record playback, but not with special expectations, this is more delicate, if the Android project has a third-party library may instrument failure. This time good luck, instrument success, recorded a bit of common operation, all OK. Think about what else to prepare:

First gesture: Search Help:

public void Swipe (

Location Startlocation,

Gesturedirection direction,

int distance,

Duration Swipeduration,

int steps

)


Well, copy and write a function out and keep the backup:

public void Myup2down (string arg UMENT1)

{

       int iparam1=convert.toint32 (argument1);

       for (int i=1;i<=iparam1;i++) {

     

      Report.Log (reportlevel.info, "Touch gestures", "Swipe gesture with direction ' up (270°) ' Starting from ' Center ' with distance ' + swipe duration ' 500ms ' and step count ' 0 ' on item ' Comwumiiandroidmimi.list View '. ', Repo.xxx.ListViewInfo, New Recorditemindex (1));

      repo.xxx.ListView.Swipe (Location.center, 4);

      delay.milliseconds ($);

      }

}

 

This comment has been said to be clear, is to slide from the bottom up, 270 degrees is upward, 180 degrees is the left, 0 degrees is the right, 90 degrees is below. 100 is the distance, 500 is the duration, and 4 is the step

 

Copy screen:

Pc:

Report.screenshot ();

Android Phone:

Report.screenshot (Reportlevel.info, "User", "", repo.xx.Self, false);

Report.screenshot (Reportlevel.info, "User", "", repo.xx.MyHomeActivity, false);

Are all objects in the Data Warehouse, very simple.

When you go down, you find a problem, Ranorex can not cross the application, and this test program to share to what, Sina Weibo category. Get it, change the knife.

With what, Appium is the most comprehensive, just him. It's always pleasant to start with:

Copy screen:

public static void Takescreenshot (Webdriver driver,string s1)

          { 

            File Screenshotfile = ((takesscreenshot) driver). Getscreenshotas (outputtype.file);  

             try {  

                Fileutils.copyfile (Screenshotfile, New File (S1)); 

               

             catch (IOException e) {e.printstacktrace ();}  

        }

public static String GetCurrentDateTime () {

SimpleDateFormat df = new SimpleDateFormat ("Hhmmss");//yyyymmddhhmmss

Return Df.format (New Date ());

}

Call Method:

Private Webdriver driver;

Takescreenshot (Driver, "/sdcard/" +getcurrentdatetime () + "main.png");

Violent Waiting:

public void Mysleep (int i1) {

try {

Thread.Sleep (I1);

} catch (Interruptedexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

Call: Wait for 5s:mysleep (5000);

Consider that if you can reference the control ID, it is much more straightforward and reliable. As if the real on-machine Hierarchyviewer.bat (D:\Android\android-sdk\tools) cannot catch the layout, with the simulator to try, remind now is the Monitor.bat era, directly open with Administrator privileges Monitor.bat ( Right-click the file, select Administrator rights to start). Start the simulator, and so on, finally got the layout file, is not a lot of things, nothing, just need to click on a few backbone nodes, you can see the corresponding elements of these nodes picture, it is easy to find it, can also be used to tune Yo, pay attention to see there is a three circle button, will show the load time of each view.

And then it was very tragic, it took a long time to try out how to quote ID:

Webelement el = driver.findelement (By.id ("Btnimsi")); Error

Webelement el = driver.findelement (By.id ("@+id/btnimsi")); Error

Webelement el = driver.findelement (By.id ("Id/btnimsi")); Error

Webelement el = driver.findelement (By.id ("1")); Error

Webelement el = driver.findelement (by.id ("Kanji One")); Error

Webelement el = driver.findelement (By.id ("Com.example.aimsi:id/btnimsi")); Ok

El.click ();

Would have been good, and constantly switching between the real machine and simulator, hierarchyviewer this broken thing and slow to die, In the middle to start Appium.exe, and to refer to the object and tagname, but also to list inside to find the first few, it is very annoying, wait for the strategy also did not search to let people cool a little. And that sendkey in this machine every time is the state of convulsions, hair a 123, he can output a 321, the navel can be gas crooked.

To change the knife again, Uiautomator but Google's own son, a start to get a dismount:

Copy screen: Dead or Alive No, finally understand, on both words: Version!

For >=android4.2

public void TakeScreenShotsGE42 (String s1) {

File Storepath = new file (S1);

Getuidevice (). Takescreenshot (Storepath);

}

private void Runshellcommand (String command) throws IOException, Interruptedexception {

Process p = null;

BufferedReader resultreader = null;

try {

p = runtime.getruntime (). exec (command);

int status = P.waitfor ();

if (Status! = 0) {

throw new RuntimeException (String.Format ("Run shell command:%s, Status:%s",

command, status));

}

} finally {

if (Resultreader! = null) {

Resultreader.close ();

}

if (P! = null) {

P.destroy ();

}

}

}

For <android4.2

public void TakeScreenShotsL42 (String s1) {

ADB Shell Screencap-p/data/local/tmp/screen-capture.png

ADB pull/data/local/tmp/screen-capture.png <localfile.png>

ADB Shell Rm/data/local/tmp/screen-capture.png

try {

Runshellcommand ("Screencap-p" +s1);

} catch (IOException e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Interruptedexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

See, what is called sin, the lower version of the need to call the bottom command line, the high version of the two sentences

The invocation methods are all the same:

Import Java.util.Date;

Import Java.text.SimpleDateFormat;

Public String getnowpng () {

SimpleDateFormat df = new SimpleDateFormat ("Mmddhhmmss"); YYYY-MM-DD HH:mm:ss

Return "/sdcard/" +df.format (New Date ()) + ". png";

}

TakeScreenShotsL42 (Getnowpng ());

TakeScreenShotsGE42 (Getnowpng ());

Finally got it, look at someone said can bypass that broken things hierarchyviewer, you can save the real-time layout in the running process, the heart of great cool, see, how simple it is, so two sentences:

public void Dump (String s1) {

Uidevice Uidevice = Getuidevice ();

Uidevice.dumpwindowhierarchy (S1);

}

The invocation is also simple: Dump ("D1.xml");

Write:/data/local/tmp directory, back to ADB pull/data/local/tmp/d1.xml drag it down just

The ideal black plump, the reality super backbone, execution no error, but is not generated, again from the real Machine (4.1.1) switch to the simulator (4.4.2), sure enough, the simulator on the execution of normal, probably is the version of the problem. Your sister's.

Try the ID reference again:

UiObject ac1=new UiObject (New Uiselector (). ResourceId ("Com.yy.android.sportbrush:id/menu"));

Wow, how nice, you can pinpoint! Big deal trouble, first in the simulator to get the layout of each interface file, and then want to manipulate the object can be directly quoted, super cool!

Don't dream about marrying a daughter-in-law all day long. This is also a high version of the line! That's crazy!

Well, so far, Uiautomator is basically enough, sorting ideas, you can do so, every time before starting to delete the files of the specified directory, back to each action to save the picture in. Object reference method also do not think ID, and do not support the Chinese, contentdescription more not expected, directly classname add index to it, there is no uncertainty. Object waiting is also a simple and uniform notation. Well, for one thing:

Remove a directory from the SD card first:

public void DeleteFile (String s1)

{

File file =new file (S1);

File files[] = File.listfiles ();

if (Files! = null) {

for (int i = 0; i < files.length; i++) {//traverse directory for all Files

Files[i].delete ();

}

}

}

Call Method: DeleteFile ("/sdcard/xxx/");

Object reference method, direct DDMS (look at a small icon: Dump View for Hierarchyviewer UI Automator), you don't even ddms how to open it? (Window-openperspective, if there is a DDMS directly open, do not choose other ..., this should always see it):

UiObject ac02_1 = new UiObject (new Uiselector (). ClassName (Android.widget.LinearLayout.class.getName ()). Index (0));

UiObject ac02_2 = ac02_1.getchild (new Uiselector (). ClassName (Android.widget.FrameLayout.class.getName ()). Index (0)) ;

UiObject ac02_3 = ac02_2.getchild (new Uiselector (). ClassName (Android.widget.ImageView.class.getName ()). Index (0));

You may be wondering why so many layers are quoted, the reason is that there are a lot of imageview on the current page, and index is 0, if you quote directly then there will be duplicate ImageView, unable to locate the only object, even if you add the previous layer of framelayout , index=0, is not necessarily the only. This kind of quoting method is very troublesome. But the only reliable, logical unity.

Shortcomings, written out of the code, I do not see it is the reference to what object.

Just at the end of the time, there is a small episode, sharing to QQ client, did not expect to open an old version of, incredibly is webview,tnnd,uiautomator can not deal with WebView, can not refer to the WebView inside the object, even if the absolute positioning, You cannot enter a user name or password by clicking on the control. In fact, this is not fair, Uiautomator can deal with WebView, but, estimated crossing has guessed, is your sister's high version can! Growl!

I can not go back to use Appium, lake Rumors, Appium in more than 4.1 use Uiautomator, 4.1 under the use of selendroid, and selendroid good at this stuff. I'll go.

To finalize the plan:

Most simple functions are used Ranorex, simple and practical is kingly;

Sharing part using Uiautomator, biological than appium or more simple.

WebView, what's wrong? Install a client on the line, not interested in taking the time to do so little function chew bones.

Students, watch and play.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.