Java Code Examples for android.hardware.usb.UsbManager#requestPermission()

The following examples show how to use android.hardware.usb.UsbManager#requestPermission() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectRcManager.java    From FimiX8-RE with MIT License 6 votes vote down vote up
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;
    }
}
 
Example 2
Source File: LoginActivity.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
void attachLedger() {
    final UsbManager usbManager = getUsbManager();
    UsbDevice device = Ledger.findDevice(usbManager);
    if (device != null) {
        if (usbManager.hasPermission(device)) {
            connectLedger(usbManager, device);
        } else {
            registerReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION));
            usbManager.requestPermission(device,
                    PendingIntent.getBroadcast(this, 0,
                            new Intent(ACTION_USB_PERMISSION), 0));
        }
    } else {
        Timber.d("no ledger device found");
    }
}
 
Example 3
Source File: MainActivity.java    From ns-usbloader-mobile with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction() == null)
        return;
    switch (intent.getAction()) {
        case UsbManager.ACTION_USB_DEVICE_ATTACHED:
            usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
            if (usbManager == null)
                break;  // ???
            if (usbManager.hasPermission(usbDevice))
                isUsbDeviceAccessible = true;
            else {
                isUsbDeviceAccessible = false;
                usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(context, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
            }
            break;
        case NsConstants.REQUEST_NS_ACCESS_INTENT:
            isUsbDeviceAccessible = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
            break;
        case UsbManager.ACTION_USB_DEVICE_DETACHED:
            usbDevice = null;
            isUsbDeviceAccessible = false;
            stopService(new Intent(context, CommunicationsService.class));
            break;
        case NsConstants.SERVICE_TRANSFER_TASK_FINISHED_INTENT:
            ArrayList<NSPElement> nspElements = intent.getParcelableArrayListExtra(NsConstants.SERVICE_CONTENT_NSP_LIST);
            if (nspElements == null)
                break;
            for (int i=0; i < mDataset.size(); i++){
                for (NSPElement receivedNSPe : nspElements)
                    if (receivedNSPe.getFilename().equals(mDataset.get(i).getFilename()))
                        mDataset.get(i).setStatus(receivedNSPe.getStatus());
            }
            mAdapter.notifyDataSetChanged();
            blockUI(false);
            break;
    }
}
 
Example 4
Source File: MainActivity.java    From Chorus-RF-Laptimer with MIT License 5 votes vote down vote up
private void checkUSBPermissionsAndConnectIfAllowed() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    UsbDevice device = getAvailableUsbDevice();
    if (device == null) return;

    if (manager.hasPermission(device)) {
        connectToUsbDevice();
        return;
    }

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    manager.requestPermission(device, mPermissionIntent);
}
 
Example 5
Source File: MasterService.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private void requestUsbPermission() {
    Log.d(TAG, "requestUsbPermission");
    UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
    UsbDevice cnlDevice = UsbHidDriver.getUsbDevice(usbManager, MedtronicCnlService.USB_VID, MedtronicCnlService.USB_PID);
    PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(Constants.ACTION_USB_PERMISSION), 0);
    usbManager.requestPermission(cnlDevice, permissionIntent);
}
 
