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

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

源代码1 项目: FimiX8-RE   文件: ConnectRcManager.java
public synchronized void connectRC(Context mContext) {
    if (!this.isTryConnect) {
        this.isTryConnect = true;
        UsbManager usbManager = (UsbManager) mContext.getSystemService("usb");
        this.mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        if (usbManager != null) {
            UsbAccessory[] accessories = usbManager.getAccessoryList();
            UsbAccessory accessory = accessories == null ? null : accessories[0];
            if (accessory != null) {
                if (usbManager.hasPermission(accessory)) {
                    CommunicationManager.getCommunicationManager().setAccessory(accessory);
                    CommunicationManager.getCommunicationManager().startConnectThread(mContext, ConnectType.Aoa);
                } else if (!this.isRequestPermission) {
                    usbManager.requestPermission(accessory, this.mPermissionIntent);
                    this.isRequestPermission = true;
                }
            }
        }
        this.isTryConnect = false;
    }
}
 
源代码2 项目: AndroidUSBCamera   文件: USBMonitor.java
/**
 * register BroadcastReceiver to monitor USB events
 * @throws IllegalStateException
 */
public synchronized void register() throws IllegalStateException {
	if (destroyed) throw new IllegalStateException("already destroyed");
	if (mPermissionIntent == null) {
		if (DEBUG) Log.i(TAG, "register:");
		final Context context = mWeakContext.get();
		if (context != null) {
			mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
			final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
			// ACTION_USB_DEVICE_ATTACHED never comes on some devices so it should not be added here
			filter.addAction(ACTION_USB_DEVICE_ATTACHED);
			filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
			context.registerReceiver(mUsbReceiver, filter);
		}
		// start connection check
		mDeviceCounts = 0;
		mAsyncHandler.postDelayed(mDeviceCheckRunnable, 1000);
	}
}
 
@ReactMethod
public void openDeviceAsync(ReadableMap deviceObject, Promise p) {

    try {
        int prodId = deviceObject.getInt("productId");
        UsbManager manager = getUsbManager();
        UsbSerialDriver driver = getUsbSerialDriver(prodId, manager);

        if (manager.hasPermission(driver.getDevice())) {
            WritableMap usd = createUsbSerialDevice(manager, driver);

            p.resolve(usd);
        } else {
            requestUsbPermission(manager, driver.getDevice(), p);
        }

    } catch (Exception e) {
        p.reject(e);
    }
}
 
源代码4 项目: sniffer154   文件: SnifferDeviceService.java
private void setupUsbDevice() {
	mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
	mSerialDevice = UsbSerialProber.acquire(mUsbManager);
	if (mSerialDevice == null) {
		Toast.makeText(this, "Cannot find USB device", Toast.LENGTH_SHORT)
				.show();
	} else {
		try {
			mSerialDevice.open();
		} catch (IOException e) {
			Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
			try {
				mSerialDevice.close();
			} catch (IOException e2) {
				// Ignore.
			}
			mSerialDevice = null;
			return;
		}
	}
	mSerialIoManager = new SerialInputOutputManager(mSerialDevice,
			mListener);
	mExecutor.submit(mSerialIoManager);
}
 
源代码5 项目: gsn   文件: FTDI_USB_Handler.java
public void onReceive(Context context, Intent intent) {
	String action = intent.getAction();

	if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
		UsbDevice dev = (UsbDevice) intent
				.getParcelableExtra(UsbManager.EXTRA_DEVICE);
		if (dev != null) {
			if (String.format("%04X:%04X", dev.getVendorId(), dev.getProductId())
					.equals(VID_PID)) {
				if (usbIf != null && conn != null) {
					conn.releaseInterface(usbIf);
					conn.close();
				}
			}
		}
	}
}
 
源代码6 项目: Android-Bridge-App   文件: USBConnectionManager.java
public void checkForDJIAccessory() {
    mUsbManager = (UsbManager) BridgeApplication.getInstance().getSystemService(Context.USB_SERVICE);
    UsbAccessory[] accessoryList = mUsbManager.getAccessoryList();
    if (accessoryList != null
        && accessoryList.length > 0
        && !TextUtils.isEmpty(accessoryList[0].getManufacturer())
        && accessoryList[0].getManufacturer().equals("DJI")) {
        BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(true));
        //Check permission
        mAccessory = accessoryList[0];
        if (mUsbManager.hasPermission(mAccessory)) {
            Log.d(TAG, "RC CONNECTED");
        } else {
            Log.d(TAG, "NO Permission to USB Accessory");
            DJILogger.e(TAG, "NO Permission to USB Accessory");
            //mUsbManager.requestPermission(mAccessory, null);
        }
    } else {
        BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(false));
        Log.d(TAG, "RC DISCONNECTED");
    }
}
 
源代码7 项目: walt   文件: BaseUsbConnection.java
@Override
public void onReceive(Context context, Intent intent) {

    if (usbDevice == null) {
        logger.log("USB device was not properly opened");
        return;
    }

    if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) &&
            usbDevice.equals(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE))){
        usbConnection = usbManager.openDevice(usbDevice);

        BaseUsbConnection.this.context.registerReceiver(disconnectReceiver,
                new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));

        onConnect();

        broadcastManager.sendBroadcast(new Intent(getConnectIntent()));
    } else {
        logger.log("Could not get permission to open the USB device");
    }
    BaseUsbConnection.this.context.unregisterReceiver(respondToUsbPermission);
}
 
源代码8 项目: ns-usbloader-mobile   文件: GoldLeaf.java
GoldLeaf(ResultReceiver resultReceiver,
         Context context,
         UsbDevice usbDevice,
         UsbManager usbManager,
         ArrayList<NSPElement> nspElements) throws Exception {
    super(resultReceiver, context, usbDevice, usbManager);

    this.nspElements = nspElements;
    String fileName;
    InputStream fileInputStream;

    fileInputStream = context.getContentResolver().openInputStream(nspElements.get(0).getUri());
    fileName = nspElements.get(0).getFilename();
    pfsElement = new PFSProvider(fileInputStream, fileName);
    if (! pfsElement.init())
        throw new Exception("GL File provided have incorrect structure and won't be uploaded.");
}
 
源代码9 项目: xDrip-Experimental   文件: 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;
}
 
源代码10 项目: xDrip   文件: UsbTools.java
@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
        synchronized (this) {
            final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                if (device != null) {
                    onGranted(device);
                }
            } else {
                Log.d(TAG, "permission denied for device " + device);
            }
            xdrip.getAppContext().unregisterReceiver(this);
        }
    }
}
 
源代码11 项目: green_android   文件: RequestLoginActivity.java
@Override
public void onResume() {
    super.onResume();
    mActiveNetwork.setText(getString(R.string.id_s_network, networkData.getName()));

    final Intent intent = getIntent();

    if (ACTION_USB_ATTACHED.equalsIgnoreCase(intent.getAction())) {
        onUsbAttach(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
    }

    if (mUsb != null || mInLedgerDashboard) {
        // Continue displaying instructions until the user opens the
        // correct wallet app, or log in completes/errors out
        return;
    }

    // No hardware wallet, jump to PIN or 1st screen entry
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    if (AuthenticationHandler.hasPin(this))
        startActivityForResult(new Intent(this, PinActivity.class), 0);
    else
        startActivityForResult(new Intent(this, FirstScreenActivity.class), 0);
}
 
源代码12 项目: USBHIDTerminal   文件: AbstractUSBHIDService.java
public void onReceive(Context context, Intent intent) {
	String action = intent.getAction();
	if (Consts.ACTION_USB_PERMISSION.equals(action)) {
		setDevice(intent);
	}
	if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
		setDevice(intent);
		if (device == null) {
			onDeviceConnected(device);
		}
	}
	if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
		if (device != null) {
			device = null;
			if (usbThreadDataReceiver != null) {
				usbThreadDataReceiver.stopThis();
			}
			eventBus.post(new DeviceDetachedEvent());
			onDeviceDisconnected(device);
		}
	}
}
 
