I am working with a thermal printer on the Android OS. I need to be able to close the connection to the connected USB device.
Instantiate UsbManager and get USB device list
mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
mDeviceList = mUsbManager.getDeviceList();
Setting up USB communication
//Broadcast receiver to obtain permission from user for connection
private final BroadcastReceiver mUsbReceiver = 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) {
//call method to set up device communication
mInterface = device.getInterface(0);
mEndPoint = mInterface.getEndpoint(0);
mConnection = mUsbManager.openDevice(device);
//setup();
}
} else {
//Log.d("SUB", "permission denied for device " + device);
Toast.makeText(context, "PERMISSION DENIED FOR THIS DEVICE", Toast.LENGTH_SHORT).show();
}
}
}
}
};
If you have already connected a USB device:
UsbDeviceConnection mConnection = usbManager.openDevice(device);
...
You can release it with:
mConnection.close();