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

Best JavaScript code snippet using appium-android-driver

android-common.js

Source:android-common.js Github

copy

Full Screen

...91};92androidCommon.background = function (secs, cb) {93  this.adb.getFocusedPackageAndActivity(function (err, pack, activity) {94    if (err) return cb(err);95    this.adb.keyevent("3", function (err) {96      if (err) return cb(err);97      setTimeout(function () {98        var onStart = function (err) {99          if (err) return cb(err);100          cb(null,{101            status: status.codes.Success.code,102            value: null103          });104        };105        this.adb.startApp({106          pkg: this.args.appPackage,107          activity: this.args.appActivity,108          action: this.args.intentAction,109          category: this.args.intentCategory,110          flags: this.args.intentFlags,111          waitPkg: pack,112          waitActivity: activity,113          optionalIntentArguments: this.args.optionalIntentArguments,114          retry: true,115          stopApp: !this.args.dontStopAppOnReset116        }, onStart);117      }.bind(this), secs * 1000);118    }.bind(this));119  }.bind(this));120};121androidCommon.openSettingsActivity = function (setting, cb) {122  this.adb.getFocusedPackageAndActivity(function (err, foundPackage,123                                                 foundActivity) {124    var cmd = 'am start -a android.settings.' + setting;125    this.adb.shell(cmd, function (err) {126      if (err) {127        cb(err);128      } else {129        this.adb.waitForNotActivity(foundPackage, foundActivity, 5000, cb);130      }131    }.bind(this));132  }.bind(this));133};134androidCommon.toggleSetting = function (setting, preKeySeq, ocb) {135  var doKey = function (key) {136    return function (cb) {137      setTimeout(function () {138        this.adb.keyevent(key, cb);139      }.bind(this), 2000);140    }.bind(this);141  }.bind(this);142  var settPkg, settAct;143  var back = function (cb) {144    this.adb.back(function (err) {145      if (err) {146        cb(err);147      } else {148        this.adb.waitForNotActivity(settPkg, settAct, 5000, cb);149      }150    }.bind(this));151  }.bind(this);152  /*153   * preKeySeq is the keyevent sequence to send over ADB in order154   * to position the cursor on the right option.155   * By default it's [up, up, down] because we usually target the 1st item in156   * the screen, and sometimes when opening settings activities the cursor is157   * already positionned on the 1st item, but we can't know for sure158   */159  if (preKeySeq === null) preKeySeq = [19, 19, 20]; // up, up, down160  var sequence = [161    function (cb) {162      this.openSettingsActivity(setting, cb);163    }.bind(this)164  ];165  var len = preKeySeq.length;166  for (var i = 0; i < len; i++) {167    sequence.push(doKey(preKeySeq[i]));168  }169  sequence.push(170    function (cb) {171      this.adb.getFocusedPackageAndActivity(function (err, foundPackage,172                                                     foundActivity) {173        settPkg = foundPackage;174        settAct = foundActivity;175        cb(err);176      }.bind(this));177    }.bind(this)178    , function (cb) {179      /*180       * Click and handle potential ADB disconnect that occurs on official181       * emulator when the network connection is disabled182       */183      this.wrapActionAndHandleADBDisconnect(doKey(23), cb);184    }.bind(this)185    , function (cb) {186      /*187       * In one particular case (enable Location Services), a pop-up is188       * displayed on some platforms so the user accepts or refuses that Google189       * collects location data. So we wait for that pop-up to open, if it190       * doesn't then proceed191       */192      this.adb.waitForNotActivity(settPkg, settAct, 5000, function (err) {193        if (err) {194          cb(null);195        } else {196          // Click on right button, "Accept"197          async.series([198            doKey(22)     // right199            , doKey(23)   // click200            , function (cb) {201              // Wait for pop-up to close202              this.adb.waitForActivity(settPkg, settAct, 5000, cb);203            }.bind(this)204          ], function (err) {205            cb(err);206          }.bind(this));207        }208      }.bind(this));209    }.bind(this)210    , back211  );212  async.series(sequence, function (err) {213    if (err) return ocb(err);214    ocb(null, { status: status.codes.Success.code });215  }.bind(this));216};217androidCommon.toggleData = function (cb) {218  this.adb.isDataOn(function (err, dataOn) {219    if (err) return cb(err);220    this.wrapActionAndHandleADBDisconnect(function (ncb) {221      this.adb.setData(dataOn ? 0 : 1, ncb);222    }.bind(this), function (err) {223      if (err) return cb(err);224      cb(null, {225        status: status.codes.Success.code226      });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");...

Full Screen

Full Screen

selendroid.js

Source:selendroid.js Github

copy

Full Screen

...262    }263  }.bind(this));264};265Selendroid.prototype.keyevent = function (keycode, metastate, cb) {266  this.adb.keyevent(keycode, function () {267    cb(null, {268      status: status.codes.Success.code269    , value: null270    });271  });272};273/*274 * Execute an arbitrary function and handle potential ADB disconnection before275 * proceeding276 */277Selendroid.prototype.wrapActionAndHandleADBDisconnect = function (action, ocb) {278  async.series([279    function (cb) {280      action(cb);...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

...102       * Once the Location services switch is OFF, it won't receive focus103       * when going back to the Location Services settings screen unless we104       * send a dummy keyevent (UP) *before* opening the settings screen105       */106      await this.adb.keyevent(19);107    }108    await this.toggleSetting('LOCATION_SOURCE_SETTINGS', seq);109  } else {110    // There's no global location services toggle on older Android versions111    throw new errors.NotYetImplementedError();112  }113};114helpers.toggleSetting = async function (setting, preKeySeq) {115  /*116   * preKeySeq is the keyevent sequence to send over ADB in order117   * to position the cursor on the right option.118   * By default it's [up, up, down] because we usually target the 1st item in119   * the screen, and sometimes when opening settings activities the cursor is120   * already positionned on the 1st item, but we can't know for sure121   */122  if (_.isNull(preKeySeq)) {123    preKeySeq = [19, 19, 20]; // up, up, down124  }125  await this.openSettingsActivity(setting);126  for (let key of preKeySeq) {127    await this.doKey(key);128  }129  let {appPackage, appActivity} = await this.adb.getFocusedPackageAndActivity();130  /*131   * Click and handle potential ADB disconnect that occurs on official132   * emulator when the network connection is disabled133   */134  await this.wrapBootstrapDisconnect(async () => {135    await this.doKey(23);136  });137  /*138   * In one particular case (enable Location Services), a pop-up is139   * displayed on some platforms so the user accepts or refuses that Google140   * collects location data. So we wait for that pop-up to open, if it141   * doesn't then proceed142   */143  try {144    await this.adb.waitForNotActivity(appPackage, appActivity, 5000);145    await this.doKey(22); // right146    await this.doKey(23); // click147    await this.adb.waitForNotActivity(appPackage, appActivity, 5000);148  } catch (ign) {}149  await this.adb.back();150};151helpers.doKey = async function (key) {152  // TODO: Confirm we need this delay. Seems to work without it.153  await B.delay(2000);154  await this.adb.keyevent(key);155};156helpers.wrapBootstrapDisconnect = async function (wrapped) {157  this.bootstrap.ignoreUnexpectedShutdown = true;158  try {159    await wrapped();160    await this.adb.restart();161    await this.bootstrap.start(this.opts.appPackage, this.opts.disableAndroidWatchers, this.opts.acceptSslCerts);162  } finally {163    this.bootstrap.ignoreUnexpectedShutdown = false;164  }165};166Object.assign(extensions, commands, helpers);167export { commands, helpers };168export default extensions;

Full Screen

Full Screen

commands.js

Source:commands.js Github

copy

Full Screen

...72};73// Selendroid doesn't support metastate for keyevents74commands.keyevent = async function keyevent (keycode, metastate) {75  log.debug(`Ignoring metastate ${metastate}`);76  await this.adb.keyevent(keycode);77};78// Use ADB since we don't have UiAutomator79commands.back = async function back () {80  await this.adb.keyevent(4);81};82commands.getContexts = async function getContexts () {83  let chromiumViews = [];84  let webviews = await webviewHelpers.getWebviews(this.adb,85      this.opts.androidDeviceSocket);86  if (_.includes(webviews, CHROMIUM_WIN)) {87    chromiumViews = [CHROMIUM_WIN];88  } else {89    chromiumViews = [];90  }91  log.info('Getting window handles from Selendroid');92  let selendroidViews = await this.selendroid.jwproxy.command('/window_handles', 'GET', {});93  this.contexts = _.union(selendroidViews, chromiumViews);94  log.info(`Available contexts: ${JSON.stringify(this.contexts)}`);...

Full Screen

Full Screen

general.js

Source:general.js Github

copy

Full Screen

...14};15// uiautomator2 doesn't support metastate for keyevents16commands.keyevent = async function (keycode, metastate) {17  log.debug(`Ignoring metastate ${metastate}`);18  await this.adb.keyevent(keycode);19};20// Use ADB since we don't have UiAutomator21commands.back = async function () {22  await this.adb.keyevent(4);23};24commands.getStrings = async function (language) {25  if (!language) {26    language = await this.adb.getDeviceLanguage();27    log.info(`No language specified, returning strings for: ${language}`);28  }29  if (this.apkStrings[language]) {30    // Return cached strings31    return this.apkStrings[language];32  }33  // TODO: This is mutating the current language, but it's how appium currently works34  this.apkStrings[language] = await androidHelpers.pushStrings(language, this.adb, this.opts);35  await this.uiautomator2.jwproxy.command(`/appium/app/strings`, 'POST', {});36  return this.apkStrings[language];...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('appium-webdriver');2  withCapabilities({3  build();4driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');5driver.findElement(webdriver.By.name('btnG')).click();6driver.sleep(5000).then(function() {7  driver.quit();8});9driver.adb.keyevent(4);10driver.adb.keyevent(3);11driver.adb.keyevent(26);12driver.adb.keyevent(82);13driver.adb.keyevent(66);14driver.adb.keyevent(4);15driver.adb.keyevent(3);16driver.adb.keyevent(26);17driver.adb.keyevent(82);18driver.adb.keyevent(66);19driver.adb.keyevent(4);20driver.adb.keyevent(3);21driver.adb.keyevent(26);

Full Screen

Using AI Code Generation

copy

Full Screen

1this.adb.keyevent(3);2this.adb.keyevent(4);3this.adb.keyevent(82);4this.adb.shell('input keyevent 3');5this.adb.shell('input keyevent 4');6this.adb.shell('input keyevent 82');7this.adb.getApiLevel().then(function(apiLevel) {8  console.log(apiLevel);9});10this.adb.getEmulatorPort().then(function(emulatorPort) {11  console.log(emulatorPort);12});13this.adb.getConnectedEmulators().then(function(connectedEmulators) {14  console.log(connectedEmulators);15});16this.adb.getRunningAVD().then(function(runningAVD) {17  console.log(runningAVD);18});19this.adb.getRunningAVDWithRetry().then(function(runningAVDWithRetry) {20  console.log(runningAVDWithRetry);21});22this.adb.getRunningAVDWithRetry().then(function(runningAVDWithRetry) {23  console.log(runningAVDWithRetry);24});25this.adb.getConnectedDevices().then(function(connectedDevices) {26  console.log(connectedDevices);27});28this.adb.getConnectedDevicesWithRetry().then(function(connectedDevicesWithRetry) {29  console.log(connectedDevicesWithRetry);30});

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumDriver = require('appium-android-driver');2var Adb = require('appium-adb');3var driver = new AppiumDriver();4var adb = new Adb();5driver.adb = adb;6driver.adb.keyevent(3).then(function() {7  console.log("done");8});9var adb = new Adb();10adb.keyevent(3).then(function() {11  console.log("done");12});13var Adb = require('appium-adb');14var adb = new Adb();15adb.keyevent(3).then(function() {16  console.log("done");17});18var adb = new Adb();19adb.keyevent(3).then(function() {20  console.log("done");21});

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