java - 通过 USB 将数据发送到 Android 应用程序

标签 java android usb

我有一个 Java 应用程序通过 USB 向 Android 设备发送字节,问题是它似乎没有在 Android 端读取任何字节

以下是信息的发送方式

private static void writeAndRead() throws LibUsbException {
    String question = "Hello Android I'll be your host today, how are you?";

    byte[] questionBuffer = question.getBytes();
    ByteBuffer questionData = BufferUtils.allocateByteBuffer(questionBuffer.length);
    IntBuffer transferred = IntBuffer.allocate(1);

    int result = 0;
    System.out.println("Sending question: " + question);
    System.out.println("Length of buffer: " + questionBuffer.length);
    result = LibUsb.bulkTransfer(handle, END_POINT_OUT_ACC, questionData, transferred, 5000);

    if(result < 0) {
        throw new LibUsbException("Bulk write error!", result);
    }
}

此方法似乎完成时没有引发异常,并且报告已发送了长度为 51 的缓冲区。

在 Android 端,我有以下内容

public class MainActivity extends AppCompatActivity  {

    private static final String TAG = "MainActivity";

    private UsbManager manager;
    private UsbAccessory accessory;
    private ParcelFileDescriptor accessoryFileDescriptor;
    private FileInputStream accessoryInput;
    private FileOutputStream accessoryOutput;

    private String question = "";
    private TextView questionTV;

    Runnable updateUI = new Runnable() {
        @Override
        public void run() {
            questionTV.append(question);
        }
    };

    Runnable readQuestionTask = new Runnable() {
        @Override
        public void run() {

            byte[] buffer = new byte[51];
            int ret;

            try {
                ret = accessoryInput.read(buffer);
                Log.d(TAG, "Read: " +ret);
                if (ret == 51) {
                    String msg = new String(buffer);
                    question += " Question: " + msg;
                } else {
                    question += " Read error";
                }
                Log.d(TAG, question);

            } catch (IOException e) {
                Log.e(TAG, "Read error ", e);
                question += " Read error";
            }

            questionTV.post(updateUI);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        questionTV = (TextView) findViewById(R.id.hello_world);
        questionTV.setMovementMethod(new ScrollingMovementMethod());

        Intent intent = getIntent();
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        if(accessory == null) {
            questionTV.append("Not started by the accessory itself"
                    + System.getProperty("line.separator"));
            return;
        }

        Log.d(TAG, accessory.toString());
        accessoryFileDescriptor = manager.openAccessory(accessory);
        Log.d(TAG, "File Descriptor " +accessoryFileDescriptor.toString());
        if (accessoryFileDescriptor != null) {
            FileDescriptor fd = accessoryFileDescriptor.getFileDescriptor();
            accessoryInput = new FileInputStream(fd);
            accessoryOutput = new FileOutputStream(fd);
        }
        new Thread(readQuestionTask).start();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

以下代码段

        try {
            ret = accessoryInput.read(buffer);
            Log.d(TAG, "Read: " +ret);
            if (ret == 51) {
                String msg = new String(buffer);
                question += " Question: " + msg;
            } else {
                question += " Read error";
            }
            Log.d(TAG, question);

        } catch (IOException e) {
            Log.e(TAG, "Read error ", e);
            question += " Read error";
        }

在控制台中报告问题字符串的内容

09-18 09:58:30.084  26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Read: 51
09-18 09:58:30.084  26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Question: ������������������������������������������������������������������������������������������������������

Activity 本身仅将其显示为“问题:”

我假设这些奇怪的字符只是首次分配字节数组时的默认字节值byte[] buffer = new byte[51];

不幸的是,该应用程序的性质使其很难调试。

关于为什么 ret =accessoryInput.read(buffer); 似乎没有读取任何内容,有什么建议吗?

编辑:实际上它正在读取一些内容,因为 accessoryInput.read(buffer); 将阻塞直到有输入,并且它不会阻塞。

那么为什么byte[]充满了垃圾?

我认为这可能与发送 ByteBuffer 的事实有关

LibUsb.bulkTransfer(handle, END_POINT_OUT_ACC, questionData, transferred, 5000);

但我尝试在 Android 中转换它

ByteBuffer buf = ByteBuffer.wrap(buffer);
String msg = new String(buf.array());
question += " Question: " + msg;

它给了我同样的垃圾字符

最佳答案

再次回答我自己的问题,问题就在这里

String question = "Hello Android I'll be your host today, how are you?";

byte[] questionBuffer = question.getBytes();
ByteBuffer questionData = BufferUtils.allocateByteBuffer(questionBuffer.length);
IntBuffer transferred = IntBuffer.allocate(1);

我实际上从未将byte[]放入ByteBuffer

questionData.put(questionBuffer) 解决了问题!

关于java - 通过 USB 将数据发送到 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648345/

相关文章:

java - Intellij 警告 - 通用未经检查的分配

android - 无法在芯片中添加图标

android - 如何使用 Android 连接蓝牙打印机?

java - 如何以编程方式将 View 和约束添加到 ConstraintLayout?

vb.net - 可编程独立按钮(硬件+软件)

python - 是否可以使用 PyUSB 通过 USB 端口获取 USB 设备

java - 使用(外部)DI 容器(Dagger 1)在 Android 中进行适当的依赖注入(inject)

java - 在 spring-data-neo4j 中使用 @Transactional 时出现问题

java - 夸脱或简单的 pojo

linux - 笔式驱动器中的 libusb 批量传输