源代码13 项目: UsbSerial   文件: UsbService.java
@Override
public void onCreate() {
    this.context = this;
    UsbService.SERVICE_CONNECTED = true;
    setFilter();
    usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    builder = SerialPortBuilder.createSerialPortBuilder(this);

    boolean ret = builder.openSerialPorts(context, BAUD_RATE,
            UsbSerialInterface.DATA_BITS_8,
            UsbSerialInterface.STOP_BITS_1,
            UsbSerialInterface.PARITY_NONE,
            UsbSerialInterface.FLOW_CONTROL_OFF);

    if(!ret)
        Toast.makeText(context, "No Usb serial ports available", Toast.LENGTH_SHORT).show();
}
 
源代码14 项目: USB-OTG-CH340-UART-interface   文件: InitCH340.java
/**
 * initialize ch340 parameters.
 *
 * @param context Application context.
 */
public static void initCH340(Context context) {
    if (context == null) return;
    Context appContext = context.getApplicationContext();
    mUsbManager = (UsbManager) appContext.getSystemService(Context.USB_SERVICE);
    if (mUsbManager != null) {
        HashMap<String, UsbDevice> deviceHashMap = mUsbManager.getDeviceList();
        LogUtils.e(TAG, "deviceHashMap.size()=" + deviceHashMap.size());
        for (UsbDevice device : deviceHashMap.values()) {
            LogUtils.i(TAG, "ProductId:" + device.getProductId() + ",VendorId:" + device.getVendorId());
            if (device.getProductId() == 29987 && device.getVendorId() == 6790) {
                mUsbDevice = device;
                if (mUsbManager.hasPermission(device)) {
                    loadDriver(appContext, mUsbManager);
                } else {
                    if (listener != null) {
                        listener.result(false);
                    }
                }
                break;
            }
        }
    }
}
 
源代码15 项目: xDrip-Experimental   文件: SyncingService.java
static public boolean isG4Connected(Context c){
    UsbManager manager = (UsbManager) c.getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> deviceList = manager.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){
            Log.i("CALIBRATION-CHECK-IN: ", "Dexcom Found!");
            return true;
        }
    }
    return false;
}
 
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) {
                    Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED~", Toast.LENGTH_SHORT).show();
                    InitCH340.loadDriver(MyApplication.getContext(), InitCH340.getmUsbManager());
                }
            } else {
                Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED null!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
源代码17 项目: remoteyourcam-usb   文件: PtpUsbService.java
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (ACTION_USB_PERMISSION.equals(action)) {
        unregisterPermissionReceiver(context);
        synchronized (this) {
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                connect(context, device);
            } else {
                //TODO report
            }
        }
    }
}
 
源代码18 项目: usb-serial-for-android   文件: DevicesFragment.java
void refresh() {
    UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
    UsbSerialProber usbDefaultProber = UsbSerialProber.getDefaultProber();
    UsbSerialProber usbCustomProber = CustomProber.getCustomProber();
    listItems.clear();
    for(UsbDevice device : usbManager.getDeviceList().values()) {
        UsbSerialDriver driver = usbDefaultProber.probeDevice(device);
        if(driver == null) {
            driver = usbCustomProber.probeDevice(device);
        }
        if(driver != null) {
            for(int port = 0; port < driver.getPorts().size(); port++)
                listItems.add(new ListItem(device, port, driver));
        } else {
            listItems.add(new ListItem(device, 0, null));
        }
    }
    listAdapter.notifyDataSetChanged();
}
 
@Override
protected void onStart() {
    super.onStart();

    /* Setup USB */
    usb = new Usb(this);
    usb.setUsbManager((UsbManager) getSystemService(Context.USB_SERVICE));
    usb.setOnUsbChangeListener(this);

    // Handle two types of intents. Device attachment and permission
    registerReceiver(usb.getmUsbReceiver(), new IntentFilter(Usb.ACTION_USB_PERMISSION));
    registerReceiver(usb.getmUsbReceiver(), new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
    registerReceiver(usb.getmUsbReceiver(), new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));


    // Handle case where USB device is connected before app launches;
    // hence ACTION_USB_DEVICE_ATTACHED will not occur so we explicitly call for permission
    usb.requestPermission(this, Usb.USB_VENDOR_ID, Usb.USB_PRODUCT_ID);
}
 
