Best JavaScript code snippet using appium-android-driver
android-common.js
Source:android-common.js  
...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  var outputPath = path.resolve(this.args.tmpDir, this.args.appPackage);760  var stringsJson = 'strings.json';761  if (!fs.existsSync(this.args.app)) {762    logger.debug("Apk doesn't exist locally");763    this.apkStrings = {};764    this.language = null;765    return cb(new Error("Apk doesn't exist locally"));766  } else {767    this.extractLocalizedStrings(language, outputPath, function (err, stdout, stderr) {768      if (err) {769        logger.warn("Error getting strings.xml from apk");770        logger.debug(stderr);771        this.apkStrings = {};772        this.language = null;773        return cb(err);774      }775      var file = fs.readFileSync(path.join(outputPath, stringsJson), 'utf8');776      this.apkStrings = JSON.parse(file);777      this.language = language;778      cb();779    }.bind(this));780  }781};782androidCommon.initUnicode = function (cb) {783  if (this.args.unicodeKeyboard) {784    logger.debug('Enabling Unicode keyboard support');785    this.pushUnicodeIME(function (err) {786      if (err) return cb(err);787      this.adb.defaultIME(function (err, engine) {788        if (err) return cb(err);789        // save the previously set IME790        this.defaultIME = engine;791        logger.debug('Unsetting IME \'' + this.defaultIME + '\'');792        logger.debug('Setting IME to \'io.appium.android.ime/.UnicodeIME\'');793        this.adb.enableIME('io.appium.android.ime/.UnicodeIME', function (err) {794          if (err) return cb(err);795          this.adb.setIME('io.appium.android.ime/.UnicodeIME', cb);796        }.bind(this));797      }.bind(this));798    }.bind(this));799  } else {800    cb();801  }802};803androidCommon.getNetworkConnection = function (cb) {804  logger.info('Getting network connection');805  this.adb.isAirplaneModeOn(function (err, airplaneModeOn) {806    if (err) return cb(err);807    var connection = airplaneModeOn ? 1 : 0;808    if (airplaneModeOn) {809      // airplane mode on implies wifi and data off810      return cb(null, {811        status: status.codes.Success.code,812        value: connection813      });814    }815    this.adb.isWifiOn(function (err, wifiOn) {816      if (err) return cb(err);817      connection += (wifiOn ? 2 : 0);818      this.adb.isDataOn(function (err, dataOn) {819        if (err) return cb(err);820        connection += (dataOn ? 4 : 0);821        cb(null, {822          status: status.codes.Success.code,823          value: connection824        });825      }.bind(this));826    }.bind(this));827  }.bind(this));828};829androidCommon.setNetworkConnection = function (type, ocb) {830  logger.info('Setting network connection');831  // decode the input832  var airplaneMode = type % 2;833  type >>= 1;834  var wifi = type % 2;835  type >>= 1;836  var data = type % 2;837  var series = [];838  // do airplane mode stuff first, since it will change the other statuses839  series.push(function (cb) {840    this.wrapActionAndHandleADBDisconnect(function (ncb) {841      this.adb.setAirplaneMode(airplaneMode, ncb);842    }.bind(this), cb);843  }.bind(this));844  series.push(function (cb) {845    this.wrapActionAndHandleADBDisconnect(function (ncb) {846      this.adb.broadcastAirplaneMode(airplaneMode, ncb);847    }.bind(this), cb);848  }.bind(this));849  // no need to do anything else if we are in or going into airplane mode850  if (airplaneMode === 0) {851    series.push(function (cb) {852      this.wrapActionAndHandleADBDisconnect(function (ncb) {853        this.adb.setWifiAndData({854          wifi: wifi,855          data: data...network.js
Source:network.js  
...30  let wifi = type % 2;31  type >>= 1;32  let data = type % 2;33  await this.wrapBootstrapDisconnect(async () => {34    await this.adb.setAirplaneMode(airplaneMode);35  });36  await this.wrapBootstrapDisconnect(async () => {37    await this.adb.broadcastAirplaneMode(airplaneMode);38  });39  if (!airplaneMode) {40    await this.wrapBootstrapDisconnect(async () => {41      await this.setWifiState(wifi);42      await this.adb.setDataState(data, this.isEmulator());43    });44  }45  return await this.getNetworkConnection();46};47/**48 * decoupling to override behaviour in other drivers like UiAutomator2.49 */50commands.setWifiState = async function (wifi) {51  await this.adb.setWifiState(wifi, this.isEmulator());52};53commands.toggleData = async function () {54  let data = !(await this.adb.isDataOn());55  log.info(`Turning network data ${data ? 'on' : 'off'}`);56  await this.wrapBootstrapDisconnect(async () => {57    await this.adb.setWifiAndData({data}, this.isEmulator());58  });59};60commands.toggleWiFi = async function () {61  let wifi = !(await this.adb.isWifiOn());62  log.info(`Turning WiFi ${wifi ? 'on' : 'off'}`);63  await this.wrapBootstrapDisconnect(async () => {64    await this.adb.setWifiAndData({wifi}, this.isEmulator());65  });66};67commands.toggleFlightMode = async function () {68  /*69   * TODO: Implement isRealDevice(). This method fails on70   * real devices, it should throw a NotYetImplementedError71   */72  let flightMode = !(await this.adb.isAirplaneModeOn());73  log.info(`Turning flight mode ${flightMode ? 'on' : 'off'}`);74  await this.wrapBootstrapDisconnect(async () => {75    await this.adb.setAirplaneMode(flightMode);76  });77  await this.wrapBootstrapDisconnect(async () => {78    await this.adb.broadcastAirplaneMode(flightMode);79  });80};81commands.setGeoLocation = async function (location) {82  return await this.adb.setGeoLocation(location, this.isEmulator());83};84commands.toggleLocationServices = async function () {85  log.info("Toggling location services");86  let api = await this.adb.getApiLevel();87  if (this.isEmulator()) {88    let providers = await this.adb.getLocationProviders();89    let isGpsEnabled = providers.indexOf('gps') !== -1;...Using AI Code Generation
1this.adb.setAirplaneMode(true);2this.adb.setAirplaneMode(false);3this.adb.setWifiAndData(true);4this.adb.setWifiAndData(false);5this.adb.setWifiState(true);6this.adb.setWifiState(false);7this.adb.setWifiState(true);8this.adb.setWifiState(false);9this.adb.setWifiAndData(true);10this.adb.setWifiAndData(false);11this.adb.setWifiState(true);12this.adb.setWifiState(false);13this.adb.setWifiState(true);14this.adb.setWifiState(false);15this.adb.setWifiAndData(true);16this.adb.setWifiAndData(false);17this.adb.setWifiState(true);18this.adb.setWifiState(false);19this.adb.setWifiState(true);20this.adb.setWifiState(false);21this.adb.setWifiAndData(true);22this.adb.setWifiAndData(false);23this.adb.setWifiState(true);24this.adb.setWifiState(false);25this.adb.setWifiState(true);26this.adb.setWifiState(false);27this.adb.setWifiAndData(true);28this.adb.setWifiAndData(false);29this.adb.setWifiState(true);30this.adb.setWifiState(false);Using AI Code Generation
1this.adb.setAirplaneMode(true);2this.adb.setAirplaneMode(false);3let isAirplaneModeOn = await this.adb.isAirplaneModeOn();4this.adb.setWifiState(true);5this.adb.setWifiState(false);6let isWifiOn = await this.adb.isWifiOn();7this.adb.setWifiAndData(true);8this.adb.setWifiAndData(false);9let isWifiAndDataOn = await this.adb.isWifiAndDataOn();10this.adb.setWifiTethering(true);11this.adb.setWifiTethering(false);12let isWifiTetheringOn = await this.adb.isWifiTetheringOn();13this.adb.setBluetoothState(true);14this.adb.setBluetoothState(false);15let isBluetoothOn = await this.adb.isBluetoothOn();16this.adb.setBluetoothTethering(true);17this.adb.setBluetoothTethering(false);18let isBluetoothTetheringOn = await this.adb.isBluetoothTetheringOn();19this.adb.setGPS(true);20this.adb.setGPS(false);21let isGPSOn = await this.adb.isGPSOn();22this.adb.setNetworkSpeed("gsm");Using AI Code Generation
1this.adb.setAirplaneMode(true);2this.adb.setAirplaneMode(false);3this.adb.setAirplaneMode(true);4this.adb.setAirplaneMode(false);5this.adb.setAirplaneMode(true);6this.adb.setAirplaneMode(false);7this.adb.setAirplaneMode(true);8this.adb.setAirplaneMode(false);9this.adb.setAirplaneMode(true);10this.adb.setAirplaneMode(false);11this.adb.setAirplaneMode(true);12this.adb.setAirplaneMode(false);13this.adb.setAirplaneMode(true);14this.adb.setAirplaneMode(false);15this.adb.setAirplaneMode(true);16this.adb.setAirplaneMode(false);17this.adb.setAirplaneMode(true);18this.adb.setAirplaneMode(false);19this.adb.setAirplaneMode(true);Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var AndroidDriver = require('appium-android-driver');3var ADB = require('appium-adb');4var driver = new AndroidDriver();5var adb = new ADB();6driver.adb.setAirplaneMode(true);7driver.adb.setAirplaneMode(false);Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var AppiumDriver = require('appium').Driver;3var AppiumAndroidDriver = require('appium-android-driver').AndroidDriver;4var AppiumAndroidDriver = require('appium-android-driver').AndroidDriver;5var driver = new webdriver.Builder()6    .withCapabilities({7    })8    .build();9driver.executeScript('mobile: shell', {command: 'am', args: ['start', '-n', 'com.android.settings/.Settings']});10driver.executeScript('mobile: shell', {command: 'am', args: ['start', '-n', 'com.android.settings/.Settings$AirplaneModeSettingsActivity']});11driver.executeScript('mobile: shell', {command: 'am', args: ['start', '-n', 'com.android.settings/.Settings']});12driver.executeScript('mobile: shell', {command: 'am', args: ['start', '-n', 'com.android.settings/.Settings$AirplaneModeSettingsActivity']});13driver.quit();14var webdriver = require('selenium-webdriver');15var AppiumDriver = require('appium').Driver;16var AppiumAndroidDriver = require('appium-android-driver').AndroidDriver;17var AppiumAndroidDriver = require('appium-android-driver').AndroidDriver;18var driver = new webdriver.Builder()19    .withCapabilities({20    })21    .build();22driver.executeScript('mobile: shell', {command: 'am', args: ['start', '-n', 'com.androidUsing AI Code Generation
1var webdriver = require('selenium-webdriver');2var android = require('appium-android-driver');3var driver = new webdriver.Builder()4    .forBrowser('android')5    .build();6var adb = new android.ADB();7var desiredCaps = {8};9    .init(desiredCaps)10    .then(function () {11        return adb.setAirplaneMode(true);12    })13    .then(function () {14        return adb.setAirplaneMode(false);15    })16    .then(function () {17        return adb.setAirplaneMode(true);18    })19    .then(function () {20        return adb.setAirplaneMode(false);21    })22    .then(function () {23        return driver.quit();24    })25    .then(null, function (err) {26        console.log(err);27    });28var webdriver = require('selenium-webdriver');29var android = require('appium-android-driver');30var driver = new webdriver.Builder()31    .forBrowser('android')32    .build();33var adb = new android.ADB();34var desiredCaps = {35};36    .init(desiredCaps)37    .then(function () {38        return adb.setAirplaneMode(true);39    })40    .then(function () {41        return adb.setAirplaneMode(false);42    })43    .then(function () {44        return adb.setAirplaneMode(true);45    })46    .then(function () {47        return adb.setAirplaneMode(false);48    })49    .then(function () {50        return driver.quit();51    })52    .then(null, function (err) {53        console.log(err);54    });Using AI Code Generation
1var Appium = require('appium');2var AndroidDriver = Appium.AndroidDriver;3var Android = require('appium-android-driver');4var ADB = Android.ADB;5var adb = new ADB();6var driver = new AndroidDriver({adb: adb});7driver.setAirplaneMode(true);8var Appium = require('appium');9var AndroidDriver = Appium.AndroidDriver;10var Android = require('appium-android-driver');11var ADB = Android.ADB;12var adb = new ADB();13var driver = new AndroidDriver({adb: adb});14driver.setAirplaneMode(true);Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var android = require('appium-android-driver');3var adb = new android.ADB();4adb.setAirplaneMode(true);5var webdriver = require('selenium-webdriver');6var android = require('appium-android-driver');7var adb = new android.ADB();8adb.setAirplaneMode(true);9var webdriver = require('selenium-webdriver');10var android = require('appium-android-driver');11var adb = new android.ADB();12adb.setAirplaneMode(true);13var webdriver = require('selenium-webdriver');14var android = require('appium-android-driver');15var adb = new android.ADB();16adb.setAirplaneMode(true);17var webdriver = require('selenium-webdriver');18var android = require('appium-android-driver');19var adb = new android.ADB();20adb.setAirplaneMode(true);21var webdriver = require('selenium-webdriver');22var android = require('appium-android-driver');23var adb = new android.ADB();24adb.setAirplaneMode(true);25var webdriver = require('selenium-webdriver');26var android = require('appium-android-driver');27var adb = new android.ADB();28adb.setAirplaneMode(true);29var webdriver = require('selenium-webdriver');30var android = require('appium-android-driver');31var adb = new android.ADB();32adb.setAirplaneMode(true);33var webdriver = require('selenium-webdriver');34var android = require('appium-android-driver');35var adb = new android.ADB();36adb.setAirplaneMode(true);37var webdriver = require('selenium-webdriver');38var android = require('appium-android-driver');Using AI Code Generation
1commands.setAirplaneMode = async function (mode) {2  return await this.adb.setAirplaneMode(mode);3};4methods.setAirplaneMode = async function (mode) {5  let apiLevel = await this.getApiLevel();6  if (apiLevel < 17) {7    throw new Error(`API level ${apiLevel} does not support setting airplane mode`);8  }9  let cmd = `settings put global airplane_mode_on ${mode ? 1 : 0}`;10  await this.shell(cmd);11  await this.broadcastAirplaneMode();12};13methods.broadcastAirplaneMode = async function () {14  let cmd = 'am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true';15  await this.shell(cmd);16};17methods.shell = async function (cmd, opts = {}) {18  let {19  } = opts;20  if (privileged) {21    cmd = `echo '${cmd}' | su`;22  }23  if (wrapInQuotes) {24    cmd = `'${cmd}'`;25  }26  return await this.exec(['shell', cmd]);27};28methods.exec = async function (args, opts = {}) {29  return await this.adbExec(args, opts);30};31methods.adbExec = async function (args, opts = {}) {32  let {timeout} = opts;33  let proc = await this.spawn(args, opts);34  if (timeout) {35    proc.on('exit', function (code, signal) {36      log.debug(`process exited with code ${code}, signal ${signal}`);37    });38    proc.on('error', function (err) {39      log.debug(`process error ${err}`);40    });41    proc.on('close', function (code, signal) {42      log.debug(`process closed with code ${code}, signal ${signal}`);43    });44  }45  return await proc;46};47methods.spawn = async function (args, opts = {})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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
