如何从标准输入 (stdin) 捕获进入我的 Android 应用程序的数据?

How can I capture data coming into my Android app from the standard input (stdin)?

我正在编写一个使用外部 USB barcode/RFID 扫描仪的应用程序。扫描仪是标准的 HID,在我的 Android 设备上运行良好。我插上电源,点击扫描按钮,数据就会在文本编辑应用程序中弹出。标准 USB 键盘也是如此。我插上电源,开始输入,然后数据显示在文本编辑应用程序中。

这是我需要帮助的地方。我需要做的是处理从扫描仪或外部键盘进入我的应用程序的数据,然后才能将其放入应用程序的正确表单字段中。

此时,我想我可以截取标准输入的数据,所以我想到了:

activity_main.xml

<LinearLayout>
    <EditText android:id="@+id/scan_data" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText scannedInput = (EditText)findViewById(R.id.scan_data);

    BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));

    StringBuilder sBuilder = new StringBuilder();
    String buffer;

    while((buffer = scanner.readLine()) != null){
        sBuilder.append(buffer);
    }

    String[] dataPoints = sBuilder.toString().split("\u003D|\u0026");

    scannedInput.setTextColor(Color.RED);
    scannedInput.setTextSize(34f);
    scannedInput.setText(dataPoints[0]); // or dataPoints[1], dataPoints[2], etc.
}

我写了这个,连接了我的扫描仪,并扫描了一个 RFID 标签。令我惊讶的是,整个扫描的字符串都出现在我的 EditText 字段中,而不仅仅是一部分。经过一些调试,我发现我可以删除 setContentView() 之后的所有代码,并且整个字符串仍然显示在我的 EditText 字段中。

所以,我需要知道的是,如何从任何外部源(例如,扫描仪、键盘等)捕获标准输入,并在将其放置在我想要的位置(表单字段、数据库)之前对其进行操作等)。

我该怎么做?

简短的回答是您无法访问标准输入,Android 中没有这样的应用程序动物。文本被注入到活动 EditText 中,因为您正在使用的 RFID / USB 设备将自身显示为 HID 设备。 Android 子系统自动拾取它们作为输入源,并将它们的输入路由到活动视图,就好像它来自键盘一样。

然而,一切并没有丢失。您可以做的是将 TextWatcher 附加到您的 EditText 并操作 Editable:

中的文本
EditText et = (EditText)findViewById(R.id.whatever_your_id);
et.addTextChangedListener(new TextWatcher() {
        @Override
        void afterTextChanged (Editable s) {
            //  Make your changes to 's' here, carefully as your changes will
            //  cause this method to be called again!
        }

        @Override
        void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //  Nothing to do here
        }

        @Override
        void onTextChanged(CharSequence s, int start, int before, int count) {
            //  Nothing to do here
        }
    });