Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: List android devices #1765

Merged
5 changes: 5 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,11 @@ Example: `yarn react-native run-android --tasks clean,installDebug`.

Build native libraries only for the current device architecture for debug builds.

#### `--list-devices`

> default: false

List all available Android devices and simulators and let you choose one to run the app.
### `build-android`

Usage:
Expand Down
68 changes: 67 additions & 1 deletion packages/cli-platform-android/src/commands/runAndroid/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ import tryLaunchAppOnDevice from './tryLaunchAppOnDevice';
import getAdbPath from './getAdbPath';
import {logger, CLIError} from '@react-native-community/cli-tools';
import {getAndroidProject} from '../../config/getAndroidProject';
import listAndroidDevices from './listAndroidDevices';
import tryLaunchEmulator from './tryLaunchEmulator';
import chalk from 'chalk';
import {build, runPackager, BuildFlags, options} from '../buildAndroid';

export interface Flags extends BuildFlags {
appId: string;
appIdSuffix: string;
mainActivity: string;
deviceId?: string;
listDevices?: boolean;
}

type AndroidProject = NonNullable<Config['project']['android']>;
Expand All @@ -36,12 +40,68 @@ async function runAndroid(_argv: Array<string>, config: Config, args: Flags) {
return buildAndRun(args, androidProject);
}

const defaultPort = 5552;
async function getAvailableDevicePort(
port: number = defaultPort,
): Promise<number> {
/**
* The default value is 5554 for the first virtual device instance running on your machine. A virtual device normally occupies a pair of adjacent ports: a console port and an adb port. The console of the first virtual device running on a particular machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two. For example, 5556/5557, 5558/5559, and so on. The range is 5554 to 5682, allowing for 64 concurrent virtual devices.
*/
const adbPath = getAdbPath();
const devices = adb.getDevices(adbPath);
adamTrz marked this conversation as resolved.
Show resolved Hide resolved
if (port > 5682) {
throw new CLIError('Failed to launch emulator...');
}
if (devices.some((d) => d.includes(port.toString()))) {
return await getAvailableDevicePort(port + 2);
}
return port;
}

// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args: Flags, androidProject: AndroidProject) {
async function buildAndRun(args: Flags, androidProject: AndroidProject) {
process.chdir(androidProject.sourceDir);
const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew';

const adbPath = getAdbPath();
if (args.listDevices) {
if (args.deviceId) {
logger.warn(
'Both "deviceId" and "list-devices" parameters were passed to "run" command. We will list available devices and let you choose from one',
);
}

const device = await listAndroidDevices();
if (!device) {
throw new CLIError(
'Failed to select device, please try to run app without "list-devices" command.',
);
}

if (device.connected) {
return runOnSpecificDevice(
{...args, deviceId: device.deviceId},
adbPath,
androidProject,
);
}

const port = await getAvailableDevicePort();
const emulator = `emulator-${port}`;
logger.info('Launching emulator...');
const result = await tryLaunchEmulator(adbPath, device.readableName, port);
if (result.success) {
logger.info('Successfully launched emulator.');
return runOnSpecificDevice(
{...args, deviceId: emulator},
adbPath,
androidProject,
);
}
throw new CLIError(
`Failed to launch emulator. Reason: ${chalk.dim(result.error || '')}`,
);
}
if (args.deviceId) {
return runOnSpecificDevice(args, adbPath, androidProject);
} else {
Expand Down Expand Up @@ -178,5 +238,11 @@ export default {
'builds your app and starts it on a specific device/simulator with the ' +
'given device id (listed by running "adb devices" on the command line).',
},
{
name: '--list-devices',
description:
'Lists all available Android devices and simulators and let you choose one to run the app',
default: false,
},
],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import {execSync} from 'child_process';
import adb from './adb';
import getAdbPath from './getAdbPath';
import {getEmulators} from './tryLaunchEmulator';
import os from 'os';
import prompts from 'prompts';
import chalk from 'chalk';
import {CLIError} from '@react-native-community/cli-tools';

type DeviceData = {
deviceId: string | undefined;
readableName: string;
connected: boolean;
type: 'emulator' | 'phone';
};

function toPascalCase(value: string) {
return value !== '' ? value[0].toUpperCase() + value.slice(1) : value;
}

/**
*
* @param deviceId string
* @returns name of Android emulator
*/
function getEmulatorName(deviceId: string) {
const adbPath = getAdbPath();
const buffer = execSync(`${adbPath} -s ${deviceId} emu avd name`);
thymikee marked this conversation as resolved.
Show resolved Hide resolved

// 1st line should get us emu name
return buffer
.toString()
.split(os.EOL)[0]
.replace(/(\r\n|\n|\r)/gm, '')
.trim();
}

/**
*
* @param deviceId string
* @returns Android device name in readable format
*/
function getPhoneName(deviceId: string) {
const adbPath = getAdbPath();
const buffer = execSync(
`${adbPath} -s ${deviceId} shell getprop | grep ro.product.model`,
);
return buffer
.toString()
.replace(/\[ro\.product\.model\]:\s*\[(.*)\]/, '$1')
.trim();
Comment on lines +48 to +51
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please extract transforming regex to a separate fn and write unit tests :)

}