Example 6
Source File: UsbTools.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void requestPermission(final UsbDevice device, final PermissionReceiver receiver) {
    final UsbManager usbManager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
    if (usbManager == null) {
        Log.d(TAG, "UsbManager is null in requestPermission");
        return;
    }
    final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(xdrip.getAppContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
    final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    xdrip.getAppContext().registerReceiver(receiver, filter);
    usbManager.requestPermission(device, mPermissionIntent);
}
 
Example 7
Source File: UsbTools.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void requestPermission(final UsbDevice device, final PermissionReceiver receiver) {
    final UsbManager usbManager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
    if (usbManager == null) {
        Log.d(TAG, "UsbManager is null in requestPermission");
        return;
    }
    final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(xdrip.getAppContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
    final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    xdrip.getAppContext().registerReceiver(receiver, filter);
    usbManager.requestPermission(device, mPermissionIntent);
}
 
Example 8
Source File: ReactUsbSerialModule.java    From react-native-usbserial with MIT License 5 votes vote down vote up
private void requestUsbPermission(UsbManager manager,
                                  UsbDevice device,
                                  Promise p) {

    try {
        ReactApplicationContext rAppContext = getReactApplicationContext();
        PendingIntent permIntent = PendingIntent.getBroadcast(rAppContext, 0, new Intent(ACTION_USB_PERMISSION), 0);

        registerBroadcastReceiver(p);

        manager.requestPermission(device, permIntent);
    } catch (Exception e) {
        p.reject(e);
    }
}
 
Example 9
Source File: FTDI_USB_Handler.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
private void enumerate() {
	l("enumerating");

	UsbManager usbman = (UsbManager) activity
			.getSystemService(Context.USB_SERVICE);

	HashMap<String, UsbDevice> devlist = usbman.getDeviceList();
	Iterator<UsbDevice> deviter = devlist.values().iterator();
	PendingIntent pi = PendingIntent.getBroadcast(activity, 0, new Intent(
			ACTION_USB_PERMISSION), 0);

	while (deviter.hasNext()) {
		UsbDevice d = deviter.next();
		l("Found device: "
				+ String.format("%04X:%04X", d.getVendorId(), d.getProductId()));
		if (String.format("%04X:%04X", d.getVendorId(), d.getProductId()).equals(
				VID_PID)) {
			// we need to upload the hex file, first request permission
			l("Device under: " + d.getDeviceName());
			activity.registerReceiver(mPermissionReceiver, new IntentFilter(
					ACTION_USB_PERMISSION));
			if (!usbman.hasPermission(d))
				usbman.requestPermission(d, pi);
			else
				init_USB(d);

			// init_USB(d);
			break;
		}
	}
	l("no more devices found");
}
 
Example 10
Source File: USBTransport.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempts to connect to the specified accessory.
 *
 * If the permission is already granted, opens the accessory. Otherwise,
 * requests permission to use it.
 *
 * @param accessory Accessory to connect to
 */
private void connectToAccessory(UsbAccessory accessory) {

    if (accessory == null) {
        handleTransportError("Can't connect to null accessory", null);
    }

    final State state = getState();
    switch (state) {
        case LISTENING:
            UsbManager usbManager = getUsbManager();
            if (usbManager.hasPermission(accessory)) {
                logI("Already have permission to use " + accessory);
                openAccessory(accessory);
            } else {
                logI("Requesting permission to use " + accessory);

                PendingIntent permissionIntent = PendingIntent
                        .getBroadcast(getContext(), 0,
                                new Intent(ACTION_USB_PERMISSION), 0);
                usbManager.requestPermission(accessory, permissionIntent);
            }

            break;

        default:
            logW("connectToAccessory() called from state " + state +
                    "; doing nothing");
    }
}
 
Example 11
Source File: TerminalFragment.java    From SimpleUsbTerminal with MIT License 4 votes vote down vote up
private void connect(Boolean permissionGranted) {
    UsbDevice device = null;
    UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
    for(UsbDevice v : usbManager.getDeviceList().values())
        if(v.getDeviceId() == deviceId)
            device = v;
    if(device == null) {
        status("connection failed: device not found");
        return;
    }
    UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
    if(driver == null) {
        driver = CustomProber.getCustomProber().probeDevice(device);
    }
    if(driver == null) {
        status("connection failed: no driver for device");
        return;
    }
    if(driver.getPorts().size() < portNum) {
        status("connection failed: not enough ports at device");
        return;
    }
    usbSerialPort = driver.getPorts().get(portNum);
    UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
    if(usbConnection == null && permissionGranted == null && !usbManager.hasPermission(driver.getDevice())) {
        PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(Constants.INTENT_ACTION_GRANT_USB), 0);
        usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
        return;
    }
    if(usbConnection == null) {
        if (!usbManager.hasPermission(driver.getDevice()))
            status("connection failed: permission denied");
        else
            status("connection failed: open failed");
        return;
    }

    connected = Connected.Pending;
    try {
        usbSerialPort.open(usbConnection);
        usbSerialPort.setParameters(baudRate, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), usbConnection, usbSerialPort);
        service.connect(socket);
        // usb connect is not asynchronous. connect-success and connect-error are returned immediately from socket.connect
        // for consistency to bluetooth/bluetooth-LE app use same SerialListener and SerialService classes
        onSerialConnect();
    } catch (Exception e) {
        onSerialConnectError(e);
    }
}
 
Example 12
Source File: MainActivity.java    From ns-usbloader-mobile with GNU General Public License v3.0 4 votes vote down vote up
private void uploadFiles(){
    ArrayList<NSPElement> NSPElementsToSend = new ArrayList<>();
    for (NSPElement element: mDataset){
        if (element.isSelected())
            NSPElementsToSend.add(element);
    }
    // Do we have files to send?
    if (NSPElementsToSend.isEmpty()){
        Snackbar.make(findViewById(android.R.id.content), getString(R.string.nothing_selected_message), Snackbar.LENGTH_LONG).show();
        return;
    }
    // Do we have selected protocol?
    if (drawerNavView.getCheckedItem() == null) {
        Snackbar.make(findViewById(android.R.id.content), getString(R.string.no_protocol_selected_message), Snackbar.LENGTH_LONG).show();
        return;
    }
    Intent serviceStartIntent = new Intent(this, CommunicationsService.class);
    serviceStartIntent.putExtra(NsConstants.NS_RESULT_RECEIVER, nsResultReciever);
    serviceStartIntent.putParcelableArrayListExtra(NsConstants.SERVICE_CONTENT_NSP_LIST, NSPElementsToSend);
    // Is it TF Net transfer?
    if (drawerNavView.getCheckedItem().getItemId() == R.id.nav_tf_net){
        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_TF_NET);
        SharedPreferences sp = getSharedPreferences("NSUSBloader", MODE_PRIVATE);

        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_NS_DEVICE_IP, sp.getString("SNsIP", "192.168.1.42"));
        if (sp.getBoolean("SAutoIP", true))
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_IP, "");
        else
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_IP, sp.getString("SServerIP", "192.168.1.142"));
        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_PORT, sp.getInt("SServerPort", 6042));
        startService(serviceStartIntent);
        blockUI(true);
        return;
    }
    // Ok, so it's something USB related
    UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    // Do we have manager?
    if (usbManager == null) {
        NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), "Internal issue: getSystemService(Context.USB_SERVICE) returned null");
        return;
    }
    // If device not connected
    if (usbDevice == null){
        HashMap<String, UsbDevice> deviceHashMap;

        deviceHashMap = usbManager.getDeviceList();

        for (UsbDevice device : deviceHashMap.values()) {
            if (device.getVendorId() == 1406 && device.getProductId() == 12288) {
                usbDevice = device;
            }
        }
        // If it's still not connected then it's really not connected.
        if (usbDevice == null) {
            NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), getResources().getString(R.string.ns_not_found_in_connected));
            return;
        }
        // If we have NS connected check for permissions
        if (! usbManager.hasPermission(usbDevice)){
            usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(this, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
            return;
        }
    }
    if (! isUsbDeviceAccessible){
        usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(this, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
        return;
    }

    switch (drawerNavView.getCheckedItem().getItemId()){
        case R.id.nav_tf_usb:
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_TF_USB);
            break;
        case R.id.nav_gl:
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_GL_USB);
            break;
        default:
            Snackbar.make(findViewById(android.R.id.content), getString(R.string.unknown_protocol_error), Snackbar.LENGTH_LONG).show(); // ?_?
            return;
    }
    serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_NS_DEVICE, usbDevice);
    startService(serviceStartIntent);
    blockUI(true);
}
 
Example 13
Source File: UsbCommService.java    From AndrOBD with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void start()
{
	if (sPort != null)
	{
		final UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
		if (usbManager == null)
		{
               connectionFailed();
               return;
           }
		
		UsbDevice device = sPort.getDriver().getDevice();
		if (!usbManager.hasPermission(device))
		{
			PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
			usbManager.requestPermission(device, usbPermissionIntent);
			connectionFailed();
			return;
		}

           UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
		if (connection == null)
		{
			connectionFailed();
			return;
		}

		try
		{
			sPort.open(connection);
			sPort.setDTR(true);
			sPort.setParameters(38400, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

			log.info("Starting io manager ..");
			Thread runner = new Thread(mSerialIoManager);
			runner.setPriority(Thread.MAX_PRIORITY);
			runner.start();

			// we are connected -> signal connectionEstablished
			connectionEstablished(sPort.toString());
		}
		catch (IOException e)
		{
			log.log(Level.SEVERE, "Error setting up device: " + e.getMessage(), e);
			try
			{
				sPort.close();
			}
			catch (IOException e2)
			{
				// Ignore.
			}
			connectionFailed();
			sPort = null;
		}
	}
}
 
Example 14
Source File: UsbLinkAndroid.java    From crazyflie-android-client with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initialize the USB device. Determines endpoints and prepares communication.
 *
 * @param vid
 * @param pid
 * @throws IOException if the device cannot be opened
 * @throws SecurityException
 */
public void initDevice(int vid, int pid) throws IOException, SecurityException {
    mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
    if (mUsbManager == null) {
        throw new IllegalArgumentException("UsbManager == null!");
    }

    List<UsbDevice> usbDevices = findUsbDevices(mUsbManager, (short) vid, (short) pid);
    if (usbDevices.isEmpty() || usbDevices.get(0) == null) {
        throw new IOException("USB device not found. (VID: " + vid + ", PID: " + pid + ")");
    }
    // TODO: Only gets the first USB device that is found
    this.mUsbDevice = usbDevices.get(0);

    //request permissions
    if (mUsbDevice != null && !mUsbManager.hasPermission(mUsbDevice)) {
        Log.d(LOG_TAG, "Request permission");
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext.getPackageName()+".USB_PERMISSION"), 0);
        mUsbManager.requestPermission(mUsbDevice, mPermissionIntent);
    } else if (mUsbDevice != null && mUsbManager.hasPermission(mUsbDevice)) {
        Log.d(LOG_TAG, "Has permission");
    } else {
        Log.d(LOG_TAG, "device == null");
        return;
    }

    Log.d(LOG_TAG, "setDevice " + this.mUsbDevice);
    // find interface
    if (this.mUsbDevice.getInterfaceCount() != 1) {
        Log.e(LOG_TAG, "Could not find interface");
        return;
    }
    mIntf = this.mUsbDevice.getInterface(0);
    // device should have two endpoints
    if (mIntf.getEndpointCount() != 2) {
        Log.e(LOG_TAG, "Could not find endpoints");
        return;
    }
    // endpoints should be of type bulk
    UsbEndpoint ep = mIntf.getEndpoint(0);
    if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {
        Log.e(LOG_TAG, "Endpoint is not of type bulk");
        return;
    }
    // check endpoint direction
    if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
        mEpIn = mIntf.getEndpoint(0);
        mEpOut = mIntf.getEndpoint(1);
    } else {
        mEpIn = mIntf.getEndpoint(1);
        mEpOut = mIntf.getEndpoint(0);
    }

    UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);
    if (connection != null && connection.claimInterface(mIntf, true)) {
        Log.d(LOG_TAG, "open SUCCESS");
        mConnection = connection;
    } else {
        Log.d(LOG_TAG, "open FAIL");
        throw new IOException("could not open usb connection");
    }
}
 
Example 15
Source File: TerminalFragment.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void connect() {
    UsbDevice device = null;
    UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
    for(UsbDevice v : usbManager.getDeviceList().values())
        if(v.getDeviceId() == deviceId)
            device = v;
    if(device == null) {
        status("connection failed: device not found");
        return;
    }
    UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
    if(driver == null) {
        driver = CustomProber.getCustomProber().probeDevice(device);
    }
    if(driver == null) {
        status("connection failed: no driver for device");
        return;
    }
    if(driver.getPorts().size() < portNum) {
        status("connection failed: not enough ports at device");
        return;
    }
    usbSerialPort = driver.getPorts().get(portNum);
    UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
    if(usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
        usbPermission = UsbPermission.Requested;
        PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
        usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
        return;
    }
    if(usbConnection == null) {
        if (!usbManager.hasPermission(driver.getDevice()))
            status("connection failed: permission denied");
        else
            status("connection failed: open failed");
        return;
    }

    try {
        usbSerialPort.open(usbConnection);
        usbSerialPort.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        if(withIoManager) {
            usbIoManager = new SerialInputOutputManager(usbSerialPort, this);
            Executors.newSingleThreadExecutor().submit(usbIoManager);
        }
        status("connected");
        connected = true;
        controlLines.start();
    } catch (Exception e) {
        status("connection failed: " + e.getMessage());
        disconnect();
    }
}