上面的代码运行之后,如果没有问题则会得到一个
UsbDevice
,先看看google文档给出的这个类的解释:
This class represents a USB device attached to the android device with the android device acting as the USB host. Each device contains one or more
UsbInterface
s, each of which contains a number of
UsbEndpoint
s (the channels via which data is transmitted over USB).此类表示连接到Android设备的USB设备,其中android设备充当USB主机。 每个设备都包含一个或多个UsbInterfaces,每个UsbInterfaces包含许多UsbEndpoints(相当于一个通道,通过USB来进行数据传输的通道)。
其实这个类就是用来描述USB设备的信息的,可以通过这个类获取到设备的输出输入端口,以及设备标识等信息。
获取到需要的设备之后,请求使用权限:
private static final String ACTION_USB_PERMISSION = “com.android.example.USB_PERMISSION”;
public static final String ACTION_USB_ATTACHED = “android.hardware.usb.action.USB_DEVICE_ATTACHED”;
public static final String ACTION_USB_DETACHED = “android.hardware.usb.action.USB_DEVICE_DETACHED”;
private void requestUserPermission() {
Intent intent = new Intent(ACTION_USB_PERMISSION);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
IntentFilter permissionFilter = new IntentFilter(ACTION_USB_PERMISSION);
context.registerReceiver(usbPermissionReceiver, permissionFilter);
//申请权限 会弹框提示用户授权
usbManager.requestPermission(usbDevice, mPermissionIntent);
}
这里我们声明一个广播Receiver,当接受到授权成功的广播后做一些其他处理:
private boolean serialPortConnected;
private UsbDeviceConnection connection;
private final BroadcastReceiver cardReaderReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED); //用户是否同意授权使用usb
if (granted)
{
connection = usbManager.openDevice(device); //建立一个连接,通过这个连接读写数据
new ConnectionThread().start(); //开始读写数据
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice();
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
serialPortConnected = false;
}
}
};
收发数据
授权成