Best JavaScript code snippet using appium-android-driver
driver.js
Source:driver.js  
...351    await helpers.removeAllSessionWebSocketHandlers(this.server, this.sessionId);352    await super.deleteSession();353    if (this.bootstrap) {354      // certain cleanup we only care to do if the bootstrap was ever run355      await this.stopChromedriverProxies();356      if (this.opts.unicodeKeyboard && this.opts.resetKeyboard && this.defaultIME) {357        log.debug(`Resetting IME to ${this.defaultIME}`);358        await this.adb.setIME(this.defaultIME);359      }360      if (!this.isChromeSession && !this.opts.dontStopAppOnReset) {361        await this.adb.forceStop(this.opts.appPackage);362      }363      await this.adb.goToHome();364      if (this.opts.fullReset && !this.opts.skipUninstall && !this.appOnDevice) {365        await this.adb.uninstallApk(this.opts.appPackage);366      }367      await this.bootstrap.shutdown();368      this.bootstrap = null;369    } else {...android.js
Source:android.js  
...181};182Android.prototype.onUiautomatorExit = function () {183  logger.debug("UiAutomator exited");184  var respondToClient = function () {185    this.stopChromedriverProxies(function () {186      this.cleanup();187      if (!this.didLaunch) {188        var msg = "UiAutomator quit before it successfully launched";189        logger.error(msg);190        this.launchCb(new Error(msg));191        return;192      } else if (typeof this.cbForCurrentCmd === "function") {193        var error = new UnknownError("UiAutomator died while responding to " +194                                      "command, please check appium logs!");195        this.cbForCurrentCmd(error, null);196      }197      // make sure appium.js knows we crashed so it can clean up198      this.uiautomatorExitCb();199    }.bind(this));200  }.bind(this);201  if (this.adb) {202    var uninstall = function () {203      logger.debug("Attempting to uninstall app");204      this.uninstallApp(function () {205        this.shuttingDown = false;206        respondToClient();207      }.bind(this));208    }.bind(this);209    if (!this.uiautomatorIgnoreExit) {210      this.adb.ping(function (err, ok) {211        if (ok) {212          uninstall();213        } else {214          logger.debug(err);215          this.adb.restart(function (err) {216            if (err) {217              logger.debug(err);218            }219            if (this.uiautomatorRestartOnExit) {220              this.uiautomatorRestartOnExit = false;221              this.restartUiautomator(function (err) {222                if (err) {223                  logger.debug(err);224                  uninstall();225                }226              }.bind(this));227            } else {228              uninstall();229            }230          }.bind(this));231        }232      }.bind(this));233    } else {234      this.uiautomatorIgnoreExit = false;235    }236  } else {237    logger.debug("We're in uiautomator's exit callback but adb is gone already");238    respondToClient();239  }240};241Android.prototype.checkShouldRelaunch = function (launchErr) {242  if (launchErr.message === null || typeof launchErr.message === 'undefined') {243    logger.error("We're checking if we should relaunch based on something " +244                 "which isn't an error object. Check the codez!");245    return false;246  }247  var msg = launchErr.message.toString();248  var relaunchOn = [249    'Could not find a connected Android device'250    , 'Device did not become ready'251  ];252  var relaunch = false;253  _.each(relaunchOn, function (relaunchMsg) {254    relaunch = relaunch || msg.indexOf(relaunchMsg) !== -1;255  });256  return relaunch;257};258Android.prototype.checkApiLevel = function (cb) {259  this.adb.getApiLevel(function (err, apiLevel) {260    if (err) return cb(err);261    logger.info('Device API level is:', parseInt(apiLevel, 10));262    if (parseInt(apiLevel) < 17) {263      var msg = "Android devices must be of API level 17 or higher. Please change your device to Selendroid or upgrade Android on your device.";264      logger.error(msg); // logs the error when we encounter it265      return cb(new Error(msg)); // send the error up the chain266    }267    cb();268  });269};270Android.prototype.decorateChromeOptions = function (caps) {271  // add options from appium session caps272  if (this.args.chromeOptions) {273    _.each(this.args.chromeOptions, function (val, option) {274      if (typeof caps.chromeOptions[option] === "undefined") {275        caps.chromeOptions[option] = val;276      } else {277        logger.warn("Cannot pass option " + caps.chromeOptions[option] + " because Appium needs it to make chromeDriver work");278      }279    });280  }281  // add device id from adb282  caps.chromeOptions.androidDeviceSerial = this.adb.curDeviceId;283  return caps;284};285Android.prototype.processFromManifest = function (cb) {286  if (!this.args.app) {287    return cb();288  } else { // apk must be local to process the manifest.289    this.adb.processFromManifest(this.args.app, function (err, process) {290      var value = process || this.args.appPackage;291      this.appProcess = value;292      logger.debug("Set app process to: " + this.appProcess);293      cb();294    }.bind(this));295  }296};297Android.prototype.pushStrings = function (cb, language) {298  var outputPath = path.resolve(this.args.tmpDir, this.args.appPackage);299  var remotePath = '/data/local/tmp';300  var stringsJson = 'strings.json';301  this.extractStrings(function (err) {302    if (err) {303      if (!fs.existsSync(this.args.app)) {304        // apk doesn't exist locally so remove old strings.json305        logger.debug("Could not get strings, but it looks like we had an " +306                     "old strings file anyway, so ignoring");307        return this.adb.rimraf(remotePath + '/' + stringsJson, function (err) {308          if (err) return cb(new Error("Could not remove old strings"));309          cb();310        });311      } else {312        // if we can't get strings, just dump an empty json and continue313        logger.warn("Could not get strings, continuing anyway");314        var remoteFile = remotePath + '/' + stringsJson;315        return this.adb.shell("echo '{}' > " + remoteFile, cb);316      }317    }318    var jsonFile = path.resolve(outputPath, stringsJson);319    this.adb.push(jsonFile, remotePath, function (err) {320      if (err) return cb(new Error("Could not push strings.json"));321      cb();322    });323  }.bind(this), language);324};325Android.prototype.getStrings = function (language, stringFile, cb) {326  if (this.language && this.language === language) {327    // Return last strings328    return cb(null, {329      status: status.codes.Success.code,330      value: this.apkStrings331    });332  }333  // Extract, push and return strings334  return this.pushStrings(function () {335    this.proxy(["updateStrings", {}], function (err, res) {336      if (err || res.status !== status.codes.Success.code) return cb(err, res);337      cb(null, {338        status: status.codes.Success.code,339        value: this.apkStrings340      });341    }.bind(this));342  }.bind(this), language);343};344Android.prototype.pushAppium = function (cb) {345  logger.debug("Pushing appium bootstrap to device...");346  var binPath = path.resolve(__dirname, "..", "..", "..", "build",347      "android_bootstrap", "AppiumBootstrap.jar");348  fs.stat(binPath, function (err) {349    if (err) {350      cb(new Error("Could not find AppiumBootstrap.jar; please run " +351                   "'grunt buildAndroidBootstrap'"));352    } else {353      this.adb.push(binPath, this.remoteTempPath(), cb);354    }355  }.bind(this));356};357Android.prototype.startAppUnderTest = function (cb) {358  this.startApp(this.args, cb);359};360Android.prototype.startApp = function (args, cb) {361  if (args.androidCoverage) {362    this.adb.androidCoverage(args.androidCoverage, args.appWaitPackage,363      args.appWaitActivity, cb);364  } else {365    this.adb.startApp({366      pkg: args.appPackage,367      activity: args.appActivity,368      action: args.intentAction,369      category: args.intentCategory,370      flags: args.intentFlags,371      waitPkg: args.appWaitPackage,372      waitActivity: args.appWaitActivity,373      optionalIntentArguments: args.optionalIntentArguments,374      stopApp: args.stopAppOnReset || !args.dontStopAppOnReset375    }, cb);376  }377};378Android.prototype.stop = function (cb) {379  if (this.shuttingDown) {380    logger.debug("Already in process of shutting down.");381    return cb();382  }383  this.shuttingDown = true;384  var completeShutdown = function (cb) {385    if (this.adb) {386      this.adb.goToHome(function () {387        this.shutdown(cb);388      }.bind(this));389    } else {390      this.shutdown(cb);391    }392  }.bind(this);393  if (this.args.fullReset) {394    logger.debug("Removing app from device");395    this.uninstallApp(function (err) {396      if (err) {397        // simply warn on error here, because we don't want to stop the shutdown398        // process399        logger.warn(err);400      }401      completeShutdown(cb);402    });403  } else {404    completeShutdown(cb);405  }406};407Android.prototype.cleanup = function () {408  logger.debug("Cleaning up android objects");409  this.adb = null;410  this.uiautomator = null;411  this.shuttingDown = false;412};413Android.prototype.shutdown = function (cb) {414  var next = function () {415    this.stopChromedriverProxies(function () {416      if (this.uiautomator) {417        this.uiautomator.shutdown(function () {418          this.cleanup();419          cb();420        }.bind(this));421      } else {422        this.cleanup();423        cb();424      }425    }.bind(this));426  }.bind(this);427  if (this.adb) {428    this.adb.endAndroidCoverage();429    if (this.args.unicodeKeyboard && this.args.resetKeyboard && this.defaultIME) {...context.js
Source:context.js  
...59    // to true then kill chromedriver session using stopChromedriverProxies or60    // else simply suspend proxying to the latter61    if (this.opts.recreateChromeDriverSessions) {62      logger.debug("recreateChromeDriverSessions set to true; killing existing chromedrivers");63      this.stopChromedriverProxies();64    } else {65      this.suspendChromedriverProxy();66    }67  } else {68    throw new Error(`Didn't know how to handle switching to context '${name}'`);69  }70};71/* ---------------------------------72 * On-object context-related helpers73 * --------------------------------- */74// The reason this is a function and not just a constant is that both android-75// driver and selendroid-driver use this logic, and each one returns76// a different default context name77helpers.defaultContextName = function () {...Using AI Code Generation
1driver.stopChromedriverProxies();2commands.stopChromedriverProxies = async function () {3  const chromedrivers = this.chromedrivers;4  log.debug(`Stopping chromedrivers`);5  for (let [chromedriver, proxy] of chromedrivers) {6    await chromedriver.stop();7    await proxy.stop();8  }9  this.chromedrivers = [];10};11commands.stopChromedriverProxies = async function () {12  const chromedrivers = this.chromedrivers;13  log.debug(`Stopping chromedrivers`);14  for (let [chromedriver, proxy] of chromedrivers) {15    await chromedriver.stop();16    await proxy.stop();17  }18  this.chromedrivers = [];19};20commands.stopChromedriverProxies = async function () {21  const chromedrivers = this.chromedrivers;22  log.debug(`Stopping chromedrivers`);23  for (let [chromedriver, proxy] of chromedrivers) {24    await chromedriver.stop();25    await proxy.stop();26  }27  this.chromedrivers = [];28};29commands.stopChromedriverProxies = async function () {30  const chromedrivers = this.chromedrivers;31  log.debug(`Stopping chromedrivers`);32  for (let [chromedriver, proxy] of chromedrivers) {33    await chromedriver.stop();34    await proxy.stop();35  }36  this.chromedrivers = [];37};38commands.stopChromedriverProxies = async function () {39  const chromedrivers = this.chromedrivers;40  log.debug(`Stopping chromedrivers`);41  for (let [chromedriver, proxy] of chromedriversUsing AI Code Generation
1const { AndroidDriver } = require('appium-android-driver');2const driver = new AndroidDriver();3driver.stopChromedriverProxies();4const { AndroidDriver } = require('appium-android-driver');5const driver = new AndroidDriver();6driver.stopChromedriverProxies();7const { AndroidDriver } = require('appium-android-driver');8const driver = new AndroidDriver();9driver.stopChromedriverProxies();10const { AndroidDriver } = require('appium-android-driver');11const driver = new AndroidDriver();12driver.stopChromedriverProxies();13const { AndroidDriver } = require('appium-android-driver');14const driver = new AndroidDriver();15driver.stopChromedriverProxies();16const { AndroidDriver } = require('appium-androidLearn 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!!
