关闭USB设备连接

时间:2017-11-23 16:49:27

标签: android thermal-printer

我正在Android OS上使用热敏打印机。我需要能够关闭与连接的USB设备的连接。

实例化UsbMabager并获取Usb设备列表

mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
mDeviceList = mUsbManager.getDeviceList();

设置USB通信

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

1 个答案:

答案 0 :(得分:1)

如果您已连接USB设备:

UsbDeviceConnection mConnection = usbManager.openDevice(device);
...

您可以通过以下方式发布它:

mConnection.close();