How to use adbCmd method in root

Best JavaScript code snippet using root

ADB.js

Source:ADB.js Github

copy

Full Screen

...10 this._cachedApiLevels = new Map();11 this.adbBin = path.join(Environment.getAndroidSDKPath(), 'platform-tools', 'adb');12 }13 async devices() {14 const output = (await this.adbCmd('', 'devices')).stdout;15 return this.parseAdbDevicesConsoleOutput(output);16 }17 async unlockScreen(deviceId) {18 const {19 mWakefulness,20 mUserActivityTimeoutOverrideFromWindowManager,21 } = await this._getPowerStatus(deviceId);22 if (mWakefulness === 'Asleep') {23 await this.pressPowerDevice(deviceId);24 }25 if (mUserActivityTimeoutOverrideFromWindowManager === '10000') { // screen is locked26 await this.pressOptionsMenu(deviceId);27 }28 }29 async _getPowerStatus(deviceId) {30 const stdout = await this.shell(deviceId, `dumpsys power | grep "^[ ]*m[UW].*="`);31 return stdout32 .split('\n')33 .map(s => s.trim().split('='))34 .reduce((acc, [key, value]) => ({35 ...acc,36 [key]: value,37 }), {});38 }39 async pressOptionsMenu(deviceId) {40 await this._sendKeyEvent(deviceId, 'KEYCODE_MENU');41 }42 async pressPowerDevice(deviceId) {43 await this._sendKeyEvent(deviceId, 'KEYCODE_POWER');44 }45 async _sendKeyEvent(deviceId, keyevent) {46 await this.shell(deviceId, `input keyevent ${keyevent}`);47 }48 async parseAdbDevicesConsoleOutput(input) {49 const outputToList = input.trim().split('\n');50 const devicesList = _.takeRight(outputToList, outputToList.length - 1);51 const devices = [];52 for (const deviceString of devicesList) {53 const deviceParams = deviceString.split('\t');54 const deviceAdbName = deviceParams[0];55 let device;56 if (this.isEmulator(deviceAdbName)) {57 const port = _.split(deviceAdbName, '-')[1];58 const telnet = new EmulatorTelnet();59 await telnet.connect(port);60 const name = await telnet.avdName();61 device = {type: 'emulator', name: name, adbName: deviceAdbName, port: port};62 await telnet.quit();63 } else if (this.isGenymotion(deviceAdbName)) {64 device = {type: 'genymotion', name: deviceAdbName, adbName: deviceAdbName};65 } else {66 device = {type: 'device', name: deviceAdbName, adbName: deviceAdbName};67 }68 devices.push(device);69 }70 return devices;71 }72 isEmulator(deviceAdbName) {73 return _.includes(deviceAdbName, 'emulator-');74 }75 isGenymotion(string) {76 return (/^((1?\d?\d|25[0-5]|2[0-4]\d)(\.|:)){4}[0-9]{4}/.test(string));77 }78 async now(deviceId) {79 return this.shell(deviceId, `date +"%m-%d %T.000"`);80 }81 async isPackageInstalled(deviceId, packageId) {82 const output = await this.shell(deviceId, `pm list packages ${packageId}`);83 const packageRegexp = new RegExp(`^package:${escape.inQuotedRegexp(packageId)}$`, 'm');84 const isInstalled = packageRegexp.test(output);85 return isInstalled;86 }87 async install(deviceId, apkPath) {88 const apiLvl = await this.apiLevel(deviceId);89 let childProcess;90 if (apiLvl >= 24) {91 childProcess = await this.adbCmd(deviceId, `install -r -g -t ${apkPath}`);92 } else {93 childProcess = await this.adbCmd(deviceId, `install -rg ${apkPath}`);94 }95 const [failure] = (childProcess.stdout || '').match(/^Failure \[.*\]$/m) || [];96 if (failure) {97 throw new DetoxRuntimeError({98 message: `Failed to install app on ${deviceId}: ${apkPath}`,99 debugInfo: failure,100 });101 }102 }103 async uninstall(deviceId, appId) {104 await this.adbCmd(deviceId, `uninstall ${appId}`);105 }106 async terminate(deviceId, appId) {107 await this.shell(deviceId, `am force-stop ${appId}`);108 }109 async pidof(deviceId, bundleId) {110 const bundleIdRegex = escape.inQuotedRegexp(bundleId) + '$';111 const processes = await this.shell(deviceId, `ps | grep "${bundleIdRegex}"`).catch(() => '');112 if (!processes) {113 return NaN;114 }115 return parseInt(processes.split(' ').filter(Boolean)[1], 10);116 }117 async getFileSize(deviceId, filename) {118 const { stdout, stderr } = await this.adbCmd(deviceId, 'shell du ' + filename).catch(e => e);119 if (stderr.includes('No such file or directory')) {120 return -1;121 }122 return Number(stdout.slice(0, stdout.indexOf(' ')));123 }124 async isBootComplete(deviceId) {125 try {126 const bootComplete = await this.shell(deviceId, `getprop dev.bootcomplete`, { silent: true });127 return (bootComplete === '1');128 } catch (ex) {129 return false;130 }131 }132 async apiLevel(deviceId) {133 if (this._cachedApiLevels.has(deviceId)) {134 return this._cachedApiLevels.get(deviceId);135 }136 const lvl = Number(await this.shell(deviceId, `getprop ro.build.version.sdk`));137 this._cachedApiLevels.set(deviceId, lvl);138 return lvl;139 }140 async screencap(deviceId, path) {141 await this.shell(deviceId, `screencap ${path}`);142 }143 /***144 * @returns ChildProcessPromise145 */146 screenrecord(deviceId, { path, size, bitRate, timeLimit, verbose }) {147 const [ width = 0, height = 0 ] = size || [];148 const _size = (width > 0) && (height > 0)149 ? ['--size', `${width}x${height}`]150 : [];151 const _bitRate = (bitRate > 0)152 ? ['--bit-rate', String(bitRate)]153 : [];154 const _timeLimit = (timeLimit > 0)155 ? [`--time-limit`, timeLimit]156 : [];157 const _verbose = verbose ? ['--verbose'] : [];158 const screenRecordArgs = [..._size, ..._bitRate, ..._timeLimit, ..._verbose, path];159 return this.spawn(deviceId, ['shell', 'screenrecord', ...screenRecordArgs]);160 }161 /***162 * @returns ChildProcessPromise163 */164 logcat(deviceId, { file, pid, time }) {165 let shellCommand = 'logcat';166 // HACK: cannot make this function async, otherwise ChildProcessPromise.childProcess field will get lost,167 // and this will break interruptProcess() call for any logcat promise.168 const apiLevel = this._cachedApiLevels.get(deviceId);169 if (time && apiLevel >= 21) {170 shellCommand += ` -T "${time}"`;171 }172 if (apiLevel < 24) {173 if (pid > 0) {174 const __pid = String(pid).padStart(5);175 shellCommand += ` -v brief | grep "(${__pid}):"`;176 }177 if (file) {178 shellCommand += ` >> ${file}`;179 }180 } else {181 if (pid > 0) {182 shellCommand += ` --pid=${pid}`;183 }184 if (file) {185 shellCommand += ` -f ${file}`;186 }187 }188 return this.spawn(deviceId, ['shell', shellCommand]);189 }190 async pull(deviceId, src, dst = '') {191 await this.adbCmd(deviceId, `pull "${src}" "${dst}"`);192 }193 async rm(deviceId, path, force = false) {194 await this.shell(deviceId, `rm ${force ? '-f' : ''} "${path}"`);195 }196 async listInstrumentation(deviceId) {197 return this.shell(deviceId, 'pm list instrumentation');198 }199 async getInstrumentationRunner(deviceId, bundleId) {200 const instrumentationRunners = await this.listInstrumentation(deviceId);201 const instrumentationRunner = this._instrumentationRunnerForBundleId(instrumentationRunners, bundleId);202 if (instrumentationRunner === 'undefined') {203 throw new Error(`No instrumentation runner found on device ${deviceId} for package ${bundleId}`);204 }205 return instrumentationRunner;206 }207 _instrumentationRunnerForBundleId(instrumentationRunners, bundleId) {208 const runnerForBundleRegEx = new RegExp(`^instrumentation:(.*) \\(target=${bundleId.replace(new RegExp('\\.', 'g'), "\\.")}\\)$`, 'gm');209 return _.get(runnerForBundleRegEx.exec(instrumentationRunners), [1], 'undefined');210 }211 async shell(deviceId, cmd, options) {212 return (await this.adbCmd(deviceId, `shell "${escape.inQuotedString(cmd)}"`, options)).stdout.trim();213 }214 async adbCmd(deviceId, params, options) {215 const serial = `${deviceId ? `-s ${deviceId}` : ''}`;216 const cmd = `${this.adbBin} ${serial} ${params}`;217 const retries = _.get(options, 'retries', 1);218 _.unset(options, 'retries');219 return execWithRetriesAndLogs(cmd, options, undefined, retries);220 }221 /***222 * @returns {ChildProcessPromise}223 */224 spawn(deviceId, params) {225 const serial = deviceId ? ['-s', deviceId] : [];226 return spawnAndLog(this.adbBin, [...serial, ...params]);227 }228}...

Full Screen

Full Screen

generate_device_package_list.js

Source:generate_device_package_list.js Github

copy

Full Screen

1var spawn = require('child_process').spawnSync;2var EOL = require('os').EOL;3var fs = require('fs');4var adbCmd = spawn( 'adb', [ 'shell', 'cmd', 'package list packages -s -f'] );5var packages = [];6if(adbCmd.stderr.toString()) {7 throw adbCmd.stderr.toString();8}9adbCmd.stdout.toString().trim().split(EOL).sort().forEach(function (adbOut) {10 var appSplit = adbOut.replace('package:/system/', '')11 .replace('=', '/')12 .split('/');13 packages.push({14 //dir: appSplit[0],15 name: (appSplit[0] === 'framework' ? appSplit[1] : appSplit[1].replace('.apk', '')),16 // apk: appSplit[2],17 packageName: (appSplit[0] === 'framework' ? appSplit[2] : appSplit[3]),18 });19});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('adbkit');2var root = require('./root.js');3var client = adb.createClient();4client.listDevices()5 .then(function(devices) {6 return Promise.map(devices, function(device) {7 return client.shell(device.id, 'su -c "getprop ro.build.version.release"')8 .then(adb.util.readAll)9 .then(function(output) {10 console.log('[%s] %s', device.id, output.toString().trim());11 });12 });13 })14 .catch(function(err) {15 console.error('Something went wrong:', err.stack);16 });17 at ChildProcess.exithandler (child_process.js:204:12)18 at emitTwo (events.js:87:13)19 at ChildProcess.emit (events.js:172:7)20 at maybeClose (internal/child_process.js:818:16)21 at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)22 at Client._shell (/home/sam/Desktop/adbkit/node_modules/adbkit/lib/adb/client.js:314:10)23 at Client.shell (/home/sam/Desktop/adbkit/node_modules/adbkit/lib/adb/client.js:291:17)24 at tryCatcher (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/util.js:16:23)25 at Promise._settlePromiseFromHandler (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/promise.js:504:31)26 at Promise._settlePromise (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/promise.js:561:18)27 at Promise._settlePromise0 (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/promise.js:606:10)28 at Promise._settlePromises (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/promise.js:685:18)29 at Async._drainQueue (/home/sam/Desktop/adbkit/node_modules/bluebird/js/release/async.js:138:

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('./root.js');2var cmd = 'ls';3adb.adbCmd(cmd, function(error, stdout, stderr) {4 console.log('stdout: ' + stdout);5 console.log('stderr: ' + stderr);6 if (error !== null) {7 console.log('exec error: ' + error);8 }9});10var adb = require('./root.js');11var cmd = 'ls /sdcard';12adb.adbCmd(cmd, function(error, stdout, stderr) {13 console.log('stdout: ' + stdout);14 console.log('stderr: ' + stderr);15 if (error !== null) {16 console.log('exec error: ' + error);17 }18});19var adb = require('./root.js');20var cmd = 'ls /sdcard';21adb.adbCmd(cmd, function(error, stdout, stderr) {22 console.log('stdout: ' + stdout);23 console.log('stderr: ' + stderr);24 if (error !== null) {25 console.log('exec error: ' + error);26 }27});

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2root.adbCmd('devices', function(err, data) {3 if (err) {4 console.log('Error: ' + err);5 } else {6 console.log('Data: ' + data);7 }8});9var exec = require('child_process').exec;10exports.adbCmd = function(cmd, callback) {11 var cmd = 'adb ' + cmd;12 exec(cmd, function(err, data) {13 if (err) {14 callback(err, null);15 } else {16 callback(null, data);17 }18 });19};

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2root.adbCmd("devices", function(data) {3 console.log(data);4});5var exec = require('child_process').exec;6var adbCmd = function(cmd, callback) {7 exec("adb " + cmd, function(error, stdout, stderr) {8 callback(stdout);9 });10};11exports.adbCmd = adbCmd;

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2var adbCmd = root.adbCmd;3adbCmd('devices', function(data){4 console.log(data);5});6 console.log(data);7});8adbCmd('shell input keyevent 3', function(data){9 console.log(data);10});11adbCmd('shell input keyevent 4', function(data){12 console.log(data);13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2root.adbCmd('adb devices', function (data) {3 console.log('Output: ' + data);4});5exports.adbCmd = function (cmd, callback) {6 var exec = require('child_process').exec;7 exec(cmd, function (error, stdout, stderr) {8 callback(stdout);9 });10};

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('./root');2adb.adbCmd('shell ls -l', function(data) {3 console.log(data);4});5var exec = require('child_process').exec;6var adbCmd = function(cmd, callback) {7 exec('adb ' + cmd, function(error, stdout, stderr) {8 callback(stdout);9 });10};11exports.adbCmd = adbCmd;

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('./root');2adb.adbCmd('shell ls -l', function(data) {3 console.log(data);4});5var exec = require('child_process').exec;6var adbCmd = function(cmd, callback) {7 exec('adb ' + cmd, function(error, stdout, stderr) {8 callback(stdout);9 });10};11exports.adbCmd = adbCmd;

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 root 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