bootstrap之DumpWindowHierarchy

本文详细介绍了Appium中dumpWindowHierarchy方法的工作原理及其在自动化测试中的应用。该方法用于获取当前手机界面的所有控件信息,并将其以XML形式保存。适用于Android API 18以上版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DumpWindowHierarchy


package io.appium.android.bootstrap.handler;

import android.os.Environment;
import com.android.uiautomator.core.UiDevice;
import io.appium.android.bootstrap.AndroidCommand;
import io.appium.android.bootstrap.AndroidCommandResult;
import io.appium.android.bootstrap.CommandHandler;
import io.appium.android.bootstrap.utils.NotImportantViews;

import java.io.File;

/**
 * This handler is used to dumpWindowHierarchy.
 * https://android.googlesource.com/
 * platform/frameworks/testing/+/master/uiautomator
 * /library/core-src/com/android/uiautomator/core/UiDevice.java
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public class DumpWindowHierarchy extends CommandHandler {
  // Note that
  // "new File(new File(Environment.getDataDirectory(), "local/tmp"), fileName)"
  // is directly from the UiDevice.java source code.
  private static final File dumpFolder = new File(Environment.getDataDirectory(), "local/tmp");
  private static final String dumpFileName = "dump.xml";
  private static final File dumpFile = new File(dumpFolder, dumpFileName);

  private static void deleteDumpFile() {
    if (dumpFile.exists()) {
      dumpFile.delete();
    }
  }

  public static boolean dump() {
    dumpFolder.mkdirs();

    deleteDumpFile();

    try {
      // dumpWindowHierarchy often has a NullPointerException
      UiDevice.getInstance().dumpWindowHierarchy(dumpFileName);
    } catch (Exception e) {
      e.printStackTrace();
      // If there's an error then the dumpfile may exist and be empty.
      deleteDumpFile();
    }

    return dumpFile.exists();
  }

  /*
   * @param command The {@link AndroidCommand} used for this handler.
   *
   * @return {@link AndroidCommandResult}
   *
   * @throws JSONException
   *
   * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android.
   * bootstrap.AndroidCommand)
   */
  @Override
  public AndroidCommandResult execute(final AndroidCommand command) {
    NotImportantViews.discard(true);
    return getSuccessResult(dump());
  }
}

这种方法可能在某些机器上运行到不成功而让非常多人对这种方法不甚了解,而我做了非常长事件的功能遍历工具的开发,专门研究过这种方法,看看我之前写的文章就理解它是做什么的啦:


dumpWindowHierarchy


它是获取当前手机界面全部控件信息,然后把树形结构保存在/data/local/tmp的文件夹下的dump.xml文件里。所以我们看见上面类的定义有非常多关于路径、文件的字符串。就是这个原因。appium的这个DumpWindowHierarchy首先依据api的不同设置是否禁止布局压缩。假设api为18以上的。那么就启动布局压缩。这对我们获取实用的控件信息是非常有作用的。然后运行dump()方法,dump方法会先创建文件夹,当然该文件夹一般都会存在,无需创建。然后删除dump.xml文件,由于要创建新的,必须删除旧的。以免获取不到控件信息的时候,dump.xml里仍然有就信息返回。然后调用


UiDevice.getInstance().dumpWindowHierarchy(dumpFileName);

将控件树信息保存在里文件里。


(android最终,在官方网站上!)

版权声明:本文博主原创文章,博客,未经同意不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值