private boolean connectDevice() { if (mRunning) { return true; } else { UsbAccessory[] accessories = mUsbManager.getAccessoryList(); UsbAccessory accessory = (accessories == null ? null : accessories[0]); Logger.d("onResume accessory:" + accessory); if (accessory != null) { if (mUsbManager.hasPermission(accessory)) { Logger.d("onResume openAccessory START"); openAccessory(accessory); } else { Logger.d("permission ERROR?"); synchronized (mUsbManager) { if (!mPermissionRequestPending) { mUsbManager.requestPermission(accessory, mPermissionIntent); mPermissionRequestPending = true; } } } return true; } else { Logger.d("not attachd USB."); return false; } } }
private void openAccessory(UsbAccessory accessory) { Logger.d("openAccessory accessory:" + accessory.toString()); ParcelFileDescriptor fd = mUsbManager.openAccessory(accessory); Logger.d("openAccessory fd:" + fd); if (fd != null) { mAccessory = accessory; mUSBCon.start(fd, mUsbReceiveHandler); mRunning = true; } else { Logger.d("accessory open fail"); } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbAccessory accessory = UsbManager.getAccessory(intent); Logger.d("onReceive accessory:" + accessory); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { openAccessory(accessory); } else { Logger.d("permission denied for accessory " + accessory); } mPermissionRequestPending = false; } } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) { UsbAccessory accessory = UsbManager.getAccessory(intent); if (accessory != null && accessory.equals(mAccessory)) { closeAccessory(); } } }