package io.appium.android.bootstrap.handler;

import io.appium.android.bootstrap.AndroidCommand;
import io.appium.android.bootstrap.AndroidCommandResult;
import io.appium.android.bootstrap.CommandHandler;

import java.io.File;

import android.os.Environment;

import com.android.uiautomator.core.UiDevice;

/**
 * This handler is used to dumpWindowHierarchy.
 * https://android.googlesource.com/
 * platform/frameworks/testing/+/master/uiautomator
 * /library/core-src/com/android/uiautomator/core/UiDevice.java
 */
public class DumpWindowHierarchy extends CommandHandler {

  /*
   * @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) {

    final String dumpXml = "dump.xml";
    final File dump = new File(new File(Environment.getDataDirectory(),
        "local/tmp"), dumpXml);
    dump.mkdirs();

    if (dump.exists()) {
      dump.delete();
    }

    UiDevice.getInstance().dumpWindowHierarchy(dumpXml);
    return getSuccessResult(true);
  }
}
@@ -251,16 +251,47 @@
 ronment;
+%0Aimport android.os.SystemClock;
 %0A%0Aimport
@@ -597,16 +597,498 @@
 andler %7B
+%0A  // Note that%0A  // %22new File(new File(Environment.getDataDirectory(), %22local/tmp%22), fileName)%22%0A  // is directly from the UiDevice.java source code.%0A  private static final File   dumpFolder   = new File(%0A                                               Environment.getDataDirectory(),%0A                                               %22local/tmp%22);%0A  private static final String dumpFileName = %22dump.xml%22;%0A  private static final File   dumpFile     = new File(dumpFolder, dumpFileName);
 %0A%0A  /*%0A 
@@ -1446,168 +1446,154 @@
 ) %7B%0A
-%0A
     
-final String dumpXml = %22dump.xml%22;%0A    final File dump = new File(new File(Environment.getDataDirectory(),
+dumpFolder.mkdirs();%0A%0A    if (dumpFile.exists()) %7B%0A      dumpFile.delete();
 %0A    
+%7D%0A%0A
     
-%22local/tmp%22), dumpXml);%0A    dump.mkdirs(
+UiDevice.getInstance().dumpWindowHierarchy(dumpFileName
 );%0A%0A
@@ -1600,20 +1600,25 @@
     if (
+!
 dump
+File
 .exists(
@@ -1632,30 +1632,35 @@
     
-dump.delete();%0A    %7D%0A%0A
+SystemClock.sleep(1000);%0A  
     
@@ -1710,13 +1710,25 @@
 dump
-Xml);
+FileName);%0A    %7D%0A
 %0A   
@@ -1756,12 +1756,25 @@
 ult(
-true
+dumpFile.exists()
 );%0A 

Improve DumpWindowHierarchy.java