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

如何为Cordova 7.0.1安卓应用添加USB线文件传输至PC的功能?

实现Cordova 7.0.1安卓应用USB文件传输到PC的方案

针对你的Cordova 7.0.1安卓应用新增USB线传输图片、JSON/TXT到PC的需求,我给你整理了一套可行的实现方案——核心是借助第三方Cordova插件调用安卓的USB Host API,毕竟Cordova本身没有原生的USB文件传输能力。下面是具体步骤:

1. 选择并安装兼容的Cordova USB插件

推荐使用cordova-plugin-usb,它封装了安卓的USB Host功能,支持设备枚举、权限请求和数据传输,且能兼容Cordova 7.x版本。执行以下命令安装:

cordova plugin add cordova-plugin-usb@1.1.0

(注:指定1.1.0版本是为了适配Cordova 7.0.1,避免新版本插件的兼容性问题)

2. 配置安卓USB权限

打开项目的platforms/android/AndroidManifest.xml,添加以下权限和特性声明:

<!-- 声明USB Host功能支持 -->
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
<!-- 请求USB设备访问权限 -->
<uses-permission android:name="android.permission.USB_PERMISSION" />

3. 编写USB设备监听与文件传输代码

在你的Cordova应用JS代码中,实现设备连接监听、权限请求和文件传输逻辑:

初始化USB监听与权限请求

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    // 监听USB设备连接事件
    document.addEventListener("usbattached", handleUsbAttached, false);
    // 启动时检测已连接的设备
    checkConnectedUsbDevices();
}

function checkConnectedUsbDevices() {
    window.usb.getDevices(function(devices) {
        if (devices.length === 0) {
            console.log("当前没有连接的USB设备");
            return;
        }
        // 取第一个匹配的设备(你可以根据设备VID/PID过滤目标PC设备)
        const targetDevice = devices[0];
        requestUsbPermission(targetDevice);
    }, function(err) {
        console.error("获取USB设备列表失败: ", err);
    });
}

function handleUsbAttached(event) {
    console.log("新USB设备连接: ", event.device);
    requestUsbPermission(event.device);
}

function requestUsbPermission(device) {
    window.usb.requestPermission(device, function() {
        console.log("USB权限获取成功");
        openUsbDevice(device);
    }, function(err) {
        console.error("USB权限请求失败: ", err);
    });
}

实现文件传输逻辑

function openUsbDevice(device) {
    window.usb.openDevice(device, function(deviceHandle) {
        // 示例:传输一张图片,你可以替换为JSON/TXT文件路径
        const filePath = cordova.file.externalRootDirectory + "DCIM/Camera/test.jpg";
        transferFile(deviceHandle, filePath);
    }, function(err) {
        console.error("打开USB设备失败: ", err);
    });
}

function transferFile(deviceHandle, filePath) {
    // 用cordova-plugin-file读取文件内容
    window.resolveLocalFileSystemURL(filePath, function(fileEntry) {
        fileEntry.file(function(file) {
            const reader = new FileReader();
            reader.onloadend = function() {
                // 将文件转为ArrayBuffer,通过USB发送
                sendDataViaUsb(deviceHandle, this.result);
            };
            // 根据文件类型选择读取方式:图片用ArrayBuffer,JSON/TXT可以用readAsText
            if (file.type.includes("image")) {
                reader.readAsArrayBuffer(file);
            } else {
                reader.readAsText(file);
            }
        }, function(err) {
            console.error("获取文件对象失败: ", err);
        });
    }, function(err) {
        console.error("解析文件路径失败: ", err);
    });
}

function sendDataViaUsb(deviceHandle, data) {
    // 自定义传输参数(需要和PC端接收程序的参数对应)
    const transferConfig = {
        bmRequestType: 0x40, // 主机到设备的传输方向
        bRequest: 0x01, // 自定义请求码,PC端要匹配这个值
        wValue: 0x0000,
        wIndex: 0x0000,
        data: data,
        timeout: 10000 // 超时时间10秒
    };

    window.usb.controlTransfer(deviceHandle, transferConfig, function(result) {
        console.log("文件传输成功!");
    }, function(err) {
        console.error("文件传输失败: ", err);
    });
}

4. PC端接收程序实现

你需要在PC端写一个简单的USB监听程序来接收数据,比如用Python的pyusb库:

import usb.core
import usb.util

# 替换为你的安卓设备VID和PID(可以在安卓设备的开发者选项中查看)
VID = 0x1234
PID = 0x5678

# 查找设备
device = usb.core.find(idVendor=VID, idProduct=PID)
if device is None:
    raise ValueError("设备未找到")

# 配置设备
device.set_configuration()
cfg = device.get_active_configuration()
interface = cfg[(0,0)]

# 接收数据并保存为文件
data = device.read(0x81, 1024*1024) # 读取1MB数据,可根据文件大小调整
with open("received_file.jpg", "wb") as f:
    f.write(data)
print("文件接收完成")

注意事项

  • 确保安卓设备支持USB Host功能(大部分中高端设备都支持,低端设备可能不兼容)
  • PC端需要安装对应安卓设备的USB驱动,并且Python环境要安装pyusb库(pip install pyusb)
  • 如果传输大文件,需要分段读取和发送,避免内存溢出
  • 可以通过设备的VID/PID过滤目标PC设备,避免连接到其他USB设备

内容的提问来源于stack exchange,提问作者Jibin Mathew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:29:45