How to use avdName method in root

Best JavaScript code snippet using root

android.js

Source:android.js Github

copy

Full Screen

1var path = require('path'),2 async = require('async'),3 xml2js = require('xml2js'),4 net = require('net'),5 fs = require('fs'),6 pc = require('path-complete'),7 prompt = require('prompt'),8 spawn = require('child_process').spawn,9 exec = require('child_process').exec,10 constants = require('../support/constants'),11 logger,12 __self;13//############## MODULE INTERFACE ################//14function Android(options) {15 __self = this;16 logger = options.logger;17 var sdkPath = options.androidPath || '';18 this.paths = {19 sdk: sdkPath,20 adb: path.join(sdkPath, 'platform-tools', 'adb'),21 android: path.join(sdkPath, 'tools', 'android'),22 ddms: path.join(sdkPath, 'tools', 'ddms'),23 emulator: path.join(sdkPath, 'tools', 'emulator'),24 titanium: options.titaniumPath25 };26 this.titanium = {27 build: titaniumBuild,28 configure: titaniumConfigure,29 deploy: titaniumDeploy,30 run: titaniumRun31 }32 this.adb = {33 restart: adbRestart,34 devices: adbDevices,35 installApp: adbInstallApp,36 runApp: adbRunApp37 }38 this.avd = {39 exists: avdExists,40 running: avdRunning,41 create: avdCreate,42 start: avdStart,43 getSerial: avdGetSerial44 }45 this.getClassNameFromManifest = getClassNameFromManifest;46};47module.exports = Android;48//############## PRIVATE FUNCTIONS ######################//49var titaniumConfigure = function(options, props, callback) {50 prompt.start();51 prompt.get([52 {53 message:"Do you have the Android SDK installed already? [(y)es/(n)o/(s)kip]",54 name:"doAndroid"55 }56 ],57 function(err, result) {58 if (err) {59 logger.error(err);60 callback(err);61 } else if (/^y/i.test(result.doAndroid)) {62 process.stdout.write('Android SDK Path: ');63 pc.getPathFromStdin((props.androidSDKPath || ''), function(aPath) {64 try {65 if (fs.statSync(aPath).isDirectory() && 66 path.existsSync(path.join(aPath, 'platform-tools', 'adb'))67 ) {68 logger.debug('Android SDK Path: ' + aPath);69 props.androidSDKPath = aPath;70 callback();71 } else {72 throw 'not found';73 }74 } catch (e) {75 logger.error('Android SDK not found at "' + aPath + '"');76 titaniumConfigure(options, props, callback); 77 }78 });79 } else if (/^n/i.test(result.doAndroid)) {80 logger.info('Download and install the Android SDK from this URL:');81 logger.info('');82 logger.info(' http://developer.android.com/sdk/index.html');83 logger.info('');84 logger.info('Then try running `titanium configure android` again to configure for Android development');85 callback();86 } else if (/^s/i.test(result.doAndroid)) {87 callback();88 } else {89 logger.error('Invalid response, try again.');90 titaniumConfigure(options, props, callback);91 }92 });93};94var titaniumBuild = function(options, tiapp, callback) {95 try {96 logger.debug('Building Android app.apk for ' + tiapp.name)97 var tiBuilderPath = path.join(__self.paths.titanium, options.sdk, 'android', 'builder.py');98 exec(constants.PYTHON + ' "' + tiBuilderPath + '" build ' + tiapp.name + ' "' + __self.paths.sdk + '" "' + options.path + '" ' + tiapp.id, 99 function(err, stdout, stderr) {100 var errMsg = '';101 if (err) {102 errMsg = err;103 stdout.split('\n').forEach(function(line) {104 if (/^\[ERROR\]/.test(line)) {105 errMsg += line + '\n';106 }107 });108 logger.error('Failed to build Android project');109 logger.error(errMsg);110 callback(errMsg);111 } else {112 logger.debug('Android project has been built');113 callback();114 }115 }116 );117 } catch (e) {118 logger.error('Failed to build Android project');119 logger.error(e);120 callback(e);121 }122};123var titaniumDeploy = function(options, tiapp, deployCallback) {124 var buildPath = path.join(options.path, 'build', 'android'),125 apkPath = path.join(buildPath, 'bin', 'app.apk'),126 manifestPath = path.join(buildPath, 'AndroidManifest.xml'),127 className = null,128 serial = null;129 logger.debug('Deploying ' + tiapp.name + ' to Android device...');130 async.parallel([131 // build apk132 function(parallelCallback) {133 async.series([134 // build apk, if necessary135 function(callback) {136 if (options.nobuild) {137 callback(); 138 } else {139 titaniumBuild(options, tiapp, function(err) {140 callback(err);141 });142 }143 },144 // get the app's classname145 function(callback) {146 logger.debug('Finding AndroidManifest.xml class name for ' + tiapp.name);147 getClassNameFromManifest(manifestPath, function(err, _className) {148 className = _className;149 if (className !== null) {150 logger.debug('Found ' + tiapp.name + ' class name: ' + className);151 }152 callback();153 });154 }155 ],156 function(err, result) {157 parallelCallback(err); 158 });159 },160 // Find the connected device161 function(parallelCallback) {162 logger.debug('Finding connected Android devices');163 adbDevices(function(err, devices) {164 if (err) {165 parallelCallback(err);166 return;167 }168 for (var i = 0; i < devices.length; i++) {169 var device = devices[i];170 if (device.type === 'device' &&171 (!options.androidSerial || options.androidSerial === device.serial)) {172 serial = device.serial;173 logger.debug('Android device found: (' + serial + ')');174 break;175 }176 }177 if (serial === null) {178 err = 'Unable to find any connected Android devices';179 }180 parallelCallback(err);181 });182 }183 ], 184 function(err, result) {185 // built apk and found device, now install and run apk186 if (err) { 187 deployCallback(err);188 return;189 }190 async.series([191 // deploy app.apk to device 192 function(callback) {193 logger.debug('Installing ' + tiapp.name + ' to ' + serial);194 adbInstallApp(apkPath, serial, function(err) {195 if (!err) { logger.debug('Application ' + tiapp.name + ' successfully installed to ' + serial); }196 callback(err);197 });198 },199 // run app on device200 function(callback) {201 if (className && !options.noRun) {202 adbRunApp(serial, tiapp.id, className, function(err) {203 if (!err) { logger.debug('Application ' + tiapp.name + ' should now be running on your Android device'); }204 callback(err);205 });206 } else {207 logger.info('Application installed. You can now run it from the Android device.');208 callback();209 }210 }211 ],212 function(err, result) {213 deployCallback(err);214 });215 });216};217var titaniumRun = function(options, tiapp, callback) {218 var buildPath = path.join(options.path, 'build', 'android'),219 apkPath = path.join(buildPath, 'bin', 'app.apk'),220 manifestPath = path.join(buildPath, 'AndroidManifest.xml');221 // Establish avd name, or create one from a target id and skin222 // TODO: Validate targets and skins223 var noAvdOptions = !options.avdTargetId && !options.avdSkin && !options.avdName;224 options.avdTargetId = options.avdTargetId || constants.RUN_AVD_TARGET;225 options.avdSkin = options.avdSkin || constants.RUN_AVD_SKIN;226 var avdName = options.avdName || [constants.RUN_AVD_PREFIX, options.avdTargetId, options.avdSkin].join('_'),227 doesAvdExist = false,228 serial, 229 className;230 // build apk and run on emulator231 async.parallel([ 232 // build apk, if necessary233 function(parallelCallback) {234 async.series([235 // build apk, if necessary236 function(callback) {237 if (options.nobuild) {238 callback(); 239 } else {240 titaniumBuild(options, tiapp, function(err) {241 callback(err);242 });243 }244 },245 function(callback) {246 logger.debug('Searching for app class name in AndroidManifest.xml');247 getClassNameFromManifest(manifestPath, function(err, _className) {248 className = _className;249 if (className !== null) {250 logger.debug('Found app class name: ' + className);251 }252 callback(err);253 });254 }255 ],256 function(err, result) {257 parallelCallback(err);258 });259 },260 // Make sure we have an appropriate emulator running261 function(parallelCallback) {262 async.series([263 // Restart adb264 function(callback) { 265 if (options.restartAdb) {266 logger.debug('Restarting adb...');267 adbRestart(function(err) { callback(err); });268 } else {269 callback();270 }271 },272 // See if we can us an emulator that's already open273 function(callback) {274 if (noAvdOptions) {275 adbDevices(function(err, devices) {276 if (err) {277 logger.error(err);278 } else if (devices) {279 for (var i = 0; i < devices.length; i++) {280 if (devices[i].type === 'emulator') {281 doesAvdExist = true;282 avdName = devices[i].name;283 serial = devices[i].serial;284 break;285 }286 }287 }288 callback();289 });290 } else {291 callback();292 }293 },294 // Make sure the given AVD name exists295 function(callback) {296 // Do we already know the AVD exists?297 if (doesAvdExist) {298 callback();299 return;300 }301 // Check the given AVD parameters, or try the default302 logger.debug('Making sure AVD "' + avdName + '" exists');303 avdExists(avdName, function(exists) {304 if (exists) {305 doesAvdExist = true;306 callback();307 } else {308 if (options.avdName) {309 callback('Invalid AVD name "' + avdName + '"');310 } else {311 logger.debug('Couldn\'t find AVD with target "' + options.avdTargetId + '" and skin "' + options.avdSkin + '", creating a new one...');312 callback();313 }314 }315 })316 },317 // Create AVD if it doesn't exist318 function(callback) {319 if (!doesAvdExist) {320 avdCreate(avdName, options.avdTargetId, options.avdSkin, function(err) {321 callback(err);322 });323 } else {324 callback();325 }326 },327 // Make sure the AVD is running328 function(callback) {329 // Do we already have the serial number?330 if (serial) {331 callback();332 return;333 }334 logger.debug('Checking to see if "' + avdName + '" is already running...');335 avdRunning(avdName, function(isRunning, _serial) {336 serial = _serial;337 if (!isRunning) {338 logger.debug('Starting AVD "' + avdName + '"');339 avdStart(340 avdName, 341 function(_serial) {342 if (_serial === null) {343 callback('Could not find serial number for AVD "' + avdName + '"');344 } else {345 logger.debug('AVD "' + avdName + '" serial number is ' + _serial);346 serial = _serial;347 callback();348 }349 },350 function(msg) {351 logger.debug(msg);352 }353 );354 } else {355 logger.debug('AVD "' + avdName + '" serial number is ' + _serial);356 callback();357 }358 });359 }360 ],361 function(err, results) {362 if (!err) {363 logger.debug('AVD "' + avdName + '" should be running');364 }365 parallelCallback(err);366 });367 }368 ],369 // If err === null, the APK has been built and we have an emulator running370 function(err, result) {371 if (err) {372 logger.error(err);373 } else {374 async.series([375 // Install the APK to the AVD376 function(callback) {377 logger.debug('Installing app.apk to "' + avdName + '"...');378 adbInstallApp(apkPath, serial, function(err) {379 callback(err);380 });381 },382 // Run the APK from the AVD383 function(callback) {384 if (!className) {385 callback('Unable to find class name in "' + manifestPath + '". You need to start the app manually.');386 callback();387 } else {388 logger.debug('Launching app.apk in AVD "' + avdName + '"...');389 adbRunApp(serial, tiapp.id, className, function(err) {390 callback(err);391 });392 } 393 }394 ],395 function(err, result) {396 if (err) {397 logger.error(err);398 } else {399 if (className) {400 logger.info('Application "' + tiapp.name + '" is now running on AVD "' + avdName + '"');401 } else {402 logger.info('Application installed. You can now run it from the application menu.');403 }404 }405 });406 }407 });408};409var adbRestart = function(callback) {410 async.series([411 // kill any running adb server412 // TODO: sometimes even the kill-server call hangs. We probably need to kill the adb413 // process to ensure this works after a certain period of time. 414 // win32: tskill adb415 // linux & darwin: killall adb416 function(asyncCallback) {417 exec(__self.paths.adb + ' kill-server', function() { asyncCallback(); });418 },419 // start the adb server420 function(asyncCallback) {421 exec(__self.paths.adb + ' start-server', function() { asyncCallback(); });422 }423 ],424 function(err, result) {425 if (callback) { callback(err); } 426 });427};428var adbDevices = function(callback) {429 exec(__self.paths.adb + ' devices', function(err, stdout, stderr) {430 if (err !== null) {431 callback(err);432 } else {433 var devices = [],434 matches,435 items;436 // parse the output of `adb devices` to find a list of437 // all connected AVDs and devices438 stdout.split('\n').forEach(function(line) {439 if (matches = line.match(/^\s*([^\s]+)\s+([^\s]+)\s*$/)) {440 var device = {441 serial:matches[1], 442 status:matches[2]443 };444 if (items = device.serial.match(/^emulator\-(\d+)$/)) {445 device.type = 'emulator';446 device.port = items[1];447 } else {448 device.type = 'device';449 }450 devices.push(device);451 }452 });453 // construct a parallel set of function to get the avd name454 // of all running emulators via telnet455 var functions = [];456 devices.forEach(function(device) {457 if (device.type === 'emulator') {458 functions.push(function(parallelCallback) {459 getAvdNameWithDevice(device, function() {460 parallelCallback();461 });462 });463 }464 });465 async.parallel(functions, function(err, result) {466 callback(null, devices);467 });468 }469 });470};471var adbInstallApp = function(apk, serial, callback, tries) {472 var wait = 2000;473 var maxTries = 10;474 tries = tries || 0;475 exec(__self.paths.adb + ' -s ' + serial + ' wait-for-device install -r ' + '"' + apk + '"', function(err, stdout, stderr) {476 tries++;477 if (/(?:(^failure|^error))/i.test(stdout)) {478 err = stdout;479 if (/could not access the package manager/i.test(stdout)) {480 if (tries > maxTries) {481 callback('Timeout when trying to install "' + apk + '" to Android avd/device "' + serial + '"');482 } else {483 logger.debug('Android avd/device not yet ready for app install, waiting a few more seconds...');484 setTimeout(function() {485 __self.adb.installApp(apk, serial, callback, tries);486 }, wait);487 }488 return;489 }490 }491 callback(err);492 });493};494var adbRunApp = function(serial, appid, className, callback) {495 var appField = appid + '/' + appid + className;496 var maxTries = 30;497 var wait = 2000;498 var tries = 0;499 var waitForDevice = function() {500 tries++;501 if (tries >= maxTries) {502 callback('Timeout waiting for device to get ready for app launch');503 }504 exec(__self.paths.adb + ' -s ' + serial + ' shell ps', function(err, stdout, stderr) {505 if (/(?:(android\.process\.acore|com\.android\.launcher))/i.test(stdout)) {506 exec(__self.paths.adb + ' -s ' + serial + ' shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n ' + appField, function(err, stdout, stderr) {507 callback(err);508 });509 } else {510 setTimeout(waitForDevice, wait);511 }512 });513 };514 setTimeout(waitForDevice, wait);515};516var avdExists = function(avdName, callback) {517 path.exists(getAndroidAvdPath(avdName + '.ini'), callback);518};519var avdRunning = function(avdName, callback) {520 var isRunning = false,521 serial = null;522 adbDevices(function(err, devices) {523 if (err) {524 callback(false);525 } else {526 devices.forEach(function(device) {527 if (device.name === avdName) {528 isRunning = true;529 serial = device.serial;530 }531 });532 callback(isRunning, serial);533 }534 });535};536var avdCreate = function(avdName, targetId, skin, callback) { 537 exec('echo no | ' + __self.paths.android + ' create avd -n ' + avdName + ' -t ' + targetId + ' -s ' + skin, function(err, stdout, stderr) {538 callback(err);539 });540};541var avdStart = function(avdName, callback) {542 // TODO: How do I get the android emulator to launch in the background and 543 // not take over the command line? Ampersand doesn't seem to be544 // working.545 spawn(__self.paths.emulator, ['-avd', avdName, '-no-boot-anim']);546 547 if (callback) {548 var maxTries = 8;549 var wait = 2000;550 var tries = 0;551 var didAdbRestart = false;552 var lookForSerial = function() {553 tries++;554 if (tries >= maxTries) {555 if (!didAdbRestart) {556 tries = 0;557 didAdbRestart = true;558 logger.debug('Couldn\'t find serial number. Restarting adb and trying again.');559 __self.adb.restart(function() {560 setTimeout(lookForSerial, wait);561 });562 } else {563 callback(null);564 }565 return;566 }567 logger.debug('Try #' + tries + ' to find serial number for AVD "' + avdName + '"...');568 avdGetSerial(avdName, function(serial) {569 if (serial === null) {570 setTimeout(lookForSerial, wait);571 } else {572 callback(serial);573 }574 });575 };576 setTimeout(lookForSerial, wait);577 }578};579var avdGetSerial = function(avdName, callback) {580 var serial = null;581 adbDevices(function(err, devices) {582 devices.forEach(function(device) {583 if (device.name === avdName) {584 serial = device.serial;585 }586 });587 callback(serial);588 });589};590var getClassNameFromManifest = function(manifestPath, callback) {591 var className = null;592 var parser = new xml2js.Parser({593 explicitArray:true594 });595 fs.readFile(manifestPath, function(err, data) {596 if (err) { callback(err); return; }597 parser.parseString(data, function (err, result) {598 if (err) { callback(err); return; }599 var acts = result['application'][0]['activity'];600 acts.forEach(function(act) {601 var intents = act['intent-filter']; 602 if (intents) {603 intents.forEach(function(intent) {604 try {605 if (intent['action'][0]['@']['android:name'] === 'android.intent.action.MAIN') {606 intent['category'].forEach(function(category) {607 if (category['@'] && 608 category['@']['android:name'] == 'android.intent.category.LAUNCHER') {609 className = act['@']['android:name'];610 }611 });612 }613 } catch (e) {}614 });615 }616 });617 callback(null, className);618 });619 });620};621//############## HELPERS #####################//622var getAndroidAvdPath = function(avdName) {623 var avdPath = '';624 switch (process.platform) {625 case 'darwin':626 case 'linux':627 avdPath = path.join(process.env.HOME, '.android', 'avd');628 break;629 case 'win32':630 avdPath = path.join(process.env.USERPROFILE, '.android', 'avd');631 break;632 default:633 logger.error('Unsupported platform "' + process.platform + '"');634 return null;635 }636 return avdName ? path.join(avdPath, avdName) : avdPath;637};638var getAvdNameWithPort = function(port, callback) {639 var avdNamePattern = /OK\s+(.+?)\s+OK/m;640 var avdName = null;641 var allData = '';642 var client = net.connect(port, function() { 643 client.write('avd name\r\n');644 });645 client.on('data', function(data) {646 allData += data.toString();647 if (/\r\n$/.test(data)) {648 client.end();649 }650 });651 client.on('end', function() {652 if (matches = allData.match(avdNamePattern)) {653 avdName = matches[1];654 } 655 callback(avdName);656 });657};658var getAvdNameWithDevice = function(device, callback) {659 getAvdNameWithPort(device.port, function(name) {660 device.name = name;661 callback();662 });...

Full Screen

Full Screen

AVDTreeView.ts

Source:AVDTreeView.ts Github

copy

Full Screen

1import * as vscode from 'vscode';2import { AVD } from '../cmd/AVDManager';3import { Manager } from '../core';4import { showMsg, showQuickPick, MsgType, showYesNoQuickPick } from '../module/ui';5import { subscribe } from '../module/';6import { AVDQuickPickItem } from './AVDQuickPick';7export class AVDTreeView {8 readonly provider: AVDTreeDataProvider;9 constructor(context: vscode.ExtensionContext, private manager: Manager) {10 this.provider = new AVDTreeDataProvider(this.manager);11 const view = vscode.window.createTreeView('avdmanager-avd', { treeDataProvider: this.provider, showCollapseAll: true });12 subscribe(context, [13 view,14 vscode.commands.registerCommand('avdmanager.avd-create', async (node) => {15 let path = node?.pkg?.pathRaw ?? undefined;16 let name = node?.pkg?.description ?? undefined;17 this.createAVDDiag(path, name).then(() => this.provider.refresh());18 }),19 vscode.commands.registerCommand('avdmanager.avdlist-refresh', this.refresh),20 vscode.commands.registerCommand('avdmanager.avd-launch', async (node) => {21 let name = node?.avd?.name ?? undefined;22 this.launchAVDDiag(name).then(() => this.provider.refresh());23 }),24 vscode.commands.registerCommand('avdmanager.avd-edit', async (node) => {25 let name = node?.avd?.name ?? undefined;26 this.renameAVDDiag(name).then(() => this.provider.refresh());27 }),28 vscode.commands.registerCommand('avdmanager.avd-delete', async (node) => {29 let name = node?.avd?.name ?? undefined;30 this.deleteAVDDiag(name).then(() => this.provider.refresh());31 })32 ]);33 }34 create = async () => {35 console.log("call avdmanager.cmd-avd-create");36 vscode.window.createWebviewPanel('avdmanager-avdCreate', "Create New AVD", vscode.ViewColumn.Beside);37 };38 refresh = async () => this.manager.avd.getAVDList(true).then(() => this.provider.refresh());39 async getAVDQuickPickItems(): Promise<AVDQuickPickItem[] | undefined> {40 return this.manager.avd.getAVDList()41 .then(avds => {42 return avds === undefined ? avds : avds.map((avd: AVD) => new AVDQuickPickItem(avd));43 });44 };45 async askAVDName() {46 const selected = await showQuickPick(this.getAVDQuickPickItems(), {47 placeHolder: "Select AVD name",48 canPickMany: false49 },50 "No AVD Found. Please create AVD first.",51 "No AVD selected");52 return (selected as AVDQuickPickItem)?.avd?.name ?? false;53 }54 async createAVDDiag(path: string, name: string) {55 //get new name56 let avdlist = await this.manager.avd.getAVDList();57 const newAvdName = await vscode.window.showInputBox({58 title: `Create AVD with ${name}:`,59 placeHolder: "Enter a new AVD name. (Must be unique)",60 validateInput: (name) => {61 if (name.match(/[^a-zA-Z0-9_]/)) {62 return `${name} is invalid! Must be [a-zA-Z0-9_]`;63 } else if (name.trim() === "") {64 return "Can't be blank!";65 } else if (avdlist.filter((avd: AVD) => avd.name === name).length > 0) {66 return `${name} already exits!`;67 } else {68 return null;69 }70 },71 });72 if (!newAvdName) {73 showMsg(MsgType.info, "The new AVD cannot be blank.");74 return;75 }76 await this.manager.avd.createAVD(newAvdName, path, name);77 await this.manager.avd.getAVDList(true); //reload cache78 }79 async renameAVDDiag(avdname: string | undefined) {80 //select avd81 let target = avdname ?? await this.askAVDName();82 if (!target) {83 return;84 }85 //get new name86 let avdlist = await this.manager.avd.getAVDList();87 const newAvdName = await vscode.window.showInputBox({88 title: `Rename AVD ${target}:`,89 placeHolder: "Enter a new AVD name. (Must be unique)",90 validateInput: (name) => {91 if (name.match(/[^a-zA-Z0-9_]/)) {92 return `${name} is invalid! Must be [a-zA-Z0-9_]`;93 } else if (name.trim() === "") {94 return "Can't be blank!";95 } else if (avdlist.filter((avd: AVD) => avd.name === name).length > 0) {96 return `${name} already exits!`;97 } else {98 return null;99 }100 },101 });102 if (!newAvdName) {103 showMsg(MsgType.info, "The new AVD cannot be blank.");104 return;105 }106 await this.manager.avd.renameAVD(target, newAvdName);107 await this.manager.avd.getAVDList(true); //reload cache108 }109 async deleteAVDDiag(avdname: string | undefined) {110 let target = avdname ?? await this.askAVDName();111 const ans = await showYesNoQuickPick(`Are you sure to delete AVD ${target}?`);112 if (ans === "Yes" && target) {113 await this.manager.avd.deleteAVD(target);114 }115 await this.manager.avd.getAVDList(true); //reload cache116 }117 async launchAVDDiag(avdname: string | undefined) {118 let target = avdname ?? await this.askAVDName();119 if (target) {120 await this.manager.avd.launchEmulator(target);121 }122 }123}124type TreeItem = AVDTreeItem;125class AVDTreeDataProvider implements vscode.TreeDataProvider<TreeItem> {126 constructor(private manager: Manager) { }127 getTreeItem(element: TreeItem): vscode.TreeItem {128 return element;129 }130 getChildren(element?: TreeItem): Thenable<TreeItem[]> {131 return this.manager.avd.getAVDList().then((avds) => {132 let list: AVDTreeItem[] = [];133 if (!avds) {134 return [];135 }136 avds.forEach((avd: AVD) => {137 if (avd.name && avd.name !== "") {138 list.push(new AVDTreeItem(avd, vscode.TreeItemCollapsibleState.None));139 }140 });141 return list;142 });143 }144 private _onDidChangeTreeData: vscode.EventEmitter<TreeItem | undefined | null | void> = new vscode.EventEmitter<TreeItem | undefined | null | void>();145 readonly onDidChangeTreeData: vscode.Event<TreeItem | undefined | null | void> = this._onDidChangeTreeData.event;146 refresh(): void {147 this._onDidChangeTreeData.fire();148 }149}150export class AVDTreeItem extends vscode.TreeItem {151 constructor(152 public readonly avd: AVD,153 public readonly collapsibleState: vscode.TreeItemCollapsibleState154 ) {155 super(avd.name, collapsibleState);156 this.description = avd.basedOn + " | " + avd.tagAbi;157 let infos = [158 { name: "Device", value: avd.device },159 { name: "Path", value: avd.path },160 { name: "Target", value: avd.target },161 { name: "Based on", value: avd.basedOn },162 { name: "Tag/ABI", value: avd.tagAbi },163 { name: "Skin", value: avd.skin },164 { name: "Sdcard", value: avd.sdCard },165 ];166 let tooltip = "";167 infos.forEach(element => {168 if (element.value) {169 tooltip += (tooltip.length === 0 ? "" : "\n") + `${element.name}: ${element.value}`;170 }171 });172 this.tooltip = tooltip;173 }174 contextValue = "avd";175 iconPath = new vscode.ThemeIcon('device-mobile');...

Full Screen

Full Screen

EmulatorDriver.js

Source:EmulatorDriver.js Github

copy

Full Screen

1const _ = require('lodash');2const path = require('path');3const Emulator = require('../android/Emulator');4const EmulatorTelnet = require('../android/EmulatorTelnet');5const DetoxRuntimeError = require('../../errors/DetoxRuntimeError');6const Environment = require('../../utils/environment');7const retry = require('../../utils/retry');8const sleep = require('../../utils/sleep');9const AndroidDriver = require('./AndroidDriver');10const ini = require('ini');11const fs = require('fs');12const os = require('os');13class EmulatorDriver extends AndroidDriver {14 constructor(config) {15 super(config);16 this.emulator = new Emulator();17 }18 async _fixEmulatorConfigIniSkinName(name) {19 const configFile = `${os.homedir()}/.android/avd/${name}.avd/config.ini`;20 const config = ini.parse(fs.readFileSync(configFile, 'utf-8'));21 if (!config['skin.name']) {22 const width = config['hw.lcd.width'];23 const height = config['hw.lcd.height'];24 if (width === undefined || height === undefined) {25 throw new Error(`Emulator with name ${name} has a corrupt config.ini file (${configFile}), try fixing it by recreating an emulator.`);26 }27 config['skin.name'] = `${width}x${height}`;28 fs.writeFileSync(configFile, ini.stringify(config));29 }30 return config;31 }32 async boot(avdName) {33 let adbName = await this._findADBNameByAVDName(avdName, { strict: false });34 const coldBoot = adbName == null;35 // If it's not already running, start it now.36 if (coldBoot) {37 await this.emulator.boot(avdName);38 adbName = await this._findADBNameByAVDName(avdName, { strict: true });39 }40 await this._waitForBootToComplete(adbName);41 await this.emitter.emit('bootDevice', { coldBoot, deviceId: adbName });42 return adbName;43 }44 async _findADBNameByAVDName(avdName, { strict }) {45 const adbDevices = await this.adb.devices();46 const filteredDevices = _.filter(adbDevices, {type: 'emulator', name: avdName});47 if (filteredDevices.length === 1) {48 return filteredDevices[0].adbName;49 }50 if (filteredDevices.length > 1) {51 throw new Error(`Got more than one device corresponding to the name: ${avdName}`);52 }53 if (strict) {54 throw new Error(`Could not find '${avdName}' on the currently ADB attached devices, 55 try restarting adb 'adb kill-server && adb start-server'`);56 }57 return null;58 }59 async acquireFreeDevice(avdName) {60 const avds = await this.emulator.listAvds();61 if (!avds) {62 const avdmanagerPath = path.join(Environment.getAndroidSDKPath(), 'tools', 'bin', 'avdmanager');63 throw new Error(`Could not find any configured Android Emulator. 64 Try creating a device first, example: ${avdmanagerPath} create avd --force --name Nexus_5X_API_24 --abi x86 --package 'system-images;android-24;google_apis_playstore;x86' --device "Nexus 5X"65 or go to https://developer.android.com/studio/run/managing-avds.html for details on how to create an Emulator.`);66 }67 if (_.indexOf(avds, avdName) === -1) {68 throw new Error(`Can not boot Android Emulator with the name: '${avdName}',69 make sure you choose one of the available emulators: ${avds.toString()}`);70 }71 await this._fixEmulatorConfigIniSkinName(avdName);72 const adbName = await this.boot(avdName);73 await this.adb.apiLevel(adbName);74 await this.adb.unlockScreen(adbName);75 return adbName;76 }77 async _waitForBootToComplete(deviceId) {78 await retry({ retries: 120, interval: 5000 }, async () => {79 const isBootComplete = await this.adb.isBootComplete(deviceId);80 if (!isBootComplete) {81 throw new DetoxRuntimeError({82 message: `Android device ${deviceId} has not completed its boot yet.`,83 });84 }85 });86 }87 async shutdown(deviceId) {88 const port = _.split(deviceId, '-')[1];89 const telnet = new EmulatorTelnet();90 await telnet.connect(port);91 await telnet.kill();92 await this.emitter.emit('shutdownDevice', { deviceId });93 }94}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var avdName = root.avdName();2print('avdName: ' + avdName);3var avdName = root.avdName();4print('avdName: ' + avdName);5var avdName = root.avdName();6print('avdName: ' + avdName);7var avdName = root.avdName();8print('avdName: ' + avdName);9var avdName = root.avdName();10print('avdName: ' + avdName);11var avdName = root.avdName();12print('avdName: ' + avdName);13var avdName = root.avdName();14print('avdName: ' + avdName);15var avdName = root.avdName();16print('avdName: ' + avdName);

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('app-root-path');2var utils = require(root + '/lib/utils.js');3var avdName = utils.avdName();4var appium = require('appium');5var wd = require('wd');6var chai = require('chai');7var chaiAsPromised = require('chai-as-promised');8var should = chai.should();9var expect = chai.expect;10var assert = chai.assert;11chai.use(chaiAsPromised);12describe('Test', function() {13 this.timeout(300000);14 var driver;15 before(function() {16 appium.main();17 driver = wd.promiseChainRemote("localhost", 4723);18 var desired = {19 };20 return driver.init(desired);21 });22 after(function() {23 return driver.quit();24 });25 it('should click on the button', function() {26 return driver.elementByAccessibilityId('button').click().sleep(5000);27 });28});29 at Error (native)30 at Object.fs.openSync (fs.js:439:18)31 at Object.fs.readFileSync (fs.js:290:15)32 at Object.module.exports [as app] (C:\Users\shubham\AppData\Roaming\npm\node_modules\appium\node_modules\appium-adb\lib\tools\apk-utils.js:27:23)33 at Object.module.exports [as desiredCapConstraints] (C:\Users\shubham\AppData\Roaming\npm\node_modules\appium\node_modules\appium-android-driver\lib\desired-caps.js:31:21)34 at Object.module.exports [as desiredCapConstraints] (C:\Users\shubham\AppData\Roaming\npm\node_modules\appium\node_modules\appium-android-driver\lib\desired-caps.js:19:18)35 at Object.module.exports [as desiredCapConstraints] (C:\Users\shubham\AppData\Roaming\npm\node_modules\appium\node_modules\appium-android-driver\lib\desired-caps.js:19:18

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