类android.hardware.usb.UsbDevice源码实例Demo

下面列出了怎么用android.hardware.usb.UsbDevice的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: libcommon   文件: UsbUtils.java
/**
 * 接続されているUSBの機器リストをLogCatに出力
 * @param context
 */
public static void dumpDevices(@NonNull final Context context) {
	final UsbManager usbManager = ContextUtils.requireSystemService(context, UsbManager.class);
	final HashMap<String, UsbDevice> list = usbManager.getDeviceList();
	if ((list != null) && !list.isEmpty()) {
		final Set<String> keys = list.keySet();
		if (keys != null && keys.size() > 0) {
			final StringBuilder sb = new StringBuilder();
			for (final String key: keys) {
				final UsbDevice device = list.get(key);
				final int num_interface = device != null ? device.getInterfaceCount() : 0;
				sb.setLength(0);
				for (int i = 0; i < num_interface; i++) {
					sb.append(String.format(Locale.US, "interface%d:%s",
						i, device.getInterface(i).toString()));
				}
				Log.i(TAG, "key=" + key + ":" + device + ":" + sb.toString());
			}
		} else {
			Log.i(TAG, "no device");
		}
	} else {
		Log.i(TAG, "no device");
	}
}
 
源代码2 项目: UsbSerial   文件: UsbSerialDevice.java
public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
  {
/*
 * It checks given vid and pid and will return a custom driver or a CDC serial driver.
 * When CDC is returned open() method is even more important, its response will inform about if it can be really
 * opened as a serial device with a generic CDC serial driver
 */
      int vid = device.getVendorId();
      int pid = device.getProductId();

      if(FTDISioIds.isDeviceSupported(device))
          return new FTDISerialDevice(device, connection, iface);
      else if(CP210xIds.isDeviceSupported(vid, pid))
          return new CP2102SerialDevice(device, connection, iface);
      else if(PL2303Ids.isDeviceSupported(vid, pid))
          return new PL2303SerialDevice(device, connection, iface);
      else if(CH34xIds.isDeviceSupported(vid, pid))
          return new CH34xSerialDevice(device, connection, iface);
      else if(isCdcDevice(device))
          return new CDCSerialDevice(device, connection, iface);
      else
          return null;
  }
 
/**
 * Checks the devices connected to android and finds the radio. It then attempts to get
 * permission to connect to the radio.
 */
private void requestConnection() {
    Log.v(TAG, "Requesting connection to device");
    UsbDevice device = getDevice();
    if (device != null) {
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(usbBroadcastReceiver, filter);

        if (usbManager.hasPermission(device)) {
            usbDevice = device;
            openConnection();
        } else {
            Log.v(TAG, "Requesting permission for device");
            usbManager.requestPermission(device, usbPermissionIntent);
        }
    } else {
        if (connectionStateListener != null) {
            connectionStateListener.onFail();
        }
        Log.v(TAG, "No device found");
    }
}
 
源代码4 项目: UsbSerial   文件: UsbSerialDevice.java
public static boolean isSupported(UsbDevice device)
{
    int vid = device.getVendorId();
    int pid = device.getProductId();

    if(FTDISioIds.isDeviceSupported(device))
        return true;
    else if(CP210xIds.isDeviceSupported(vid, pid))
        return true;
    else if(PL2303Ids.isDeviceSupported(vid, pid))
        return true;
    else if(CH34xIds.isDeviceSupported(vid, pid))
        return true;
    else if(isCdcDevice(device))
        return true;
    else
        return false;
}
 
源代码5 项目: UVCCameraZxing   文件: UVCService.java
private void removeService(final UsbDevice device) {
	final int key = device.hashCode();
	synchronized (sServiceSync) {
		final CameraServer service = sCameraServers.get(key);
		if (service != null)
			service.release();
		sCameraServers.remove(key);
		sServiceSync.notifyAll();
	}
	if (checkReleaseService()) {
		if (mUSBMonitor != null) {
			mUSBMonitor.unregister();
			mUSBMonitor = null;
		}
	}
}
 
