LandiYax
2020-07-31 22:03
采纳率: 100%
浏览 146

Android串口通讯线程问题

正在做Android串口通讯项目, 个人对android编程也不是很熟, 属赶鸭子上架; 刚发现个问题, 一直baidu,google/csdn都没找到解决办法.

问题描述:我在onCreate() 时设置按钮监听, 然后点击按钮 打开串口通讯, 并读取串口发送信息; 能成功读取;

现在问题是, 我取消了按钮, 进入MainActivity时就打开串口, 并读取串口信息,此时程序就蹦贵了;

正常运行代码如下:

menuKeyboard = findViewById(R.id.menu_keyboard);
        menuKeyboard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 键盘测试
                SerialPortUtil serialPortUtil = new SerialPortUtil(SerialPortUtil.SERIAL_PORT_KEYBOARD);
                boolean isOpened = serialPortUtil.isOpen();
                if (isOpened) {
                    Toast.makeText(MainActivity.this, "串口"+SerialPortUtil.SERIAL_PORT_KEYBOARD+"打开,扫描读取!", Toast.LENGTH_SHORT).show();
                    serialPortUtil.readAsync(new OnSerialPortReadListener() {
                        @Override
                        public void onDataReceived(byte[] data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String responseStr = HexStrUtil.byteArrayToHexString(data);
                                    String endSix = responseStr.substring(responseStr.length()-6);
                                    Long responseEnd = (Long.parseLong(endSix,16));
                                    CommonUtils.alert(MainActivity.this, responseEnd.toString()).show();
                                }
                            });
                        }
                    }, false);
                } else {
                    CommonUtils.alert(MainActivity.this, "请先打开串口!").show();
                }
            }
        });
修改后代码如下:
SerialPortUtil serialPortUtil = new SerialPortUtil(SerialPortUtil.SERIAL_PORT_KEYBOARD);

        serialPortUtil.readAsync(new OnSerialPortReadListener() {
            @Override
            public void onDataReceived(byte[] data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String responseStr = HexStrUtil.byteArrayToHexString(data);
                        String endSix = responseStr.substring(responseStr.length()-6);
                        Long responseEnd = (Long.parseLong(endSix,16));
                        CommonUtils.alert(MainActivity.this, responseEnd.toString()).show();
                    }
                });
            }
        }, false);

只是去掉了按钮, 就导致程序崩溃; 貌似是线程的问题, 不知道咋解决

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题