How to use this.adb.isAirplaneModeOn method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

android-common.js

Source:android-common.js Github

copy

Full Screen

...227    });228  }.bind(this));229};230androidCommon.toggleFlightMode = function (ocb) {231  this.adb.isAirplaneModeOn(function (err, airplaneModeOn) {232    if (err) return ocb(err);233    async.series([234      function (cb) {235        this.wrapActionAndHandleADBDisconnect(function (ncb) {236          this.adb.setAirplaneMode(airplaneModeOn ? 0 : 1, ncb);237        }.bind(this), cb);238      }.bind(this),239      function (cb) {240        this.wrapActionAndHandleADBDisconnect(function (ncb) {241          this.adb.broadcastAirplaneMode(airplaneModeOn ? 0 : 1, ncb);242        }.bind(this), cb);243      }.bind(this)244    ], function (err) {245      if (err) return ocb(err);246      ocb(null, {247        status: status.codes.Success.code248      });249    }.bind(this));250  }.bind(this));251};252androidCommon.toggleWiFi = function (cb) {253  this.adb.isWifiOn(function (err, dataOn) {254    if (err) return cb(err);255    this.wrapActionAndHandleADBDisconnect(function (ncb) {256      this.adb.setWifi(dataOn ? 0 : 1, ncb);257    }.bind(this), function (err) {258      if (err) return cb(err);259      cb(null, {260        status: status.codes.Success.code261      });262    });263  }.bind(this));264};265androidCommon.toggleLocationServices = function (ocb) {266  this.adb.getApiLevel(function (err, api) {267    if (api > 15) {268      var seq = [19, 19];   // up, up269      if (api === 16) {270        // This version of Android has a "parent" button in its action bar271        seq.push(20);       // down272      } else if (api >= 19) {273        // Newer versions of Android have the toggle in the Action bar274        seq = [22, 22, 19];     // right, right, up275        /*276         * Once the Location services switch is OFF, it won't receive focus277         * when going back to the Location Services settings screen unless we278         * send a dummy keyevent (UP) *before* opening the settings screen279         */280        this.adb.keyevent(19, function (/*err*/) {281          this.toggleSetting('LOCATION_SOURCE_SETTINGS', seq, ocb);282        }.bind(this));283        return;284      }285      this.toggleSetting('LOCATION_SOURCE_SETTINGS', seq, ocb);286    } else {287      // There's no global location services toggle on older Android versions288      ocb(new NotYetImplementedError(), null);289    }290  }.bind(this));291};292androidCommon.prepareDevice = function (onReady) {293  logger.debug("Using fast reset? " + this.args.fastReset);294  logger.debug("Preparing device for session");295  async.series([296    function (cb) { this.checkAppPresent(cb); }.bind(this),297    function (cb) { this.prepareEmulator(cb); }.bind(this),298    function (cb) { this.prepareActiveDevice(cb); }.bind(this),299    function (cb) { this.adb.waitForDevice(cb); }.bind(this),300    function (cb) { this.adb.startLogcat(cb); }.bind(this)301  ], onReady);302};303androidCommon.checkAppPresent = function (cb) {304  if (this.args.app === null) {305    logger.debug("Not checking whether app is present since we are assuming " +306                "it's already on the device");307    cb();308  } else {309    logger.debug("Checking whether app is actually present");310    fs.stat(this.args.app, function (err) {311      if (err) {312        logger.error("Could not find app apk at " + this.args.app);313        cb(err);314      } else {315        cb();316      }317    }.bind(this));318  }319};320androidCommon.prepareEmulator = function (cb) {321  if (this.args.avd !== null) {322    var avdName = this.args.avd.replace('@', '');323    this.adb.getRunningAVD(avdName, function (err, runningAVD) {324      if (err && err.message.indexOf('No devices') === -1 &&325          err.message.indexOf('No emulators') === -1) return cb(err);326      if (runningAVD !== null) {327        logger.debug("Did not launch AVD because it was already running.");328        return this.ensureDeviceLocale(cb);329      }330      this.adb.launchAVD(this.args.avd, this.args.avdArgs, this.args.language, this.args.locale,331        this.args.avdLaunchTimeout, this.args.avdReadyTimeout, cb);332    }.bind(this));333  } else {334    this.ensureDeviceLocale(cb);335  }336};337androidCommon.ensureDeviceLocale = function (cb) {338  var haveLanguage = this.args.language && typeof this.args.language === "string";339  var haveCountry = this.args.locale && typeof this.args.locale === "string";340  if (!haveLanguage && !haveCountry) return cb();341  this.getDeviceLanguage(function (err, language) {342    if (err) return cb(err);343    this.getDeviceCountry(function (err, country) {344      if (err) return cb(err);345      var adbCmd = "";346      if (haveLanguage && this.args.language !== language) {347        logger.debug("Setting Android Device Language to " + this.args.language);348        adbCmd += "setprop persist.sys.language " + this.args.language.toLowerCase() + ";";349      }350      if (haveCountry && this.args.locale !== country) {351        logger.debug("Setting Android Device Country to " + this.args.locale);352        adbCmd += "setprop persist.sys.country " + this.args.locale.toUpperCase() + ";";353      }354      if (adbCmd === "") return cb();355      this.adb.shell(adbCmd, function (err) {356        if (err) return cb(err);357        this.adb.reboot(cb);358      }.bind(this));359    }.bind(this));360  }.bind(this));361};362androidCommon.prepareActiveDevice = function (cb) {363  if (this.adb.curDeviceId) {364    // deviceId is already setted365    return cb();366  }367  logger.info('Retrieving device');368  this.adb.getDevicesWithRetry(function (err, devices) {369    if (err) return cb(err);370    var deviceId = null;371    if (this.adb.udid) {372      if (!_.contains(_.pluck(devices, 'udid'), this.adb.udid)) {373        return cb(new Error("Device " + this.adb.udid + " was not in the list " +374                            "of connected devices"));375      }376      deviceId = this.adb.udid;377    } else {378      deviceId = devices[0].udid;379      var emPort = this.adb.getPortFromEmulatorString(deviceId);380      this.adb.setEmulatorPort(emPort);381    }382    logger.info('Found device', deviceId);383    this.adb.setDeviceId(deviceId);384    cb();385  }.bind(this));386};387androidCommon.resetApp = function (cb) {388  if (this.args.fastReset) {389    logger.debug("Running fast reset (stop and clear)");390    this.adb.stopAndClear(this.args.appPackage, cb);391  } else {392    logger.debug("Running old fashion reset (reinstall)");393    this.remoteApkExists(function (err, remoteApk) {394      if (err) return cb(err);395      if (!remoteApk) {396        return cb(new Error("Can't run reset if remote apk doesn't exist"));397      }398      this.adb.uninstallApk(this.args.appPackage, function (err) {399        if (err) return cb(err);400        this.adb.installRemote(remoteApk, cb);401      }.bind(this));402    }.bind(this));403  }404};405androidCommon.getRemoteApk = function (cb) {406  var next = function () {407    cb(null, this.remoteTempPath() + this.appMd5Hash + '.apk', this.appMd5Hash);408  }.bind(this);409  if (this.appMd5Hash) {410    next();411  } else {412    this.getAppMd5(function (err, md5Hash) {413      if (err) return cb(err);414      this.appMd5Hash = md5Hash;415      next();416    }.bind(this));417  }418};419androidCommon.remoteApkExists = function (cb) {420  this.getRemoteApk(function (err, remoteApk) {421    if (err) return cb(err);422    this.adb.shell("ls " + remoteApk, function (err, stdout) {423      if (err) return cb(err);424      if (stdout.indexOf("No such file") !== -1) {425        return cb(new Error("remote apk did not exist"));426      }427      cb(null, stdout.trim());428    });429  }.bind(this));430};431androidCommon.uninstallApp = function (cb) {432  var next = function () {433    this.adb.uninstallApk(this.args.appPackage, function (err) {434      if (err) return cb(err);435      cb(null);436    }.bind(this));437  }.bind(this);438  if (this.args.skipUninstall) {439    logger.debug("Not uninstalling app since server not started with " +440      "--full-reset");441    cb();442  } else {443    next();444  }445};446androidCommon.installAppForTest = function (cb) {447  if (this.args.app === null) {448    logger.debug("Skipping install since we launched with a package instead " +449                "of an app path");450    return cb();451  }452  var afterSigning = function (err) {453    if (err) return cb(err);454    this.remoteApkExists(function (err, remoteApk) {455      // err is set if the remote apk doesn't exist so don't check it.456      this.adb.isAppInstalled(this.args.appPackage, function (err, installed) {457        if (installed && this.args.fastReset && remoteApk) {458          logger.info('App is already installed, resetting app');459          this.resetApp(cb);460        } else if (!installed || (this.args.fastReset && !remoteApk)) {461          logger.info('Installing App');462          this.adb.mkdir(this.remoteTempPath(), function (err) {463            if (err) return cb(err);464            this.getRemoteApk(function (err, remoteApk, md5Hash) {465              if (err) return cb(err);466              this.removeTempApks([md5Hash], function (err, appExists) {467                if (err) return cb(err);468                var install = function (err) {469                  if (err) return cb(err);470                  this.installRemoteWithRetry(remoteApk, cb);471                }.bind(this);472                if (appExists) {473                  install();474                } else {475                  this.adb.push(this.args.app, remoteApk, install);476                }477              }.bind(this));478            }.bind(this));479          }.bind(this));480        } else {481          cb();482        }483      }.bind(this));484    }.bind(this));485  }.bind(this);486  // Skipping sign apk for noSign true487  if (this.args.noSign) {488    logger.debug('noSign capability set to true, skipping checking and signing of app');489    afterSigning();490  } else {491    this.adb.checkAndSignApk(this.args.app, this.args.appPackage, afterSigning);492  }493};494androidCommon.installRemoteWithRetry = function (remoteApk, cb) {495  this.adb.uninstallApk(this.args.appPackage, function (err) {496    if (err) logger.warn("Uninstalling apk failed, continuing");497    this.adb.installRemote(remoteApk, function (err) {498      if (err) {499        logger.warn("Installing remote apk failed, going to uninstall and try " +500                    "again");501        this.removeTempApks([], function () {502          this.adb.push(this.args.app, remoteApk, function (err) {503            if (err) return cb(err);504            logger.debug("Attempting to install again for the last time");505            this.adb.installRemote(remoteApk, cb);506          }.bind(this));507        }.bind(this));508      } else {509        cb();510      }511    }.bind(this));512  }.bind(this));513};514androidCommon.getAppMd5 = function (cb) {515  try {516    md5(this.args.app, function (err, md5Hash) {517      if (err) return cb(err);518      logger.debug("MD5 for app is " + md5Hash);519      cb(null, md5Hash);520    }.bind(this));521  } catch (e) {522    logger.error("Problem calculating md5: " + e);523    return cb(e);524  }525};526androidCommon.remoteTempPath = function () {527  return "/data/local/tmp/";528};529androidCommon.removeTempApks = function (exceptMd5s, cb) {530  logger.debug("Removing any old apks");531  if (typeof exceptMd5s === "function") {532    cb = exceptMd5s;533    exceptMd5s = [];534  }535  var listApks = function (cb) {536    var cmd = 'ls /data/local/tmp/*.apk';537    this.adb.shell(cmd, function (err, stdout) {538      if (err || stdout.indexOf("No such file") !== -1) {539        return cb(null, []);540      }541      var apks = stdout.split("\n");542      cb(null, apks);543    });544  }.bind(this);545  var removeApks = function (apks, cb) {546    if (apks.length < 1) {547      logger.debug("No apks to examine");548      return cb();549    }550    var matchingApkFound = false;551    var noMd5Matched = true;552    var removes = [];553    _.each(apks, function (path) {554      path = path.trim();555      if (path !== "") {556        noMd5Matched = true;557        _.each(exceptMd5s, function (md5Hash) {558          if (path.indexOf(md5Hash) !== -1) {559            noMd5Matched = false;560          }561        });562        if (noMd5Matched) {563          removes.push('rm "' + path + '"');564        } else {565          logger.debug("Found an apk we want to keep at " + path);566          matchingApkFound = true;567        }568      }569    });570    // Invoking adb shell with an empty string will open a shell console571    // so return here if there's nothing to remove.572    if (removes.length < 1) {573      logger.debug("Couldn't find any apks to remove");574      return cb(null, matchingApkFound);575    }576    var cmd = removes.join(" && ");577    this.adb.shell(cmd, function () {578      cb(null, matchingApkFound);579    });580  }.bind(this);581  async.waterfall([582    function (cb) { listApks(cb); },583    function (apks, cb) { removeApks(apks, cb); }584  ], function (err, matchingApkFound) { cb(null, matchingApkFound); });585};586androidCommon.forwardPort = function (cb) {587  this.adb.forwardPort(this.args.systemPort, this.args.devicePort, cb);588};589androidCommon.pushUnicodeIME = function (cb) {590  /* logger.debug("Pushing unicode ime to device...");591  var imePath = path.resolve(__dirname, "..", "..", "..", "build",592      "unicode_ime_apk", "UnicodeIME-debug.apk");593  fs.stat(imePath, function (err) {594    if (err) {595      cb(new Error("Could not find Unicode IME apk; please run " +596                   "'reset.sh --android' to build it."));597    } else {598      this.adb.install(imePath, false, cb);599    }600  }.bind(this)); */601};602androidCommon.pushSettingsApp = function (cb) {603  logger.debug("Pushing settings apk to device...");604  var settingsPath = path.resolve(__dirname, "..", "..", "..", "build",605      "settings_apk", "settings_apk-debug.apk");606  fs.stat(settingsPath, function (err) {607    if (err) {608      cb(new Error("Could not find settings apk; please run " +609                   "'reset.sh --android' to build it."));610    } else {611      this.adb.install(settingsPath, false, cb);612    }613  }.bind(this));614};615androidCommon.packageAndLaunchActivityFromManifest = function (cb) {616  if (!this.args.app) {617    logger.warn("No app capability, can't parse package/activity");618    return cb();619  }620  if (this.args.appPackage && this.args.appActivity) return cb();621  logger.debug("Parsing package and activity from app manifest");622  this.adb.packageAndLaunchActivityFromManifest(this.args.app, function (err, pkg, act) {623    if (err) {624      logger.error("Problem parsing package and activity from manifest: " +625                   err);626      return cb(err);627    }628    if (pkg && !this.args.appPackage) this.args.appPackage = pkg;629    if (!this.args.appWaitPackage) this.args.appWaitPackage = this.args.appPackage;630    // Retrying to parse activity from AndroidManifest.xml631    if (act === null) {632      var appiumApkToolsJarPath = this.adb.jars['appium_apk_tools.jar'];633      var outputPath = path.resolve(this.args.tmpDir, pkg);634      var getLaunchActivity = ['java -jar "', appiumApkToolsJarPath,635                                '" "', 'printLaunchActivity',636                                '" "', this.args.app, '" "', outputPath, '"'].join('');637      exec(getLaunchActivity, { maxBuffer: 524288 }, function (err, stdout, stderr) {638        if (err || stderr) {639          logger.warn(stderr);640          return cb(new Error("Cannot parse launchActivity from manifest." + err));641        }642        var apkActivity = new RegExp(/Launch activity parsed:([^']+)/g).exec(stdout);643        if (apkActivity && apkActivity.length >= 2) {644          act = apkActivity[1];645        } else {646          act = null;647        }648        if (act && !this.args.appActivity) this.args.appActivity = act;649        if (!this.args.appWaitActivity) this.args.appWaitActivity = this.args.appActivity;650        logger.debug("Parsed package and activity are: " + pkg + "/" + act);651        cb();652      }.bind(this));653    }654    else {655       if (act && !this.args.appActivity) this.args.appActivity = act;656       if (!this.args.appWaitActivity) this.args.appWaitActivity = this.args.appActivity;657       logger.debug("Parsed package and activity are: " + pkg + "/" + act);658       cb();659    }660   }.bind(this));661};662androidCommon.getLog = function (logType, cb) {663  // Check if passed logType is supported664  if (!_.has(logTypesSupported, logType)) {665    return cb(null, {666      status: status.codes.UnknownError.code667    , value: "Unsupported log type '" + logType + "', supported types : " + JSON.stringify(logTypesSupported)668    });669  }670  var logs;671  // Check that current logType and instance is compatible672  if (logType === 'logcat') {673    try {674      logs = this.adb.getLogcatLogs();675    } catch (e) {676      return cb(e);677    }678  }679  // If logs captured sucessfully send response with data, else send error680  if (logs) {681    return cb(null, {682      status: status.codes.Success.code683    , value: logs684    });685  } else {686    return cb(null, {687      status: status.codes.UnknownError.code688    , value: "Incompatible logType for this device"689    });690  }691};692androidCommon.getLogTypes = function (cb) {693  return cb(null, {694    status: status.codes.Success.code695  , value: _.keys(logTypesSupported)696  });697};698androidCommon.getCurrentActivity = function (cb) {699  this.adb.getFocusedPackageAndActivity(function (err, curPackage, activity) {700    if (err) {701      return cb(null, {702        status: status.codes.UnknownError.code703      , value: err.message704      });705    }706    cb(null, {707      status: status.codes.Success.code708    , value: activity709    });710  });711};712androidCommon.getDeviceProperty = function (property, cb) {713  this.adb.shell("getprop " + property, function (err, stdout) {714    if (err) {715      logger.error("Error getting device property " + property + ": " + err);716      cb(err, null);717    } else {718      logger.debug("Current device " + property + ": " + stdout.trim());719      cb(null, stdout.trim());720    }721  }.bind(this));722};723androidCommon.getDeviceLanguage = function (cb) {724  this.getDeviceProperty("persist.sys.language", cb);725};726androidCommon.getDeviceCountry = function (cb) {727  this.getDeviceProperty("persist.sys.country", cb);728};729androidCommon.extractLocalizedStrings = function (language, outputPath, cb) {730  var appiumApkToolsJarPath = this.adb.jars['appium_apk_tools.jar'];731  if (!this.args.appPackage) {732    return cb(new Error("Parameter 'appPackage' is required for launching application"));733  }734  var makeStrings = ['java -jar "', appiumApkToolsJarPath, '" "', 'stringsFromApk',735                     '" "', this.args.app, '" "', outputPath, '"'].join('');736  if (language) {737    this.extractStringsFromApk(makeStrings, language, cb);738  } else {739    // If language is not set, use device language740    this.getDeviceLanguage(function (err, language) {741      this.extractStringsFromApk(makeStrings, language, cb);742    }.bind(this));743  }744};745androidCommon.extractStringsFromApk = function (makeStrings, language, cb) {746  var makeLanguageStrings = makeStrings;747  if (language !== null) makeLanguageStrings = [makeStrings, language].join(' ');748  logger.debug(makeLanguageStrings);749  exec(makeLanguageStrings, { maxBuffer: 524288 }, function (err, stdout, stderr) {750    if (err && language !== null) {751      logger.debug("No strings.xml for language '" + language + "', getting default strings.xml");752      this.extractStringsFromApk(makeStrings, null, cb);753    } else {754      cb(err, stdout, stderr);755    }756  }.bind(this));757};758androidCommon.extractStrings = function (cb, language) {759  logger.debug("Extracting strings for language: " + (language || "default"));760  var outputPath = path.resolve(this.args.tmpDir, this.args.appPackage);761  var stringsJson = 'strings.json';762  if (!fs.existsSync(this.args.app)) {763    logger.debug("Apk doesn't exist locally");764    this.apkStrings = {};765    this.language = null;766    return cb(new Error("Apk doesn't exist locally"));767  } else {768    this.extractLocalizedStrings(language, outputPath, function (err, stdout, stderr) {769      if (err) {770        logger.warn("Error getting strings.xml from apk");771        logger.debug(stderr);772        this.apkStrings = {};773        this.language = null;774        return cb(err);775      }776      var file;777      try {778        logger.debug("Reading strings from converted strings.json");779        file = fs.readFileSync(path.join(outputPath, stringsJson)).toString('utf8');780        this.apkStrings = JSON.parse(file);781      } catch (e) {782        var msg = "Could not parse strings from strings.json. Original " +783                  "error: " + e.message;784        logger.debug(msg);785        if (file) {786          logger.debug("Content started with: " + file.slice(0, 300));787        }788        return cb(new Error(msg));789      }790      logger.debug("Setting language to " + (language || "default"));791      this.language = language;792      cb();793    }.bind(this));794  }795};796androidCommon.initUnicode = function (cb) {797  if (this.args.unicodeKeyboard) {798    logger.debug('Enabling Unicode keyboard support');799    this.pushUnicodeIME(function (err) {800      if (err) return cb(err);801      this.adb.defaultIME(function (err, engine) {802        if (err) return cb(err);803        // save the previously set IME804        this.defaultIME = engine;805        logger.debug('Unsetting IME \'' + this.defaultIME + '\'');806        logger.debug('Setting IME to \'io.appium.android.ime/.UnicodeIME\'');807        this.adb.enableIME('io.appium.android.ime/.UnicodeIME', function (err) {808          if (err) return cb(err);809          this.adb.setIME('io.appium.android.ime/.UnicodeIME', cb);810        }.bind(this));811      }.bind(this));812    }.bind(this));813  } else {814    cb();815  }816};817androidCommon.getNetworkConnection = function (cb) {818  logger.info('Getting network connection');819  this.adb.isAirplaneModeOn(function (err, airplaneModeOn) {820    if (err) return cb(err);821    var connection = airplaneModeOn ? 1 : 0;822    if (airplaneModeOn) {823      // airplane mode on implies wifi and data off824      return cb(null, {825        status: status.codes.Success.code,826        value: connection827      });828    }829    this.adb.isWifiOn(function (err, wifiOn) {830      if (err) return cb(err);831      connection += (wifiOn ? 2 : 0);832      this.adb.isDataOn(function (err, dataOn) {833        if (err) return cb(err);...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

...13// The value must not be greater than DBL_EPSILON (https://opensource.apple.com/source/Libc/Libc-498/include/float.h)14const GEO_EPSILON = Number.MIN_VALUE;15commands.getNetworkConnection = async function getNetworkConnection () {16  log.info('Getting network connection');17  let airplaneModeOn = await this.adb.isAirplaneModeOn();18  let connection = airplaneModeOn ? AIRPLANE_MODE_MASK : 0;19  // no need to check anything else if we are in airplane mode20  if (!airplaneModeOn) {21    let wifiOn = await this.isWifiOn();22    connection |= (wifiOn ? WIFI_MASK : 0);23    let dataOn = await this.adb.isDataOn();24    connection |= (dataOn ? DATA_MASK : 0);25  }26  return connection;27};28/**29 * decoupling to override the behaviour in other drivers like UiAutomator2.30 */31commands.isWifiOn = async function isWifiOn () {32  return await this.adb.isWifiOn();33};34commands.setNetworkConnection = async function setNetworkConnection (type) {35  log.info('Setting network connection');36  // decode the input37  const shouldEnableAirplaneMode = (type & AIRPLANE_MODE_MASK) !== 0;38  const shouldEnableWifi = (type & WIFI_MASK) !== 0;39  const shouldEnableDataConnection = (type & DATA_MASK) !== 0;40  const currentState = await this.getNetworkConnection();41  const isAirplaneModeEnabled = (currentState & AIRPLANE_MODE_MASK) !== 0;42  const isWiFiEnabled = (currentState & WIFI_MASK) !== 0;43  const isDataEnabled = (currentState & DATA_MASK) !== 0;44  if (shouldEnableAirplaneMode !== isAirplaneModeEnabled) {45    await this.wrapBootstrapDisconnect(async () => {46      await this.adb.setAirplaneMode(shouldEnableAirplaneMode);47    });48    await this.wrapBootstrapDisconnect(async () => {49      await this.adb.broadcastAirplaneMode(shouldEnableAirplaneMode);50    });51  } else {52    log.info(`Not changing airplane mode, since it is already ` +53             `${shouldEnableAirplaneMode ? 'enabled' : 'disabled'}`);54  }55  if (shouldEnableWifi === isWiFiEnabled && shouldEnableDataConnection === isDataEnabled) {56    log.info('Not changing data connection/Wi-Fi states, since they are already set to expected values');57    if (await this.adb.isAirplaneModeOn()) {58      return AIRPLANE_MODE_MASK | currentState;59    }60    return ~AIRPLANE_MODE_MASK & currentState;61  }62  await this.wrapBootstrapDisconnect(async () => {63    if (shouldEnableWifi !== isWiFiEnabled) {64      await this.setWifiState(shouldEnableWifi);65    } else {66      log.info(`Not changing Wi-Fi state, since it is already ` +67               `${shouldEnableWifi ? 'enabled' : 'disabled'}`);68    }69    if (shouldEnableAirplaneMode) {70      log.info('Not changing data connection state, because airplane mode is enabled');71    } else if (shouldEnableDataConnection === isDataEnabled) {72      log.info(`Not changing data connection state, since it is already ` +73               `${shouldEnableDataConnection ? 'enabled' : 'disabled'}`);74    } else {75      await this.adb.setDataState(shouldEnableDataConnection, this.isEmulator());76    }77  });78  return await this.getNetworkConnection();79};80/**81 * decoupling to override behaviour in other drivers like UiAutomator2.82 */83commands.setWifiState = async function setWifiState (wifi) {84  await this.adb.setWifiState(wifi, this.isEmulator());85};86commands.toggleData = async function toggleData () {87  let data = !(await this.adb.isDataOn());88  log.info(`Turning network data ${data ? 'on' : 'off'}`);89  await this.wrapBootstrapDisconnect(async () => {90    await this.adb.setWifiAndData({data}, this.isEmulator());91  });92};93commands.toggleWiFi = async function toggleWiFi () {94  let wifi = !(await this.adb.isWifiOn());95  log.info(`Turning WiFi ${wifi ? 'on' : 'off'}`);96  await this.wrapBootstrapDisconnect(async () => {97    await this.adb.setWifiAndData({wifi}, this.isEmulator());98  });99};100commands.toggleFlightMode = async function toggleFlightMode () {101  /*102   * TODO: Implement isRealDevice(). This method fails on103   * real devices, it should throw a NotYetImplementedError104   */105  let flightMode = !(await this.adb.isAirplaneModeOn());106  log.info(`Turning flight mode ${flightMode ? 'on' : 'off'}`);107  await this.wrapBootstrapDisconnect(async () => {108    await this.adb.setAirplaneMode(flightMode);109  });110  await this.wrapBootstrapDisconnect(async () => {111    await this.adb.broadcastAirplaneMode(flightMode);112  });113};114commands.setGeoLocation = async function setGeoLocation (location) {115  await this.adb.setGeoLocation(location, this.isEmulator());116  try {117    return await this.getGeoLocation();118  } catch (e) {119    log.warn(`Could not get the current geolocation info: ${e.message}`);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var driver = new webdriver.Builder()4    .forBrowser('chrome')5    .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.isAirplaneModeOn().then(function(isOn) {11    console.log('Airplane mode is on? ' + isOn);12});13driver.setAirplaneMode(true).then(function() {14    console.log('Airplane mode is now on');15});16driver.isAirplaneModeOn().then(function(isOn) {17    console.log('Airplane mode is on? ' + isOn);18});19driver.setAirplaneMode(false).then(function() {20    console.log('Airplane mode is now off');21});22driver.isAirplaneModeOn().then(function(isOn) {23    console.log('Airplane mode is on? ' + isOn);24});25driver.setAirplaneMode(true).then(function() {26    console.log('Airplane mode is now on');27});28driver.isAirplaneModeOn().then(function(isOn) {29    console.log('Airplane mode is on? ' + isOn);30});31driver.setAirplaneMode(false).then(function() {32    console.log('Airplane mode is now off');33});34driver.isAirplaneModeOn().then(function(isOn) {35    console.log('Airplane mode is on? ' + isOn);36});

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumAndroidDriver = require('appium-android-driver');2var AppiumAndroidDriver = new AppiumAndroidDriver();3AppiumAndroidDriver.adb.isAirplaneModeOn();4var AppiumAndroidDriver = require('appium-android-driver');5var AppiumAndroidDriver = new AppiumAndroidDriver();6AppiumAndroidDriver.adb.isAirplaneModeOn();7var AppiumAndroidDriver = require('appium-android-driver');8var AppiumAndroidDriver = new AppiumAndroidDriver();9AppiumAndroidDriver.adb.isAirplaneModeOn();10var AppiumAndroidDriver = require('appium-android-driver');11var AppiumAndroidDriver = new AppiumAndroidDriver();12AppiumAndroidDriver.adb.isAirplaneModeOn();13var AppiumAndroidDriver = require('appium-android-driver');14var AppiumAndroidDriver = new AppiumAndroidDriver();15AppiumAndroidDriver.adb.isAirplaneModeOn();16var AppiumAndroidDriver = require('appium-android-driver');17var AppiumAndroidDriver = new AppiumAndroidDriver();18AppiumAndroidDriver.adb.isAirplaneModeOn();19var AppiumAndroidDriver = require('appium-android-driver');20var AppiumAndroidDriver = new AppiumAndroidDriver();21AppiumAndroidDriver.adb.isAirplaneModeOn();22var AppiumAndroidDriver = require('appium-android-driver');23var AppiumAndroidDriver = new AppiumAndroidDriver();24AppiumAndroidDriver.adb.isAirplaneModeOn();25var AppiumAndroidDriver = require('appium-android-driver');26var AppiumAndroidDriver = new AppiumAndroidDriver();27AppiumAndroidDriver.adb.isAirplaneModeOn();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var AppiumDriver = require('appium-android-driver');3var driver = new AppiumDriver();4var ADB = require('appium-adb');5var adb = new ADB();6driver.adb = adb;7driver.adb.isAirplaneModeOn().then(function(isOn) {8    console.log("Airplane mode is on: " + isOn);9});10var webdriver = require('selenium-webdriver');11var AppiumDriver = require('appium-android-driver');12var driver = new AppiumDriver();13var ADB = require('appium-adb');14var adb = new ADB();15driver.adb = adb;16driver.adb.getApiLevel().then(function(apiLevel) {17    console.log("API level: " + apiLevel);18});19var webdriver = require('selenium-webdriver');20var AppiumDriver = require('appium-android-driver');21var driver = new AppiumDriver();22var ADB = require('appium-adb');23var adb = new ADB();24driver.adb = adb;25driver.adb.getConnectedEmulators().then(function(emulators) {26    console.log("Connected emulators: " + emulators);27});28var webdriver = require('selenium-webdriver');29var AppiumDriver = require('appium-android-driver');30var driver = new AppiumDriver();31var ADB = require('appium-adb');32var adb = new ADB();33driver.adb = adb;34driver.adb.getConnectedDevices().then(function(devices)

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var AndroidDriver = require('appium-android-driver');3var driver = new AndroidDriver();4driver.adb.isAirplaneModeOn().then(function(isOn) {5  console.log('Airplane mode is ' + (isOn ? 'on' : 'off'));6});7var webdriver = require('selenium-webdriver');8var AndroidDriver = require('appium-android-driver');9var driver = new AndroidDriver();10driver.adb.setAirplaneMode(true).then(function() {11  console.log('Airplane mode is on');12});13var webdriver = require('selenium-webdriver');14var AndroidDriver = require('appium-android-driver');15var driver = new AndroidDriver();16driver.adb.isDataOn().then(function(isOn) {17  console.log('Data is ' + (isOn ? 'on' : 'off'));18});19var webdriver = require('selenium-webdriver');20var AndroidDriver = require('appium-android-driver');21var driver = new AndroidDriver();22driver.adb.setData(true).then(function() {23  console.log('Data is on');24});25var webdriver = require('selenium-webdriver');26var AndroidDriver = require('appium-android-driver');27var driver = new AndroidDriver();28driver.adb.isWifiOn().then(function(isOn) {29  console.log('Wifi is ' + (isOn ? 'on' : 'off'));30});31var webdriver = require('selenium-webdriver');32var AndroidDriver = require('appium-android-driver');33var driver = new AndroidDriver();34driver.adb.setWifi(true).then(function() {35  console.log('Wifi is on');36});37var webdriver = require('selenium-webdriver');38var AndroidDriver = require('appium-android-driver');39var driver = new AndroidDriver();

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var wd = require('wd');3var desired = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6  .init(desired)7  .then(function () {8    return driver.adb.isAirplaneModeOn();9  })10  .then(function (airplaneModeStatus) {11    assert.equal(airplaneModeStatus, false);12  })13  .fin(function () { return driver.quit(); })14  .done();15var assert = require('assert');16var wd = require('wd');17var desired = {18};19var driver = wd.promiseChainRemote('localhost', 4723);20  .init(desired)21  .then(function () {22    return driver.adb.toggleAirplaneMode();23  })24  .then(function () {25    return driver.adb.isAirplaneModeOn();26  })27  .then(function (airplaneModeStatus) {28    assert.equal(airplaneModeStatus, true);29  })30  .fin(function () { return driver.quit(); })31  .done();32var assert = require('assert');33var wd = require('wd');34var desired = {35};36var driver = wd.promiseChainRemote('localhost', 4723);37  .init(desired)38  .then(function () {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6var should = chai.should();7var desiredCaps = {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Android Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful