Android 读取USB中的文件教程

整体流程

教小白读取USB文件
确认USB连接
确认USB连接
小白->>你
小白->>你
申请权限
申请权限
小白->>你
小白->>你
找到USB设备
找到USB设备
小白->>你
小白->>你
读取文件
读取文件
小白->>你
小白->>你
教小白读取USB文件

步骤

步骤操作
1确认USB连接
2申请USB读取权限
3找到USB设备
4读取文件

操作说明

步骤1:确认USB连接

在AndroidManifest.xml文件中添加以下权限:

<!-- 在Manifest文件中添加USB权限 -->
<uses-feature android:name="android.hardware.usb.host" />
  • 1.
  • 2.
步骤2:申请USB读取权限

在Activity中添加以下代码,请求USB读取权限:

// 在Activity中请求USB权限
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private PendingIntent permissionIntent;

// 确认USB设备是否已连接
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, filter);

HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
    device = entry.getValue();
    usbManager.requestPermission(device, permissionIntent);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
步骤3:找到USB设备

在BroadcastReceiver中处理USB权限请求结果,并打开USB设备连接:

// 处理USB权限请求结果
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        // 打开USB设备连接
                        connection = usbManager.openDevice(device);
                    }
                }
            }
        }
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
步骤4:读取文件

通过USB设备连接读取文件:

// 通过USB设备连接读取文件
UsbDeviceConnection connection = usbManager.openDevice(device);
UsbInterface usbInterface = device.getInterface(0);
UsbEndpoint endpoint = usbInterface.getEndpoint(0);
connection.claimInterface(usbInterface, true);

byte[] buffer = new byte[endpoint.getMaxPacketSize()];
int readBytes = connection.bulkTransfer(endpoint, buffer, buffer.length, TIMEOUT);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

现在,小白就可以通过上述步骤成功读取USB中的文件了。如果有任何疑问,欢迎随时向我提出。祝你学习顺利!