背景
我想尝试通过 adb 命令将 Unicode 字符从 PC 发送到 Android 设备,就好像它们是从物理键盘输入一样。例如,来自各种语言的字符,而不仅仅是英语。
问题
使用我发现的命令是不可能的,因为它似乎只支持一组基本字符(可能只支持 Ascii):
adb shell "input keyboard text 'This goes to Android device'"
因此,我决定请求支持它,here (请考虑主演)。
作为一种解决方法,我想也许我可以开发一个使用 AccessibilityService 的应用程序,它会像我通过设备打字一样发送关键事件,而 PC 会使用 adb 将此类事件通过 Intent 。
问题是,在创建应用程序后,我找不到应该使用哪个函数来完成它。
我发现了什么
我发现了很多东西:
- onAccessibilityEvent - 这不是为了调度。它仅用于获取事件,我认为在这种情况下我什至不需要。
- getSoftKeyboardController - 一个可以帮助隐藏自动显示的键盘的功能,仅此而已...
- dispatchGesture - 一个似乎只用于调度触摸事件的函数。看起来很酷,但我不认为它可以处理按键。
- performGlobalAction - 看起来很有希望,但遗憾的是支持非常有限的一组操作(返回键、主页键等...)。
- findFocus - 我想我可以使用它,然后在我得到的东西上分派(dispatch)一个关键事件,但我不确定这是否是一种有效的方法,因为我想全局分派(dispatch)事件(另外,也许我会得到空对象,这意味着它可能不可靠)。更不用说根据我看到的选项,它不允许我将文本放在插入符号上,仅此而已。
问题
AccessibilityService 是否可以调度 Unicode 字符的关键事件,就像我键入一些文本一样?
最好的选择是什么?
最佳答案
这是一个非常规的解决方案。
您可以使用 UI Automator框架通过 ADB 将 Unicode 字符发送到焦点文本字段,就像输入命令对 ASCII 字符所做的那样(但对于 Unicode 字符失败。)
首先,实现一个能够接收广播的 Android 自动化测试。广播将指导测试执行某些任务。下面的实现将使用 Base-64 或 Unicode 清除文本并输入文本。在停止之前,我不应该认为以下内容可以像后台服务器一样运行。
AdbReceiver.kt
package com.example.adbreceiver
/*
* Test that runs with a broadcast receiver that accepts commands.
*
* To start the test:
* adb shell nohup am instrument -w com.example.adbreceiver.test/androidx.test.runner.AndroidJUnitRunner
*
* On Windows, the code page may need to be changed to UTF-8 by using the following command:
* chcp 65001
*
*/
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Base64
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 18)
class AdbInterface {
private var mDevice: UiDevice? = null
private var mStop = false
private val ACTION_MESSAGE = "ADB_INPUT_TEXT"
private val ACTION_MESSAGE_B64 = "ADB_INPUT_B64"
private val ACTION_CLEAR_TEXT = "ADB_CLEAR_TEXT"
private val ACTION_STOP = "ADB_STOP"
private var mReceiver: BroadcastReceiver? = null
@Test
fun adbListener() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
if (mReceiver == null) {
val filter = IntentFilter(ACTION_MESSAGE)
filter.addAction(ACTION_MESSAGE_B64)
filter.addAction(ACTION_CLEAR_TEXT)
filter.addAction(ACTION_STOP)
mReceiver = AdbReceiver()
ApplicationProvider.getApplicationContext<Context>().registerReceiver(mReceiver, filter)
}
try {
// Keep us running to receive commands.
// Really not a good way to go, but it works for the proof of concept.
while (!mStop) {
Thread.sleep(10000)
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fun inputMsg(s: String?) {
mDevice?.findObject(By.focused(true))?.setText(s)
}
internal inner class AdbReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
ACTION_MESSAGE -> {
val msg = intent.getStringExtra("msg")
inputMsg(msg)
}
ACTION_MESSAGE_B64 -> {
val data = intent.getStringExtra("msg")
val b64 = Base64.decode(data, Base64.DEFAULT)
val msg: String
try {
msg = String(b64, Charsets.UTF_8)
inputMsg(msg)
} catch (e: Exception) {
}
}
ACTION_CLEAR_TEXT -> inputMsg("")
ACTION_STOP -> {
mStop = true
ApplicationProvider.getApplicationContext<Context>()
.unregisterReceiver(mReceiver)
}
}
}
}
}
这是一个在模拟器上运行的简短演示。在演示中,第一个文本“你好吗?你好?”通过使用 Base-64 编码的 adb 输入。第二个文本,“你好吗?你好,再次?”输入为直接的 Unicode 字符串。
这里有三个Windows .bat 文件来管理界面。没有理由不能将这些移植到其他操作系统。
start.bat
启动接收命令广播的插桩测试。这将一直运行,直到它收到“ADB_STOP”命令。
rem Start AdbReceiver and disconnect.
adb shell nohup am instrument -w com.example.adbreceiver.test/androidx.test.runner.AndroidJUnitRunner
send.bat
用于演示发送Unicode文本,但可以很容易地概括
rem Send text entry commands to AdbReceiver. All text is input on the current focused element.
rem Change code page to UTF-8.
chcp 65001
rem Clear the field.
adb shell am broadcast -a ADB_CLEAR_TEXT
rem Input the Unicode characters encode in Base-64.
adb shell am broadcast -a ADB_INPUT_B64 --es msg 5L2g5aW95ZeOPyBIZWxsbz8=
rem Input the Unicode characters withouth further encoding.
adb shell am broadcast -a ADB_INPUT_TEXT --es msg '你好嗎? Hello, again?'
stop.bat
停止插桩测试。
rem Stop AdbReceiver.
adb shell am broadcast -a ADB_STOP
由于某种原因,该代码仅适用于 API 21+。它不会在早期的 API 上出错,只是默默地失败。
这只是概念验证,代码需要更多工作。
Project AdbReceiver在 GitHub 上。
如何运行(Windows)
启动模拟器。
在 Android Studio 中调出项目。
在java->com.example.adbrceiver(andoidTest)下右键AdbInterface。
在弹出的菜单中,点击“运行”。这将启动仪器测试。
在模拟器上打开任何应用程序并将光标设置到数据输入字段 (EditText)。
在终端窗口中,输入
adb shell am broadcast -a ADB_INPUT_TEXT --es msg 'Hello World!'
这应该输入“Hello World!”进入文本字段。
这也可以从命令行完成。参见“start.bat” 上面的文件说明如何开始测试,“stop.bat”文件说明如何停止测试。
关于 UI Automator 和 Assessibility 的说明
我深入了解了 UI Automator 的工作原理。正如 OP 猜测的那样,UI Automator 确实在 Android 上使用了可评估性服务。 AssessibilityNode 用于设置文本。在上面发布的代码中,inputMesg()
函数具有以下行:
mDevice?.findObject(By.focused(true))?.setText(s)
findObject()
位于 UiDevice.java 中,如下所示:
public UiObject2 findObject(BySelector selector) {
AccessibilityNodeInfo node = ByMatcher.findMatch(this, selector, getWindowRoots());
return node != null ? new UiObject2(this, selector, node) : null;
}
setText()
可以在 _UiObject2.java` 中找到,并像这样开始:
public void setText(String text) {
AccessibilityNodeInfo node = getAccessibilityNodeInfo();
// Per framework convention, setText(null) means clearing it
if (text == null) {
text = "";
}
if (UiDevice.API_LEVEL_ACTUAL > Build.VERSION_CODES.KITKAT) {
// do this for API Level above 19 (exclusive)
Bundle args = new Bundle();
args.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
if (!node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)) {
// TODO: Decide if we should throw here
Log.w(TAG, "AccessibilityNodeInfo#performAction(ACTION_SET_TEXT) failed");
}
} else {
...
因此,无障碍服务是 UI Automator 不可或缺的一部分。
关于android - AccessibilityService 可以调度关键事件,甚至包括 Unicode 字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70160582/