源代码6 项目: FireFiles   文件: UsbStorageProvider.java
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
    String deviceName = usbDevice.getDeviceName();
    if (UsbStorageProvider.ACTION_USB_PERMISSION.equals(action)) {
        boolean permission = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
        if (permission) {
            discoverDevice(usbDevice);
            notifyRootsChanged();
            notifyDocumentsChanged(getContext(), getRootId(usbDevice)+ROOT_SEPERATOR);
        } else {
            // so we don't ask for permission again
        }
    } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)
            || UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
        updateRoots();
    }
}
 
源代码7 项目: DeviceConnect-Android   文件: USBMonitor.java
/**
 * open specific USB device
 * @param device
 */
private final void processConnect(final UsbDevice device) {
	if (destroyed) return;

	updatePermission(device, true);
	mAsyncHandler.post(new Runnable() {
		@Override
		public void run() {
			if (DEBUG) Log.v(TAG, "processConnect:device=" + device);
			UsbControlBlock ctrlBlock;
			final boolean createNew;
			ctrlBlock = mCtrlBlocks.get(device);
			if (ctrlBlock == null) {
				ctrlBlock = new UsbControlBlock(USBMonitor.this, device);
				mCtrlBlocks.put(device, ctrlBlock);
				createNew = true;
			} else {
				createNew = false;
			}
			if (mOnDeviceConnectListener != null) {
				mOnDeviceConnectListener.onConnect(device, ctrlBlock, createNew);
			}
		}
	});
}
 
源代码8 项目: xDrip   文件: SyncingService.java
public UsbDevice findDexcom() {
    Log.i("CALIBRATION-CHECK-IN: ", "Searching for dexcom");
    mUsbManager = (UsbManager) getApplicationContext().getSystemService(Context.USB_SERVICE);
    Log.i("USB MANAGER = ", mUsbManager.toString());
    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
    Log.i("USB DEVICES = ", deviceList.toString());
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    Log.i("USB DEVICES = ", String.valueOf(deviceList.size()));

    while(deviceIterator.hasNext()){
        UsbDevice device = deviceIterator.next();
        if (device.getVendorId() == 8867 && device.getProductId() == 71
                && device.getDeviceClass() == 2 && device.getDeviceSubclass() ==0
                && device.getDeviceProtocol() == 0){
            dexcom = device;
            Log.i("CALIBRATION-CHECK-IN: ", "Dexcom Found!");
            return device;
        } else {
            Log.w("CALIBRATION-CHECK-IN: ", "that was not a dexcom (I dont think)");
        }
    }
    return null;
}
 
源代码9 项目: UVCCameraZxing   文件: USBMonitor.java
/**
 * request permission to access to USB device
 * @param device
 */
public synchronized void requestPermission(final UsbDevice device) {
	if (DEBUG) Log.v(TAG, "requestPermission:device=" + device);
	if (mPermissionIntent != null) {
		if (device != null) {
			if (mUsbManager.hasPermission(device)) {
				processConnect(device);
			} else {
				mUsbManager.requestPermission(device, mPermissionIntent);
			}
		} else {
			processCancel(device);
		}
	} else {
		processCancel(device);
	}
}
 
源代码10 项目: UsbHid   文件: UsbHidDevice.java
private UsbHidDevice(UsbDevice usbDevice, UsbInterface usbInterface, UsbManager usbManager) {
    mUsbDevice = usbDevice;
    mUsbInterface = usbInterface;
    mUsbManager= usbManager;

    for (int i = 0; i < mUsbInterface.getEndpointCount(); i++) {
        UsbEndpoint endpoint = mUsbInterface.getEndpoint(i);
        int dir = endpoint.getDirection();
        int type = endpoint.getType();
        if (mInUsbEndpoint == null && dir == UsbConstants.USB_DIR_IN && type == UsbConstants.USB_ENDPOINT_XFER_INT) {
            mInUsbEndpoint = endpoint;
        }
        if (mOutUsbEndpoint == null && dir == UsbConstants.USB_DIR_OUT && type == UsbConstants.USB_ENDPOINT_XFER_INT) {
            mOutUsbEndpoint = endpoint;
        }
    }
}
 
源代码11 项目: UVCCameraZxing   文件: USBMonitor.java
/**
 * close specified interface. USB device itself still keep open.
 */
public synchronized void close() {
	if (DEBUG) Log.i(TAG, "UsbControlBlock#close:");

	if (mConnection != null) {
		final int n = mInterfaces.size();
		int key;
		UsbInterface intf;
		for (int i = 0; i < n; i++) {
			key = mInterfaces.keyAt(i);
			intf = mInterfaces.get(key);
			mConnection.releaseInterface(intf);
		}
		mConnection.close();
		mConnection = null;
		final USBMonitor monitor = mWeakMonitor.get();
		if (monitor != null) {
			if (monitor.mOnDeviceConnectListener != null) {
				final UsbDevice device = mWeakDevice.get();
				monitor.mOnDeviceConnectListener.onDisconnect(device, this);
			}
			monitor.mCtrlBlocks.remove(getDevice());
		}
	}
}
 
@Override
public void onStart() {
  super.onStart();
  HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
  ListView listView = getRootView().findViewById(R.id.connected_usb_devices_list);
  listView.setAdapter(usbArrayAdapter);
  for (UsbDevice device : deviceList.values()) {
    usbArrayAdapter.add(getDisplayableUsbDeviceName(device));
  }
  usbArrayAdapter.notifyDataSetChanged();
  if (usbArrayAdapter.getCount() == 0) {
    updateScreenBasedOnIfUsbDeviceIsConnected(false);
  }

  IntentFilter intent = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
  intent.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
  getActivity().registerReceiver(broadcastReceiver, intent);
}
 
源代码13 项目: DeviceConnect-Android   文件: USBMonitor.java
/**
 * return device list, return empty list if no device matched
 * @param filters
 * @return
 * @throws IllegalStateException
 */
public List<UsbDevice> getDeviceList(final List<DeviceFilter> filters) throws IllegalStateException {
	if (destroyed) throw new IllegalStateException("already destroyed");
	final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
	final List<UsbDevice> result = new ArrayList<UsbDevice>();
	if (deviceList != null) {
		if ((filters == null) || filters.isEmpty()) {
			result.addAll(deviceList.values());
		} else {
			for (final UsbDevice device: deviceList.values() ) {
				for (final DeviceFilter filter: filters) {
					if ((filter != null) && filter.matches(device)) {
						// when filter matches
						if (!filter.isExclude) {
							result.add(device);
						}
						break;
					}
				}
			}
		}
	}
	return result;
}
 
源代码14 项目: UsbGps4Droid   文件: USBGpsSettingsFragment.java
/**
 * Gets a summary of the current select product and vendor ids
 */
private String getSelectedDeviceSummary() {
    int productId = sharedPreferences.getInt(
            USBGpsProviderService.PREF_GPS_DEVICE_PRODUCT_ID, DEFAULT_GPS_PRODUCT_ID);
    int vendorId = sharedPreferences.getInt(
            USBGpsProviderService.PREF_GPS_DEVICE_VENDOR_ID, DEFAULT_GPS_VENDOR_ID);

    String deviceDisplayedName = "Device not connected - " + vendorId + ": " + productId;

    for (UsbDevice usbDevice: usbManager.getDeviceList().values()) {
        if (usbDevice.getVendorId() == vendorId && usbDevice.getProductId() == productId) {
            deviceDisplayedName =
                    "USB " + usbDevice.getDeviceProtocol() + " " + usbDevice.getDeviceName() +
                            " | " + vendorId + ": " + productId;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                deviceDisplayedName = usbDevice.getManufacturerName() + usbDevice.getProductName() +
                        " | " + vendorId + ": " + productId;
            }

            break;
        }
    }

    return deviceDisplayedName;
}
 
源代码15 项目: UsbSerial   文件: UsbSpiDevice.java
public static UsbSpiDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
    int vid = device.getVendorId();
    int pid = device.getProductId();

    if(CP2130Ids.isDeviceSupported(vid, pid))
        return new CP2130SpiDevice(device, connection, iface);
    else
        return null;
}
 
