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

Best JavaScript code snippet using appium-android-driver

android-common.js

Source:android-common.js Github

copy

Full Screen

...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();...

Full Screen

Full Screen

driver.js

Source:driver.js Github

copy

Full Screen

...309        await helpers.resetApp(this.adb, this.opts);310      }311    }312    if (!this.opts.skipUninstall) {313      await this.adb.uninstallApk(this.opts.appPackage);314    }315    if (this.opts.app) {316      if (this.opts.noSign) {317        logger.info('Skipping application signing because noSign capability is set to true. ' +318          'Having the application under test with improper signature/non-signed will cause ' +319          'Espresso automation startup failure.');320      } else if (!await this.adb.checkApkCert(this.opts.app, this.opts.appPackage)) {321        await this.adb.sign(this.opts.app, this.opts.appPackage);322      }323      await helpers.installApk(this.adb, this.opts);324    }325    await this.espresso.installTestApk();326  }327  async deleteSession () {328    logger.debug('Deleting espresso session');329    if (this.espresso) {330      if (this.jwpProxyActive) {331        await this.espresso.deleteSession();332      }333      this.espresso = null;334    }335    this.jwpProxyActive = false;336    // TODO below logic is duplicated from uiautomator2337    if (this.adb) {338      if (this.wasAnimationEnabled) {339        try {340          await this.adb.setAnimationState(true);341        } catch (err) {342          logger.warn(`Unable to reset animation: ${err.message}`);343        }344      }345      if (this.opts.unicodeKeyboard && this.opts.resetKeyboard &&346          this.defaultIME) {347        logger.debug(`Resetting IME to '${this.defaultIME}'`);348        await this.adb.setIME(this.defaultIME);349      }350      if (this.opts.appPackage) {351        await this.adb.forceStop(this.opts.appPackage);352      }353      if (this.opts.fullReset && !this.opts.skipUninstall && !this.appOnDevice) {354        logger.debug(`FULL_RESET set to 'true', Uninstalling '${this.opts.appPackage}'`);355        await this.adb.uninstallApk(this.opts.appPackage);356      }357      await this.adb.stopLogcat();358      if (this.opts.reboot) {359        let avdName = this.opts.avd.replace('@', '');360        logger.debug(`closing emulator '${avdName}'`);361        await this.adb.killEmulator(avdName);362      }363      if (await this.adb.getApiLevel() >= 28) { // Android P364        logger.info('Restoring hidden api policy to the device default configuration');365        await this.adb.setDefaultHiddenApiPolicy();366      }367    }368    await super.deleteSession();369    if (this.opts.systemPort !== undefined) {...

Full Screen

Full Screen

general.js

Source:general.js Github

copy

Full Screen

...82commands.isAppInstalled = function (appPackage) {83  return this.adb.isAppInstalled(appPackage);84};85commands.removeApp = function (appPackage) {86  return this.adb.uninstallApk(appPackage);87};88commands.installApp = async function (appPath) {89  appPath = await this.helpers.configureApp(appPath, APP_EXTENSION);90  if (!(await fs.exists(appPath))) {91    log.errorAndThrow(`Could not find app apk at ${appPath}`);92  }93  let {apkPackage} = await this.adb.packageAndLaunchActivityFromManifest(appPath);94  let opts = {95    app: appPath,96    appPackage: apkPackage,97    fastReset: this.opts.fastReset98  };99  return androidHelpers.installApkRemotely(this.adb, opts);100};101commands.background = async function (seconds) {102  if (seconds < 0) {103    // if user passes in a negative seconds value, interpret that as the instruction104    // to not bring the app back at all105    await this.adb.goToHome();106    return true;107  }108  let {appPackage, appActivity} = await this.adb.getFocusedPackageAndActivity();109  await this.adb.goToHome();110  await B.delay(seconds * 1000);111  let args;112  if (this.opts.startActivityArgs && this.opts.startActivityArgs[`${appPackage}/${appActivity}`]) {113    // the activity was started with `startActivity`, so use those args to restart114    args = this.opts.startActivityArgs[`${appPackage}/${appActivity}`];115  } else if (appPackage === this.opts.appPackage && appActivity === this.opts.appActivity) {116    // the activity is the original session activity, so use the original args117    args = {118      pkg: appPackage,119      activity: appActivity,120      action: this.opts.intentAction,121      category: this.opts.intentCategory,122      flags: this.opts.intentFlags,123      waitPkg: this.opts.appWaitPackage,124      waitActivity: this.opts.appWaitActivity,125      optionalIntentArguments: this.opts.optionalIntentArguments,126      stopApp: false,127    };128  } else {129    // the activity was started some other way, so use defaults130    args = {131      pkg: appPackage,132      activity: appActivity,133      waitPkg: appPackage,134      waitActivity: appActivity,135      stopApp: false136    };137  }138  args = await util.filterObject(args);139  log.debug(`Bringing application back to foreground with arguments: ${JSON.stringify(args)}`);140  return await this.adb.startApp(args);141};142commands.getStrings = async function (language) {143  if (!language) {144    language = await this.adb.getDeviceLanguage();145    log.info(`No language specified, returning strings for: ${language}`);146  }147  if (this.apkStrings[language]) {148    // Return cached strings149    return this.apkStrings[language];150  }151  // TODO: This is mutating the current language, but it's how appium currently works152  this.apkStrings[language] = await androidHelpers.pushStrings(language, this.adb, this.opts);153  await this.bootstrap.sendAction('updateStrings');154  return this.apkStrings[language];155};156commands.launchApp = async function () {157  await this.initAUT();158  await this.startAUT();159};160commands.startActivity = async function (appPackage, appActivity,161                                         appWaitPackage, appWaitActivity,162                                         intentAction, intentCategory,163                                         intentFlags, optionalIntentArguments,164                                         dontStopAppOnReset) {165  log.debug(`Starting package '${appPackage}' and activity '${appActivity}'`);166  // dontStopAppOnReset is both an argument here, and a desired capability167  // if the argument is set, use it, otherwise use the cap168  if (!util.hasValue(dontStopAppOnReset)) {169    dontStopAppOnReset = !!this.opts.dontStopAppOnReset;170  }171  let args = {172    pkg: appPackage,173    activity: appActivity,174    waitPkg: appWaitPackage || appPackage,175    waitActivity: appWaitActivity || appActivity,176    action: intentAction,177    category: intentCategory,178    flags: intentFlags,179    optionalIntentArguments,180    stopApp: !dontStopAppOnReset181  };182  this.opts.startActivityArgs = this.opts.startActivityArgs || {};183  this.opts.startActivityArgs[`${appPackage}/${appActivity}`] = args;184  await this.adb.startApp(args);185};186commands.reset = async function () {187  if (this.opts.fullReset) {188    log.info("Running old fashion reset (reinstall)");189    await this.adb.stopAndClear(this.opts.appPackage);190    await this.adb.uninstallApk(this.opts.appPackage);191    await androidHelpers.installApkRemotely(this.adb, this.opts);192  } else {193    log.info("Running fast reset (stop and clear)");194    await this.adb.stopAndClear(this.opts.appPackage);195  }196  await this.grantPermissions();197  return await this.startAUT();198};199commands.startAUT = async function () {200  await this.adb.startApp({201    pkg: this.opts.appPackage,202    activity: this.opts.appActivity,203    action: this.opts.intentAction,204    category: this.opts.intentCategory,...

Full Screen

Full Screen

espresso-runner.js

Source:espresso-runner.js Github

copy

Full Screen

...49    ].includes(appState);50    if (shouldUninstallApp) {51      logger.info(`Uninstalling Espresso Test Server apk from the target device (pkg: '${TEST_APK_PKG}')`);52      try {53        await this.adb.uninstallApk(TEST_APK_PKG);54      } catch (err) {55        logger.warn(`Error uninstalling '${TEST_APK_PKG}': ${err.message}`);56      }57    }58    if (shouldInstallApp) {59      logger.info(`Installing Espresso Test Server apk from the target device (path: '${this.modServerPath}')`);60      try {61        await this.adb.install(this.modServerPath, { replace: false, timeout: this.androidInstallTimeout });62        logger.info(`Installed Espresso Test Server apk '${this.modServerPath}' (pkg: '${TEST_APK_PKG}')`);63      } catch (err) {64        logger.errorAndThrow(`Cannot install '${this.modServerPath}' because of '${err.message}'`);65      }66    }67  }68  async installTestApk () {69    let rebuild = this.forceEspressoRebuild;70    if (rebuild) {71      logger.debug(`'forceEspressoRebuild' capability is enabled`);72    } else if (await this.isAppPackageChanged()) {73      logger.info(`Forcing Espresso server rebuild because of changed application package`);74      rebuild = true;75    }76    if (rebuild && await fs.exists(this.modServerPath)) {77      logger.debug(`Deleting the obsolete Espresso server package '${this.modServerPath}'`);78      await fs.unlink(this.modServerPath);79    }80    if (!(await fs.exists(this.modServerPath))) {81      await this.buildNewModServer();82    }83    const isSigned = await this.adb.checkApkCert(this.modServerPath, TEST_APK_PKG);84    if (!isSigned) {85      await this.adb.sign(this.modServerPath);86    }87    if ((rebuild || !isSigned) && await this.adb.uninstallApk(TEST_APK_PKG)) {88      logger.info('Uninstalled the obsolete Espresso server package from the device under test');89    }90    await this.installServer();91  }92  async buildNewModServer () {93    logger.info(`Repackaging espresso server for: '${this.appPackage}'`);94    const packageTmpDir = path.resolve(this.tmpDir, this.appPackage);95    const newManifestPath = path.resolve(this.tmpDir, 'AndroidManifest.xml');96    await fs.rimraf(newManifestPath);97    logger.info(`Creating new manifest: '${newManifestPath}'`);98    await mkdirp(packageTmpDir);99    await fs.copyFile(TEST_MANIFEST_PATH, newManifestPath);100    await this.adb.compileManifest(newManifestPath, TEST_APK_PKG, this.appPackage); // creates a file `${newManifestPath}.apk`101    await this.adb.insertManifest(newManifestPath, TEST_APK_PATH, this.modServerPath); // copies from second to third and add manifest...

Full Screen

Full Screen

app-management.js

Source:app-management.js Github

copy

Full Screen

...84 * @returns {boolean} True if the package was found on the device and85 *                    successfully uninstalled.86 */87commands.removeApp = async function removeApp (appId, options = {}) {88  return await this.adb.uninstallApk(appId, options);89};90/**91 * @typedef {Object} TerminateOptions92 * @property {number|string} timeout [500] - The count of milliseconds to wait until the93 *                                           app is terminated.94 */95/**96 * Terminates the app if it is running.97 *98 * @param {string} appId - Application package identifier99 * @param {?TerminateOptions} options - The set of application termination options100 * @returns {boolean} True if the app has been successfully terminated.101 * @throws {Error} if the app has not been terminated within the given timeout.102 */...

Full Screen

Full Screen

uiautomator2.js

Source:uiautomator2.js Github

copy

Full Screen

...47      false);48    if (shouldUninstallServerPackages) {49      for (const {appId} of packagesInfo) {50        try {51          await this.adb.uninstallApk(appId);52        } catch (err) {53          logger.warn(`Error uninstalling '${appId}': ${err.message}`);54          logger.debug('Continuing');55        }56      }57    }58    for (const {appPath, appId} of packagesInfo) {59      await this.adb.installOrUpgrade(appPath, appId, {60        timeout: installTimeout,61      });62    }63    let retries = getRetries('Server install', installTimeout, SERVER_INSTALL_RETRIES);64    logger.debug(`Waiting up to ${retries * 1000}ms for instrumentation '${INSTRUMENTATION_TARGET}' to be available`);65    let output;...

Full Screen

Full Screen

selendroid.js

Source:selendroid.js Github

copy

Full Screen

...34    }35    needsUninstall = await this.checkAndSignCert(this.modServerPath) || needsUninstall;36    if (needsUninstall) {37      logger.info('New server was built, uninstalling any instances of it');38      await this.adb.uninstallApk(this.modServerPkg);39    }40  }41  async installModifiedServer () {42    let installed = await this.adb.isAppInstalled(this.modServerPkg);43    if (!installed) {44      await this.adb.install(this.modServerPath);45    }46  }47  async buildNewModServer () {48    logger.info(`Repackaging selendroid for: '${this.appPackage}'`);49    let packageTmpDir = path.resolve(this.tmpDir, this.appPackage);50    let newManifestPath = path.resolve(this.tmpDir, 'AndroidManifest.xml');51    logger.info(`Creating new manifest: '${newManifestPath}'`);52    await fs.mkdir(packageTmpDir);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Appium = require('appium');2var AndroidDriver = Appium.AndroidDriver;3var ADB = require('appium-adb');4var adb = new ADB();5var driver = new AndroidDriver(adb);6driver.uninstallApk('com.example.app');7var Appium = require('appium');8var AndroidDriver = Appium.AndroidDriver;9var ADB = require('appium-adb');10var adb = new ADB();11var driver = new AndroidDriver(adb);12driver.uninstallApk('com.e

Full Screen

Using AI Code Generation

copy

Full Screen

1AndroidHelpers.prototype.uninstallApk = async function (pkg) {2  await this.adb.uninstallApk(pkg);3};4AndroidHelpers.prototype.installApk = async function (apk, replace = false, timeout = 60000) {5  await this.adb.install(apk, replace, timeout);6};7methods.uninstallApk = async function (pkg) {8  log.debug(`Uninstalling ${pkg}`);9  await this.initAapt();10  let apkInfo = await this.getApkInfo(pkg);11  if (apkInfo) {12    await this.shell(['pm', 'uninstall', pkg]);13    await this.initAapt();14    apkInfo = await this.getApkInfo(pkg);15    if (apkInfo) {16      log.errorAndThrow(`Error executing adbExec. Original error: 'Failure [DELETE_FAILED_INTERNAL_ERROR]'; ` +17Error: 'pm install-delete' failed`);18    }19  } else {20    log.debug(`App was not uninstalled, because it wasn't present on device`);21  }22};23methods.install = async function (apk, replace = false, timeout = 60000) {24  if (!await fs.exists(apk)) {25    log.errorAndThrow(`Could not find apk at ${apk}`);26  }27  if (replace) {28    log.debug(`Replacing apk with ${apk}`);29    await this.uninstallApk(await this.packageFromManifest(apk));30  }31  log.debug(`Installing ${apk}`);32  await this.initAapt();33  await this.adbExec(['install', '-r', apk], {timeout});34};35methods.initAapt = async function () {36  if (!this.aapt) {37    this.aapt = await this.getAaptBinaryPath();38  }39};40methods.getAaptBinaryPath = async function () {41  let aaptPath = await this.getAaptPath();42  if (!aaptPath) {43    log.warn('Could not find aapt

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var fs = require('fs');4var path = require('path');5var Q = require('q');6var _ = require('underscore');7var _ = require('underscore');8var Appium = require('appium');9var AppiumServer = Appium.main;10var appiumServer = new AppiumServer(4723);11var appiumStarted = false;

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var Appium = require('appium');4var appium = new Appium();5var desiredCaps = {6  };7var driver = wd.remote("localhost", 4723);8driver.init(desiredCaps, function() {9  driver.uninstallApk("com.example.app", function(err) {10    if(err) {11       console.log(err);12    }13    else {14       console.log("Uninstalled Successfully");15    }16  });17});

Full Screen

Using AI Code Generation

copy

Full Screen

1var ADB = require('appium-adb');2var adb = new ADB();3adb.uninstallApk("com.android.chrome", function(err) {4if (err) {5console.log("Error in uninstalling apk");6} else {7console.log("Apk uninstalled successfully");8}9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumAndroidDriver = require('appium-android-driver');2var driver = new AppiumAndroidDriver();3driver.adb.uninstallApk('com.example.app');4var AppiumAndroidDriver = require('appium-android-driver');5var driver = new AppiumAndroidDriver();6driver.adb.uninstallApk('com.example.app');7public void testGetMessage(){8    String message = "Hello World!";9    MyClass myClass = new MyClass();10    Assert.assertEquals(message, myClass.getMessage());11}12However, this test case fails because the getMessage() method returns a different String. I want to test this method. How can I do this?13public void testGetMessage(){14    String message = "Hello World!";15    MyClass myClass = new MyClass();16    Assert.assertEquals(message, myClass.getMessage());17}18However, this test case fails because the getMessage() method returns a different String. I want to test this method. How can I do this?19public void testCalculator() throws Exception {20    DesiredCapabilities capabilities = new DesiredCapabilities();21    capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");22    capabilities.setCapability(MobileCapabilityType.PLATFORM, "Android");23    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");24    capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "6.0");25    capabilities.setCapability("appPackage", "com.android.calculator2");26    capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

Full Screen

Using AI Code Generation

copy

Full Screen

1class AndroidDriver extends AppiumDriver {2}3class AppiumDriver extends BaseDriver {4}5class BaseDriver extends Driver {6}7class Driver extends BasePlugin {8}9class BasePlugin extends EventEmitter {10}

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