You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino与Android Studio连接问题:USB串口依赖库无法找到

问题解决:找不到com.hoho.android:usb-serial-for-android:3.3.0

问题原因

你引入的com.github.mik3y:usb-serial-for-android:3.7.3是原com.hoho.android:usb-serial-for-android的fork版本,但构建时出现依赖冲突或仓库配置缺失,导致系统尝试拉取旧版本3.3.0却找不到。

解决方案

1. 确认仓库配置

在项目根目录的settings.gradle(新版Android Studio)中,确保添加必要的仓库:

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
}

2. 修正依赖声明

在模块的build.gradle中,确保依赖声明正确并排除冲突的旧依赖:

implementation ('com.github.mik3y:usb-serial-for-android:3.7.3') {
    exclude group: 'com.hoho.android', module: 'usb-serial-for-android'
}

3. 清理构建缓存

  • 点击Android Studio顶部菜单栏File -> Invalidate Caches...
  • 勾选Invalidate and Restart,等待IDE重启后重新构建项目

代码优化建议

除依赖问题外,你的代码还有几个可优化点:

  • 精准识别Arduino设备:不要循环请求所有USB设备权限,只针对Arduino的VID/PID请求(Uno的VID通常为0x2341,PID为0x0043,不同版本可能有差异):
    for (UsbDevice device : usbManager.getDeviceList().values()) {
        if (device.getVendorId() == 0x2341 && device.getProductId() == 0x0043) {
            usbManager.requestPermission(device, permissionIntent);
            break;
        }
    }
    
  • 安全关闭串口线程:添加volatile变量控制读取循环,避免内存泄漏:
    private volatile boolean isReading = true;
    
    // 读取线程内
    while (isReading) {
        // 读取逻辑
    }
    
    // onDestroy中
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(usbReceiver);
        isReading = false;
        if (port != null) {
            try {
                port.close();
            } catch (IOException e) {
                Log.e("USB", "Port close failed: " + e.getMessage());
            }
        }
    }
    
  • 数据解析容错:避免数组越界异常,增加数据格式判断:
    String[] parts = data.trim().split(" ");
    if (parts.length >= 3) {
        float dustDensity = Float.parseFloat(parts[2]);
        // 更新UI逻辑
    } else {
        Log.w("USB", "Invalid data format: " + data);
    }
    

内容的提问来源于stack exchange,提问作者Matthew Seril

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:54:55