源代码16 项目: USBIPServerForAndroid   文件: UsbIpService.java
@Override
public UsbDeviceInfo getDeviceByBusId(String busId) {
	UsbDevice dev = getDevice(busId);
	if (dev == null) {
		return null;
	}
	
	AttachedDeviceContext context = connections.get(dev.getDeviceId());
	UsbDeviceConnection devConn = null;
	if (context != null) {
		devConn = context.devConn;
	}
	
	return getInfoForDevice(dev, devConn);
}
 
源代码17 项目: UVCCameraZxing   文件: DeviceFilter.java
public DeviceFilter(final UsbDevice device) {
		mVendorId = device.getVendorId();
		mProductId = device.getProductId();
		mClass = device.getDeviceClass();
		mSubclass = device.getDeviceSubclass();
		mProtocol = device.getDeviceProtocol();
		mManufacturerName = null;	// device.getManufacturerName();
		mProductName = null;		// device.getProductName();
		mSerialNumber = null;		// device.getSerialNumber();
/*		Log.i(TAG, String.format("vendorId=0x%04x,productId=0x%04x,class=0x%02x,subclass=0x%02x,protocol=0x%02x",
			mVendorId, mProductId, mClass, mSubclass, mProtocol)); */
	}
 
源代码18 项目: ns-usbloader-mobile   文件: TinfoilUSB.java
TinfoilUSB(ResultReceiver resultReceiver,
           Context context,
           UsbDevice usbDevice,
           UsbManager usbManager,
           ArrayList<NSPElement> nspElements) throws Exception{
    super(resultReceiver, context, usbDevice, usbManager);
    this.nspElements = nspElements;
}
 
源代码19 项目: FireFiles   文件: UsbStorageProvider.java
public void discoverDevices(){
    try{
        for (UsbDevice device : usbManager.getDeviceList().values()) {
            if(hasPermission(device)) {
                discoverDevice(device);
            } else {
                addRoot(device);
            }
        }
    } catch (Exception e){
        Crashlytics.logException(e);
    }
}
 
源代码20 项目: sample-usbenum   文件: UsbActivity.java
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (device != null) {
            printStatus(getString(R.string.status_removed));
            printDeviceDescription(device);
        }
    }
}
 
源代码21 项目: AndroidUSBCamera   文件: USBMonitor.java
/**
 * return device list, return empty list if no device matched
 * @param filter
 * @return
 * @throws IllegalStateException
 */
public List<UsbDevice> getDeviceList(final DeviceFilter filter) throws IllegalStateException {
	if (destroyed) throw new IllegalStateException("already destroyed");
	final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
	final List<UsbDevice> result = new ArrayList<UsbDevice>();
	if (deviceList != null) {
		for (final UsbDevice device: deviceList.values() ) {
			if ((filter == null) || (filter.matches(device) && !filter.isExclude)) {
				result.add(device);
			}
		}
	}
	return result;
}
 
源代码22 项目: yubikit-android   文件: UsbDeviceManager.java
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (ACTION_USB_PERMISSION.equals(action)) {
        context.unregisterReceiver(this);
        final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        // device is not plugged in anymore, we're not interested in it's permissions
        if (device == null || !findDevices().contains(device)) {
            return;
        }

        listener.onRequestPermissionsResult(new UsbSession(usbManager, device), usbManager.hasPermission(device));
    }
}
 
源代码23 项目: usb-with-serial-port   文件: UsbSerialProber.java
/**
 * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
 * from the currently-attached {@link UsbDevice} hierarchy. This method does
 * not require permission from the Android USB system, since it does not
 * open any of the devices.
 *
 * @param usbManager
 *
 * @return a list, possibly empty, of all compatible drivers
 */
@Keep
public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
    final List<UsbSerialDriver> result = new ArrayList<UsbSerialDriver>();
    HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
        UsbDevice usbDevice = deviceIterator.next();
        UsbSerialDriver driver = probeDevice(usbDevice);
        if (driver != null) {
            result.add(driver);
        }
    }
    return result;
}
 
源代码24 项目: USBIPServerForAndroid   文件: UsbIpService.java
private UsbDevice getDevice(int deviceId) {
	for (UsbDevice dev : usbManager.getDeviceList().values()) {
		if (dev.getDeviceId() == deviceId) {
			return dev;
		}
	}
	
	return null;
}
 
源代码25 项目: Walrus   文件: LineBasedUsbSerialCardDevice.java
protected LineBasedUsbSerialCardDevice(Context context, UsbDevice usbDevice, String delimiter,
        String charsetName, String status) throws IOException {
    super(context, usbDevice, status);

    this.delimiter = delimiter;
    this.charsetName = charsetName;
}
 
源代码26 项目: UsbGps4Droid   文件: USBGpsManager.java
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (ACTION_USB_PERMISSION.equals(action)) {
        synchronized (this) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                if (device != null) {
                    if (usbManager.hasPermission(device)) {
                        debugLog("We have permission, good!");
                        if (enabled) {
                            openConnection(device);
                        }
                    }
                }
            } else {
                debugLog("permission denied for device " + device);
            }
        }
    } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
        synchronized (this) {
            if (connectedGps != null && enabled) {
                connectedGps.close();
            }
        }
    }
}
 
源代码27 项目: xmrwallet   文件: Ledger.java
private Ledger(UsbManager usbManager, UsbDevice usbDevice) throws IOException {
    final BTChipTransport transport = BTChipTransportAndroidHID.open(usbManager, usbDevice);
    Timber.d("transport opened = %s", transport.toString());
    transport.setDebug(BuildConfig.DEBUG);
    this.transport = transport;
    this.name = usbDevice.getManufacturerName() + " " + usbDevice.getProductName();
    initKey();
}
 
源代码28 项目: UVCCameraZxing   文件: USBMonitor.java
private final void processCancel(final UsbDevice device) {
	if (DEBUG) Log.v(TAG, "processCancel:");
	if (mOnDeviceConnectListener != null) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mOnDeviceConnectListener.onCancel();
			}
		});
	}
}
 
源代码29 项目: FireFiles   文件: UsbUtils.java
private static String nameForClass(UsbDevice usbDevice) {
    int classType = usbDevice.getDeviceClass();
    switch (classType) {
        case UsbConstants.USB_CLASS_AUDIO:
            return "Audio";
        case UsbConstants.USB_CLASS_CDC_DATA:
            return "CDC Control";
        case UsbConstants.USB_CLASS_COMM:
            return "Communications";
        case UsbConstants.USB_CLASS_CONTENT_SEC:
            return "Content Security";
        case UsbConstants.USB_CLASS_CSCID:
            return "Content Smart Card";
        case UsbConstants.USB_CLASS_HID:
            return "Human Interface Device";
        case UsbConstants.USB_CLASS_HUB:
            return "Hub";
        case UsbConstants.USB_CLASS_MASS_STORAGE:
            return "Mass Storage";
        case UsbConstants.USB_CLASS_MISC:
            return "Wireless Miscellaneous";
        case UsbConstants.USB_CLASS_PHYSICA:
            return "Physical";
        case UsbConstants.USB_CLASS_PRINTER:
            return "Printer";
        case UsbConstants.USB_CLASS_STILL_IMAGE:
            return "Still Image";
        case UsbConstants.USB_CLASS_VENDOR_SPEC:
            return String.format("Vendor Specific 0x%02x", classType);
        case UsbConstants.USB_CLASS_VIDEO:
            return "Video";
        case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
            return "Wireless Controller";
        default:
            return "";
    }
}
 
源代码30 项目: Easycam   文件: easycam.java
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (ACTION_USB_PERMISSION.equals(action)) {
        synchronized (this) {
            UsbDevice uDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {

                if(uDevice != null) {
                    initView();

                    // Right now the activity doesn't have focus, so if we need to manually
                    // set immersive mode.
                    if (immersive) {
                        camView.setSystemUiVisibility(
                                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                        | View.SYSTEM_UI_FLAG_FULLSCREEN);

                        currentLayout.post(setAspectRatio);
                    }
                }
                else {
                    Log.d(TAG, "USB Device not valid");
                }
            }
            else {
                Log.d(TAG, "permission denied for device " + uDevice);
            }
        }
    }
}
 
 类所在包
 同包方法