async function promptForDeviceSelection(
allDevices: Array<DeviceData>,
): Promise<DeviceData | undefined> {
if (!allDevices.length) {
throw new CLIError(
'No devices and/or emulators connected. Please create emulator with Android Studio or connect Android device.',
);
}
const {device} = await prompts({
type: 'select',
name: 'device',
message: 'Select the device / emulator you want to use',
choices: allDevices.map((d) => ({
title: `${chalk.bold(`${toPascalCase(d.type)}`)} ${chalk.green(
`${d.readableName}`,
)} (${d.connected ? 'connected' : 'disconnected'})`,
value: d,
})),
min: 1,
});

return device;
}

async function listAndroidDevices() {
const adbPath = getAdbPath();
const devices = adb.getDevices(adbPath);

let allDevices: Array<DeviceData> = [];

devices.forEach((deviceId) => {
if (deviceId.includes('emulator')) {
const emulatorData: DeviceData = {
deviceId,
readableName: getEmulatorName(deviceId),
connected: true,
type: 'emulator',
};
allDevices = [...allDevices, emulatorData];
} else {
const phoneData: DeviceData = {
deviceId,
readableName: getPhoneName(deviceId),
type: 'phone',
connected: true,
};
allDevices = [...allDevices, phoneData];
}
});

const emulators = getEmulators();

// Find not booted ones:
emulators.forEach((emulatorName) => {
// skip those already booted
if (allDevices.some((device) => device.readableName === emulatorName)) {
return;
}
const emulatorData: DeviceData = {
deviceId: undefined,
readableName: emulatorName,
type: 'emulator',
connected: false,
};
allDevices = [...allDevices, emulatorData];
});

const selectedDevice = await promptForDeviceSelection(allDevices);
return selectedDevice;
}

export default listAndroidDevices;
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import os from 'os';
import execa from 'execa';
import Adb from './adb';
import adb from './adb';

const emulatorCommand = process.env.ANDROID_HOME
? `${process.env.ANDROID_HOME}/emulator/emulator`
: 'emulator';

const getEmulators = () => {
export const getEmulators = () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd consider moving it to separate file to avoid unexpected circular deps and make it clearer what's shared (although one could say export says it all, and they would be right)

try {
const emulatorsOutput = execa.sync(emulatorCommand, ['-list-avds']).stdout;
return emulatorsOutput.split(os.EOL).filter((name) => name !== '');
Expand All @@ -15,55 +15,75 @@ const getEmulators = () => {
}
};

const launchEmulator = async (emulatorName: string, adbPath: string) => {
return new Promise((resolve, reject) => {
const cp = execa(emulatorCommand, [`@${emulatorName}`], {
const launchEmulator = async (
emulatorName: string,
adbPath: string,
port?: number,
): Promise<boolean> => {
const manualCommand = `${emulatorCommand} @${emulatorName}`;

const cp = execa(
emulatorCommand,
[`@${emulatorName}`, port ? '-port' : '', port ? `${port}` : ''],
{
detached: true,
stdio: 'ignore',
});
cp.unref();
const timeout = 30;
},
);
cp.unref();
const timeout = 30;

// Reject command after timeout
const rejectTimeout = setTimeout(() => {
cleanup();
reject(`Could not start emulator within ${timeout} seconds.`);
}, timeout * 1000);

const bootCheckInterval = setInterval(() => {
if (Adb.getDevices(adbPath).length > 0) {
return new Promise<boolean>((resolve, reject) => {
const bootCheckInterval = setInterval(async () => {
const devices = adb.getDevices(adbPath);
const connected = port
? devices.find((d) => d.includes(`${port}`))
: devices.length > 0;
if (connected) {
cleanup();
resolve();
resolve(true);
}
}, 1000);

// Reject command after timeout
const rejectTimeout = setTimeout(() => {
stopWaitingAndReject(
`It took too long to start and connect with Android emulator: ${emulatorName}. You can try starting the emulator manually from the terminal with: ${manualCommand}`,
);
}, timeout * 1000);

const cleanup = () => {
clearTimeout(rejectTimeout);
clearInterval(bootCheckInterval);
};

cp.on('exit', () => {
const stopWaitingAndReject = (message: string) => {
cleanup();
reject('Emulator exited before boot.');
});
reject(new Error(message));
};

cp.on('error', (error) => {
cleanup();
reject(error.message);
cp.on('error', ({message}) => stopWaitingAndReject(message));

cp.on('exit', () => {
stopWaitingAndReject(
`The emulator (${emulatorName}) quit before it finished opening. You can try starting the emulator manually from the terminal with: ${manualCommand}`,
);
});
});
};

export default async function tryLaunchEmulator(
adbPath: string,
emulatorName?: string,
port?: number,
): Promise<{success: boolean; error?: string}> {
const emulators = getEmulators();
if (emulators.length > 0) {
try {
await launchEmulator(emulators[0], adbPath);
await launchEmulator(emulatorName ?? emulators[0], adbPath, port);
return {success: true};
} catch (error) {
return {success: false, error};
return {success: false, error: error?.message};
}
}
return {
Expand Down