简体   繁体   中英

Close USB device connection

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM