From 2a68022a420383185b4c5e932cf87edc4dc6157b Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Wed, 18 May 2022 12:35:56 +0200 Subject: [PATCH] refactor: Update the way apps are activated on Android 7+ (#744) --- lib/commands/app-management.js | 47 +++++++++++++++++++++++----------- package.json | 2 +- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/lib/commands/app-management.js b/lib/commands/app-management.js index 7101c1e8..1827125f 100644 --- a/lib/commands/app-management.js +++ b/lib/commands/app-management.js @@ -54,22 +54,39 @@ commands.queryAppState = async function queryAppState (appId) { * @param {string} appId - Application package identifier */ commands.activateApp = async function activateApp (appId) { - const cmd = ['monkey', - // https://stackoverflow.com/questions/44860475/how-to-use-the-monkey-command-with-an-android-system-that-doesnt-have-physical - '--pct-syskeys', '0', - '-p', appId, - '-c', 'android.intent.category.LAUNCHER', - '1']; - let output = ''; - try { - this.log.debug(`Activating '${appId}' with 'adb shell ${cmd.join(' ')}' command`); - output = await this.adb.shell(cmd); - this.log.debug(`Command stdout: ${output}`); - } catch (e) { - this.log.errorAndThrow(`Cannot activate '${appId}'. Original error: ${e.message}`); + this.log.debug(`Activating '${appId}'`); + // Fallback to Monkey in older APIs + if (await this.adb.getApiLevel() < 24) { + const cmd = ['monkey', + // https://stackoverflow.com/questions/44860475/how-to-use-the-monkey-command-with-an-android-system-that-doesnt-have-physical + '--pct-syskeys', '0', + '-p', appId, + '-c', 'android.intent.category.LAUNCHER', + '1']; + let output = ''; + try { + output = await this.adb.shell(cmd); + this.log.debug(`Command stdout: ${output}`); + } catch (e) { + this.log.errorAndThrow(`Cannot activate '${appId}'. Original error: ${e.message}`); + } + if (output.includes('monkey aborted')) { + this.log.errorAndThrow(`Cannot activate '${appId}'. Are you sure it is installed?`); + } + return; } - if (output.includes('monkey aborted')) { - this.log.errorAndThrow(`Cannot activate '${appId}'. Are you sure it is installed?`); + + const stdout = await this.adb.shell([ + 'am', 'start', + '-a', 'android.intent.action.MAIN', + '-c', 'android.intent.category.LAUNCHER', + // FLAG_ACTIVITY_REORDER_TO_FRONT | FLAG_ACTIVITY_BROUGHT_TO_FRONT | FLAG_ACTIVITY_NEW_TASK + '-f', '0x10420000', + '-n', await this.adb.resolveLaunchableActivity(appId), + ]); + this.log.debug(stdout); + if (/^error:/mi.test(stdout)) { + throw new Error(`Cannot activate '${appId}'. Original error: ${stdout}`); } }; diff --git a/package.json b/package.json index 42ca0b64..20a4dd56 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "@appium/base-driver": "^8.5.2", "@appium/support": "^2.58.0", "@babel/runtime": "^7.0.0", - "appium-adb": "^9.0.0", + "appium-adb": "^9.5.0", "appium-chromedriver": "^5.0.1", "asyncbox": "^2.8.0", "axios": "^0.x",