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(); } } }
@Override public void onCreate() { super.onCreate(); { try { mUsbManager = UsbManager.getInstance(this); } catch (Exception e) { Logger.e( "<uses-library android:name=\"com.android.future.usb.accessory\" />をマニフェストに追加してますか?", e); } mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); registerReceiver(mUsbReceiver, filter); } { mUSBCon = new USBConnection(); } }