解决 Appium 使用 UiAutomator2 带来的 keyevent 无法识别问题

最近将appium更新到了1.6.5,uiautomator2确实能实现对Android toast内容的断言。但后续发现之前的wd.pressDeviceKey()方法不起作用。

更新

wd@1.3.0添加了press_keycode的路由,修复了这个bug
Replace the deprecated sendKeyEvent API with pressKeycode for Appium

POST /session/:sessionId/appium/device/press_keycode
Send key event to device (mjsonWire).
    
pressKeycode(keycode, metastate, cb) -> cb(err)
metastate is optional.

问题

首先分析appium server的日志:

2017-07-04 10:10:14:838 - info: [HTTP] --> POST /wd/hub/session/744e508b-3f7c-446b-b75f-a4373b0da0c1/appium/device/keyevent {"keycode":4}
2017-07-04 10:10:14:838 - info: [MJSONWP] Driver proxy active, passing request on via HTTP proxy
2017-07-04 10:10:14:838 - info: [debug] [JSONWP Proxy] Proxying [POST /wd/hub/session/744e508b-3f7c-446b-b75f-a4373b0da0c1/appium/device/keyevent] to [POST http://localhost:8200/wd/hub/session/3705f215-26ac-409d-a89d-c9ab578af2b4/appium/device/keyevent] with body: {"keycode":4}
2017-07-04 10:10:14:947 - error: [MJSONWP] Encountered internal error running command: Error: Could not proxy. Proxy error: Could not proxy command to remote server. Original error: 404 - undefined
    at doJwpProxy$ (C:\Users\lichen2\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\mjsonwp\mjsonwp.js:354:13)
    at tryCatch (C:\Users\lichen2\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (C:\Users\lichen2\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:315:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as throw] (C:\Users\lichen2\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (C:\Users\lichen2\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:136:37)
2017-07-04 10:10:14:947 - info: [HTTP] <-- POST /wd/hub/session/744e508b-3f7c-446b-b75f-a4373b0da0c1/appium/device/keyevent 500 119 ms - 274 

日志显示,Appium server接收到了keyevent的POST请求,但转发出去时: Error: Could not proxy. Proxy error: Could not proxy command to remote server. Original error: 404 - undefined,很明显,404表示设备端的sever没有响应该请求。

原因

出了问题,第一反应是去appium上翻Issue,确实有人提过同样的问题,但作者并没有给出Answer:
Can't use sendKeyEvent
于是只能自己翻源码了,因为问题出在appium server发POST到uiautomator2 server时404,所以直接去appium-uiautomator2-server项目里看:
找到文件AppiumServelt,该类看上去是注册路由的:

private void registerPostHandler() {
        register(postHandler, new NewSession("/wd/hub/session"));
        register(postHandler, new FindElement("/wd/hub/session/:sessionId/element"));
        register(postHandler, new FindElements("/wd/hub/session/:sessionId/elements"));
        register(postHandler, new Click("/wd/hub/session/:sessionId/element/:id/click"));
        register(postHandler, new Click("/wd/hub/session/:sessionId/appium/tap"));
        register(postHandler, new Clear("/wd/hub/session/:sessionId/element/:id/clear"));
        register(postHandler, new RotateScreen("/wd/hub/session/:sessionId/orientation"));
        register(postHandler, new RotateScreen("/wd/hub/session/:sessionId/rotation"));
        register(postHandler, new PressBack("/wd/hub/session/:sessionId/back"));
        register(postHandler, new SendKeysToElement("/wd/hub/session/:sessionId/element/:id/value"));
        register(postHandler, new SendKeysToElement("/wd/hub/session/:sessionId/keys"));
        register(postHandler, new Swipe("/wd/hub/session/:sessionId/touch/perform"));
        register(postHandler, new TouchLongClick("/wd/hub/session/:sessionId/touch/longclick"));
        register(postHandler, new OpenNotification("/wd/hub/session/:sessionId/appium/device/open_notifications"));
        register(postHandler, new PressKeyCode("/wd/hub/session/:sessionId/appium/device/press_keycode"));
        register(postHandler, new LongPressKeyCode("/wd/hub/session/:sessionId/appium/device/long_press_keycode"));
        register(postHandler, new Drag("/wd/hub/session/:sessionId/touch/drag"));
        register(postHandler, new AppStrings("/wd/hub/session/:sessionId/appium/app/strings"));
        register(postHandler, new Flick("/wd/hub/session/:sessionId/touch/flick"));
        register(postHandler, new ScrollTo("/wd/hub/session/:sessionId/touch/scroll"));
        register(postHandler, new MultiPointerGesture("/wd/hub/session/:sessionId/touch/multi/perform"));
        register(postHandler, new TouchDown("/wd/hub/session/:sessionId/touch/down"));
        register(postHandler, new TouchUp("/wd/hub/session/:sessionId/touch/up"));
        register(postHandler, new TouchMove("/wd/hub/session/:sessionId/touch/move"));
        register(postHandler, new UpdateSettings("/wd/hub/session/:sessionId/appium/settings"));
        register(postHandler, new NetworkConnection("/wd/hub/session/:sessionId/network_connection"));
    }

发现上面代码里并没有对应wd: POST /session/:sessionId/appium/device/keyevent,只有register(postHandler, new PressKeyCode("/wd/hub/session/:sessionId/appium/device/press_keycode"));
所以,404的原因找到了,笔者也在上面的Issue里给作者提了,希望后面作者能更新下uiautomator2 server。

解决

知道了问题原因,可以想到三种解决方案:

1.修改uiautomator2 server
对appium编译安装uiautomator2 server的过程没深入研究,尝试卸载原手机里的io.appium.uiautomator2.server程序,修改AppiumServlet,并没有起作用,所以这个解决方法我还是等作者吧。。

更新
感谢Carl的提示,原来appium-uiautomator2-server项目的Readme已经给出编译方法。

  • AS打开appium-uiautomator2-server项目,完成上面提到的AppiumServelt代码的修改
  • 运行gradle clean assembleServerDebug assembleServerDebugAndroidTest,这里编译可能会遇到一些问题,我遇到的是:app的build.gradle中,配置了对sdk-manager-plugin的依赖,而阿里云的maven库里并没有收录这个项目。解决方法: 将相关配置的代码注释掉
  • gradle编译成功后,会在/app/build/outputs/apk/下生产两个apk:
    1.appium-uiautomator2-server-v0.1.5.APK,执行命令的apk,(GitHub上已经更新到0.1.6)
    2.appium-uiautomator2-server-debug-androidTest.apk,用于启动Server的apk
  • 替换设备中的apk,可以手动安装,也可以替换appium下默认的apk。默认apk放在appium-uiautomator2-driver的uiautomator2目录下,替换之。还未结束,查看driver里的uiautomator2.js代码:
async installServerApk () {
    // Installs the apks on to the device or emulator
    let apkPackage = await this.getPackageName(apkPath);
    // appending .test to apkPackage name to get test apk package name
    let testApkPackage = apkPackage + '.test';
    let isApkInstalled = await this.adb.isAppInstalled(apkPackage);
    let isTestApkInstalled = await this.adb.isAppInstalled(testApkPackage);
    if (isApkInstalled || isTestApkInstalled) {
      //check server apk versionName
      let apkVersion = await this.getAPKVersion(apkPath);
      let pkgVersion = await this.getInstalledPackageVersion(apkPackage);
      if (apkVersion !== pkgVersion) {
        isApkInstalled = false;
        isTestApkInstalled = false;
        await this.adb.uninstallApk(apkPackage);
        await this.adb.uninstallApk(testApkPackage);
      }
    }
    if (!isApkInstalled) {
      await this.signAndInstall(apkPath, apkPackage);
    }
    if (!isTestApkInstalled) {
      await this.signAndInstall(testApkPath, testApkPackage);
    }
  }

uiautomator2-driver会去校验设备是否已安装以及对版本号进行判断,所以想替换设备里的版本,还需修改你编译apk的version,或者提前删除设备已经安装的。

2.修改wd代码
既然uiautomator2-Server路由中只有press_keycode,没有keyevent,那可以在wd里添加相应的Post方法。
找到你项目中node_modules里wd模块,在/lib/commands.js中添加代码如下:

/**
 * pressKeyCode(keycode, metastate, cb) -> cb(err)
 * metastate is optional
 *
 * @jsonWire POST /session/:sessionId/appium/device/press_keycode
 */
commands.pressKeyCode = function() {
    var fargs = utils.varargs(arguments);
    var cb = fargs.callback,
        keycode = fargs.all[0],
        metastate = fargs.all[1];
    var data = {keycode: keycode};
    if(metastate) { data.metastate = metastate; }
    this._jsonWireCall({
        method: 'POST'
        , relPath: '/appium/device/press_keycode'
        , data: data
        , cb: simpleCallback(cb)
    });
};

重启项目后,driver就可以调用pressKeyCode方法,appium server会将请求转发到/press_keycode,uiautomator2 server也就可以识别。

3.修改uiautomator2-driver
我们在分析appium-uiautomator2-driver时,发现作者其实是有写keyevent方法的,只不过调用的是adb:

// uiautomator2 doesn't support metastate for keyevents
commands.keyevent = async function (keycode, metastate) {
  log.debug(`Ignoring metastate ${metastate}`);
  await this.adb.keyevent(keycode);
};

那么怎么才能让appium直接调用这个方法呢,我们发现uiautomator2-driver的driver.js里有个数组:

// NO_PROXY contains the paths that we never want to proxy to UiAutomator2 server.
// TODO:  Add the list of paths that we never want to proxy to UiAutomator2 server.
// TODO: Need to segregate the paths better way using regular expressions wherever applicable.
// (Not segregating right away because more paths to be added in the NO_PROXY list)
const NO_PROXY = [
  ['POST', new RegExp('^/session/[^/]+/touch/multi/perform')],
  ['POST', new RegExp('^/session/[^/]+/touch/perform')],
  ['POST', new RegExp('^/session/[^/]+/element')],
  ['POST', new RegExp('^/session/[^/]+/appium/element/[^/]+/value')],
  ['POST', new RegExp('^/session/[^/]+/appium/element/[^/]+/replace_value')],
  ['GET', new RegExp('^/session/[^/]+/appium/[^/]+/current_activity')],
  ['POST', new RegExp('^/session/[^/]+/appium/[^/]+/start_activity')],
  ['POST', new RegExp('^/session/[^/]+/app/[^/]')],
  ['POST', new RegExp('^/session/[^/]+/location')],
  ['GET', new RegExp('^/session/[^/]+/appium/device/system_time')],
  ['POST', new RegExp('^/session/[^/]+/appium/settings')],
  ['GET', new RegExp('^/session/[^/]+/appium/settings')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/app_installed')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/lock')],
  ['POST', new RegExp('^/session/[^/]+/appium/app/close')],
  ['POST', new RegExp('^/session/[^/]+/appium/app/launch')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/pull_file')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/push_file')],
  ['POST', new RegExp('^/session/[^/]+/appium/app/reset')],
  ['POST', new RegExp('^/session/[^/]+/appium/app/background')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/toggle_location_services')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/is_locked')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/unlock')],
  ['POST', new RegExp('^/session/[^/]+/appium/app/end_test_coverage')],
  ['GET', new RegExp('^/session/[^/]+/contexts')],
  ['POST', new RegExp('^/session/[^/]+/context')],
  ['GET', new RegExp('^/session/[^/]+/context')],
  ['POST', new RegExp('^/session/[^/]+/network_connection')],
  ['GET', new RegExp('^/session/[^/]+/network_connection')],
  ['POST', new RegExp('^/session/[^/]+/timeouts')],
  ['GET', new RegExp('^/session/[^/]+/screenshot')],
  ['GET', new RegExp('^/session/[^/]+/element/[^/]+/attribute')],
  ['GET', new RegExp('^/session/[^/]+/element/[^/]+/enabled')],
  ['GET', new RegExp('^/session/[^/]+/element/[^/]+/selected')],
  ['GET', new RegExp('^/session/[^/]+/element/[^/]+/displayed')],
  ['GET', new RegExp('^/session/[^/]+/element/[^/]+/name')],
  ['GET', new RegExp('^/session/(?!.*\/)')],
  ['POST', new RegExp('^/session/[^/]+/keys')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/hide_keyboard')],
  ['POST', new RegExp('^/session/[^/]+/log')],
  ['POST', new RegExp('^/session/[^/]+/appium/device/remove_app')],
  ['GET', new RegExp('^/session/[^/]+/appium/device/is_keyboard_shown')]
];

注释里写了, 该数组维护的是不会转发到uiautomator2的路由,那么,我们只需要在该数组里添加:
['POST', new RegExp('^/session/[^/]+/appium/device/keyevent')]

p.s,该方法修改的是appium server依赖的appium-uiatumator2-driver,修改后需通过命令行启动appium,桌面程序似乎是带有缓存自制的,直接运行修改的代码不会起作用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容