源代码20 项目: libcommon   文件: UsbDeviceInfo.java
/**
 * USB機器情報(ベンダー名・製品名・バージョン・シリアル等)を取得する
 * @param manager
 * @param device
 * @param out
 * @return
 */
@SuppressLint("NewApi")
public static UsbDeviceInfo getDeviceInfo(
	@NonNull final UsbManager manager,
	@Nullable final UsbDevice device, @Nullable final UsbDeviceInfo out) {

	final UsbDeviceConnection connection
		= (device != null && manager.hasPermission(device))
			? manager.openDevice(device) : null;

	try {
		return getDeviceInfo(connection, device, out);
	} finally {
		if (connection != null) {
			connection.close();
		}
	}
}
 
源代码21 项目: 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");
	}
}
 
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (StkWriter.ACTION_USB_PERMISSION.equals(action)) {

    } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
        // USBを閉じる
        /*
        mStkWriter.closeUsb();
        mTextViewComment.setText(R.string.disconnect_usb);
        mButtonConnect.setEnabled(false);
        mButtonSend.setVisibility(Button.INVISIBLE);
        mButtonBack.setVisibility(Button.INVISIBLE);
        */
    }
}
 
源代码23 项目: xmrwallet   文件: LoginActivity.java
private void registerDetachReceiver() {
    detachReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                unregisterDetachReceiver();
                final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                Timber.i("Ledger detached!");
                if (device != null)
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this,
                                    getString(R.string.toast_ledger_detached, device.getProductName()),
                                    Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                Ledger.disconnect();
                onLedgerAction();
            }
        }
    };

    registerReceiver(detachReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
}
 
源代码24 项目: FTCVision   文件: FtcRobotControllerActivity.java
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(intent.getAction())) {
        // a new USB device has been attached
        DbgLog.msg("USB Device attached; app restart may be needed");
    }
}
 
源代码25 项目: PHONK   文件: PSerial.java
@PhonkMethod(description = "starts serial", example = "")
public void start() {
    getAppRunner().whatIsRunning.add(this);
    mUsbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_USB_PERMISSION);
    // filter.addAction(ACTION_USB_DETACHED);
    // filter.addAction(ACTION_USB_ATTACHED);
    getContext().registerReceiver(usbReceiver, filter);
    findSerialPortDevice();
}
 
源代码26 项目: apollo-DuerOS   文件: AOAAccessoryReceiver.java
public void registerReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    filter.addAction(ACTION_USB_PERMISSION);
    mContext.registerReceiver(this, filter);
}
 
源代码27 项目: xDrip-plus   文件: UsbTools.java
public static UsbDevice getUsbDevice(final int vendorId, final int productId, final String search) {

        final UsbManager manager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
        if (manager == null) return null;
        final HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
            final UsbDevice device = entry.getValue();
            if (device.getVendorId() == vendorId && device.getProductId() == productId
                    && device.toString().contains(search)) {
                Log.d(TAG, "Found device: " + entry.getKey() + " " + device.toString());
                return device;
            }
        }
        return null;
    }
 
源代码28 项目: 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();
            }
        }
    }
}
 
源代码29 项目: Android-Bridge-App   文件: BridgeActivity.java
/**
 * ACTION_USB_ACCESSORY_ATTACHED is an Activity Broadcast.
 * Thus this needs to be here not inside {@link USBConnectionManager}
 */
@Override
protected void onNewIntent(Intent intent) {
    if (intent.getAction() != null)
        switch (intent.getAction()) {
            case UsbManager.ACTION_USB_ACCESSORY_ATTACHED:
                BridgeApplication.getInstance().getBus().post(new USBConnectionManager.USBConnectionEvent(true));
                break;
        }
    super.onNewIntent(intent);
}
 
源代码30 项目: UsbSerial   文件: UsbService.java
@Override
public void onCreate() {
    this.context = this;
    serialPortConnected = false;
    UsbService.SERVICE_CONNECTED = true;
    setFilter();
    usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    findSerialPortDevice();
}
 
 类所在包
 同包方法