How to use adb.dismissKeyguard method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

unlock-helpers.js

Source:unlock-helpers.js Github

copy

Full Screen

...62  } else {63    logger.info('No active lock has been detected. Proceeding to the keyguard dismissal');64  }65  try {66    await adb.dismissKeyguard();67  } finally {68    if (wasLockEnabled) {69      await adb.setLockCredential(credentialType, credential);70    }71  }72};73helpers.encodePassword = function encodePassword (key) {74  return `${key}`.replace(/\s/ig, '%s');75};76helpers.stringKeyToArr = function stringKeyToArr (key) {77  return `${key}`.trim().replace(/\s+/g, '').split(/\s*/);78};79helpers.fingerprintUnlock = async function fingerprintUnlock (adb, driver, capabilities) {80  if (await adb.getApiLevel() < 23) {81    throw new Error('Fingerprint unlock only works for Android 6+ emulators');82  }83  await adb.fingerprint(capabilities.unlockKey);84  await sleep(UNLOCK_WAIT_TIME);85};86helpers.pinUnlock = async function pinUnlock (adb, driver, capabilities) {87  logger.info(`Trying to unlock device using pin ${capabilities.unlockKey}`);88  await adb.dismissKeyguard();89  const keys = helpers.stringKeyToArr(capabilities.unlockKey);90  if (await adb.getApiLevel() >= 21) {91    const els = await driver.findElOrEls('id', 'com.android.systemui:id/digit_text', true);92    if (_.isEmpty(els)) {93      // fallback to pin with key event94      return await helpers.pinUnlockWithKeyEvent(adb, driver, capabilities);95    }96    const pins = {};97    for (const el of els) {98      const text = await driver.getAttribute('text', util.unwrapElement(el));99      pins[text] = el;100    }101    for (const pin of keys) {102      const el = pins[pin];103      await driver.click(util.unwrapElement(el));104    }105  } else {106    for (const pin of keys) {107      const el = await driver.findElOrEls('id', `com.android.keyguard:id/key${pin}`, false);108      if (el === null) {109        // fallback to pin with key event110        return await helpers.pinUnlockWithKeyEvent(adb, driver, capabilities);111      }112      await driver.click(util.unwrapElement(el));113    }114  }115  await waitForUnlock(adb);116};117/**118 * Wait for the display to be unlocked.119 * Some devices automatically accept typed 'pin' and 'password' code120 * without pressing the Enter key. But some devices need it.121 * This method waits a few seconds first for such automatic acceptance case.122 * If the device is still locked, then this method will try to send123 * the enter key code.124 *125 * @param {ADB} adb The instance of ADB126 */127async function waitForUnlock (adb) {128  await sleep(UNLOCK_WAIT_TIME);129  if (!await adb.isScreenLocked()) {130    return;131  }132  await adb.keyevent(KEYCODE_NUMPAD_ENTER);133  await sleep(UNLOCK_WAIT_TIME);134}135helpers.pinUnlockWithKeyEvent = async function pinUnlockWithKeyEvent (adb, driver, capabilities) {136  logger.info(`Trying to unlock device using pin with keycode ${capabilities.unlockKey}`);137  await adb.dismissKeyguard();138  const keys = helpers.stringKeyToArr(capabilities.unlockKey);139  // Some device does not have system key ids like 'com.android.keyguard:id/key'140  // Then, sending keyevents are more reliable to unlock the screen.141  for (const pin of keys) {142    // 'pin' is number (0-9) in string.143    // Number '0' is keycode '7'. number '9' is keycode '16'.144    await adb.shell(['input', 'keyevent', parseInt(pin, 10) + NUMBER_ZERO_KEYCODE]);145  }146  await waitForUnlock(adb, driver);147};148helpers.passwordUnlock = async function passwordUnlock (adb, driver, capabilities) {149  const { unlockKey } = capabilities;150  logger.info(`Trying to unlock device using password ${unlockKey}`);151  await adb.dismissKeyguard();152  // Replace blank spaces with %s153  const key = helpers.encodePassword(unlockKey);154  // Why adb ? It was less flaky155  await adb.shell(['input', 'text', key]);156  // Why sleeps ? Avoid some flakyness waiting for the input to receive the keys157  await sleep(INPUT_KEYS_WAIT_TIME);158  await adb.shell(['input', 'keyevent', KEYCODE_NUMPAD_ENTER]);159  // Waits a bit for the device to be unlocked160  await waitForUnlock(adb, driver);161};162helpers.getPatternKeyPosition = function getPatternKeyPosition (key, initPos, piece) {163  /*164  How the math works:165  We have 9 buttons divided in 3 columns and 3 rows inside the lockPatternView,166  every button has a position on the screen corresponding to the lockPatternView since167  it is the parent view right at the middle of each column or row.168  */169  const cols = 3;170  const pins = 9;171  const xPos = (key, x, piece) => Math.round(x + ((key % cols) || cols) * piece - piece / 2);172  const yPos = (key, y, piece) => Math.round(y + (Math.ceil(((key % pins) || pins) / cols) * piece - piece / 2));173  return {174    x: xPos(key, initPos.x, piece),175    y: yPos(key, initPos.y, piece)176  };177};178helpers.getPatternActions = function getPatternActions (keys, initPos, piece) {179  const actions = [];180  let lastPos;181  for (let key of keys) {182    const keyPos = helpers.getPatternKeyPosition(key, initPos, piece);183    if (key === keys[0]) {184      actions.push({action: 'press', options: {element: null, x: keyPos.x, y: keyPos.y}});185      lastPos = keyPos;186      continue;187    }188    const moveTo = {x: 0, y: 0};189    const diffX = keyPos.x - lastPos.x;190    if (diffX > 0) {191      moveTo.x = piece;192      if (Math.abs(diffX) > piece) {193        moveTo.x += piece;194      }195    } else if (diffX < 0) {196      moveTo.x = -1 * piece;197      if (Math.abs(diffX) > piece) {198        moveTo.x -= piece;199      }200    }201    const diffY = keyPos.y - lastPos.y;202    if (diffY > 0) {203      moveTo.y = piece;204      if (Math.abs(diffY) > piece) {205        moveTo.y += piece;206      }207    } else if (diffY < 0) {208      moveTo.y = -1 * piece;209      if (Math.abs(diffY) > piece) {210        moveTo.y -= piece;211      }212    }213    actions.push({214      action: 'moveTo',215      options: {element: null, x: moveTo.x + lastPos.x, y: moveTo.y + lastPos.y}216    });217    lastPos = keyPos;218  }219  actions.push({action: 'release'});220  return actions;221};222helpers.patternUnlock = async function patternUnlock (adb, driver, capabilities) {223  const { unlockKey } = capabilities;224  logger.info(`Trying to unlock device using pattern ${unlockKey}`);225  await adb.dismissKeyguard();226  const keys = helpers.stringKeyToArr(unlockKey);227  /* We set the device pattern buttons as number of a regular phone228   *  | • • • |     | 1 2 3 |229   *  | • • • | --> | 4 5 6 |230   *  | • • • |     | 7 8 9 |231  The pattern view buttons are not seeing by the uiautomator since they are232  included inside a FrameLayout, so we are going to try clicking on the buttons233  using the parent view bounds and math.234  */235  const apiLevel = await adb.getApiLevel();236  const el = await driver.findElOrEls('id',237    `com.android.${apiLevel >= 21 ? 'systemui' : 'keyguard'}:id/lockPatternView`,238    false239  );...

Full Screen

Full Screen

lock-mgmt-e2e-specs.js

Source:lock-mgmt-e2e-specs.js Github

copy

Full Screen

...32      await adb.isLockEnabled().should.eventually.be.true;33      await adb.isScreenLocked().should.eventually.be.true;34      await adb.clearLockCredential(password);35      await adb.cycleWakeUp();36      await adb.dismissKeyguard();37      await adb.isLockEnabled().should.eventually.be.false;38      await adb.isScreenLocked().should.eventually.be.false;39    });40  });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .withCapabilities({4    })5    .build();6    .executeScript('mobile: dismissKeyguard', {})7    .then(function() {8        console.log('keyguard dismissed');9    });10    .executeScript('mobile: unlock', {})11    .then(function() {12        console.log('device unlocked');13    });14    .executeScript('mobile: isLocked', {})15    .then(function(locked) {16        console.log('device locked: ' + locked);17    });18driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desired = require('./desired');4describe('android', function() {5  this.timeout(300000);6  var driver;7  var allPassed = true;8  before(function() {9    driver = wd.promiseChainRemote('localhost', 4723);10    require("./logging").configure(driver);11    desired.app = require('./apps').androidApiDemos;12      .init(desired)13      .setImplicitWaitTimeout(6000);14  });15  after(function() {16      .quit()17      .finally(function() {18        if (!allPassed) {19          console.log("Not all tests passed!");20        }21      });22  });23  afterEach(function() {24    allPassed = allPassed && this.currentTest.state === 'passed';25  });26  it('should find the dismissKeyguard button', function() {27      .elementByName('App')28      .click()29      .elementByName('Alert Dialogs')30      .click()31      .elementByName('Dismiss Keyguard')32      .click()33      .dismissKeyguard()34      .sleep(10000)35      .elementByName('OK')36      .click()37      .sleep(10000);38  });39});40var wd = require('wd');41var assert = require('assert');42var desired = require('./desired');43describe('android', function() {44  this.timeout(300000);45  var driver;46  var allPassed = true;47  before(function() {48    driver = wd.promiseChainRemote('localhost', 4723);49    require("./logging").configure(driver);50    desired.app = require('./apps').androidApiDemos;51      .init(desired)52      .setImplicitWaitTimeout(6000);53  });54  after(function() {55      .quit()56      .finally(function() {57        if (!allPassed) {58          console.log("Not all tests passed!");59        }60      });61  });62  afterEach(function

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var _ = require('underscore');3var assert = require('assert');4var chai = require('chai');5var chaiAsPromised = require('chai-as-promised');6var should = chai.should();7var expect = chai.expect;8var assert = chai.assert;9chai.use(chaiAsPromised);10var desiredCaps = {11};12var driver = wd.promiseChainRemote("localhost", 4723);13driver.on('status', function(info) {14    console.log(info);15});16driver.on('command', function(meth, path, data) {17    console.log(' > ' + meth + ' ' + path + ' ' + (data || ''));18});19driver.on('http', function(meth, path, data) {20    console.log(' > ' + meth + ' ' + path + ' ' + (data || ''));21});22    .init(desiredCaps)23    .sleep(5000)24    .dismissKeyguard()25    .sleep(5000)26    .quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require("wd");2var assert = require("assert");3var desired = {4};5var driver = wd.promiseChainRemote("localhost", 4723);6  .init(desired)7  .dismissKeyguard()8  .sleep(3000)9  .quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Dismiss Keyguard', function () {2    it('should be able to dismiss keyguard', function () {3            .dismissKeyguard()4            .then(function () {5                    .sleep(5000)6                    .then(function () {7                            .findElementByAccessibilityId('Apps')8                            .click()9                            .then(function () {10                                    .sleep(5000)11                                    .then(function () {12                                            .findElementByAccessibilityId('Settings')13                                            .click()14                                            .then(function () {15                                                    .sleep(5000)16                                                    .then(function () {17                                                            .findElementByAccessibilityId('Apps')18                                                            .click()19                                                            .then(function () {20                                                                    .sleep(5000)21                                                                    .then(function () {22                                                                            .findElementByAccessibilityId('Settings')23                                                                            .click()24                                                                            .then(function () {25                                                                                    .sleep(5000)26                                                                                    .then(function () {27                                                                                            .findElementByAccessibilityId('Apps')28                                                                                            .click()29                                                                                            .then(function () {30                                                                                                    .sleep(5000)31                                                                                                    .then(function () {32                                                                                                            .findElementByAccessibilityId('Settings')33                                                                                                            .click()34                                                                                                            .then(function () {35                                                                                                                    .sleep(5000)36                                                                                                                    .then(function () {37                                                                                                                            .findElementByAccessibilityId('Apps')38                                                                                                                            .click()39                                                                                                                            .then(function () {40                                                                                                                                    .sleep(5000)41                                                                                                                                    .then(function () {42                                                                                                                                            .findElementByAccessibilityId('Settings')43                                                                                                                                            .click()44                                                                                                                                            .then(function () {45                                                                                                                                                    .sleep(5000)46                                                                                                                                                    .then(function () {47                                                                                                                                                            .findElementByAccessibilityId('Apps')48                                                                                                                                                            .click()49                                                                                                                                                            .then(function () {50                                                                                                                                                                    .sleep(5000)51                                                                                                                                                                    .then(function () {52                                                                                                                                                                            .findElementByAccessibilityId('Settings')53                                                                                                                                                                            .click()54                                                                                                                                                                            .then(function () {55                                                                                                                                                                                    .sleep(5000)

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('appium-adb');2var driver = new adb();3driver.dismissKeyguard();4var adb = require('appium-adb');5var driver = new adb();6driver.pressKeyCode(82);7var adb = require('appium-adb');8var driver = new adb();9driver.startLogcat();10var adb = require('appium-adb');11var driver = new adb();12driver.stopLogcat();13var adb = require('appium-adb');14var driver = new adb();15driver.getLogcatLogs();16var adb = require('appium-adb');17var driver = new adb();18driver.getConnectedEmulators();19var adb = require('appium-adb');20var driver = new adb();21driver.getConnectedDevices();22var adb = require('appium-adb');23var driver = new adb();24driver.getRunningAVD();25var adb = require('appium-adb');26var driver = new adb();27driver.getRunningAVDWithRetry();28var adb = require('appium-adb');29var driver = new adb();30driver.launchAVD();

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