Example usage for android.content Context USB_SERVICE

List of usage examples for android.content Context USB_SERVICE

Introduction

In this page you can find the example usage for android.content Context USB_SERVICE.

Prototype

String USB_SERVICE

To view the source code for android.content Context USB_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.hardware.usb.UsbManager for access to USB devices (as a USB host) and for controlling this device's behavior as a USB device.

Usage

From source file:com.physicaroid.pocketduino.cordova.PocketDuino.java

private void getDeviceName(CallbackContext callbackContext) {
    Activity activity = cordova.getActivity();
    UsbManager mUsbManager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> map = mUsbManager.getDeviceList();
    Iterator<UsbDevice> it = map.values().iterator();
    while (it.hasNext()) {
        UsbDevice device = it.next();/*from www.java 2  s.c o m*/
        // use device info
        Log.v(POCKETDUINO, "!!!--- USB Device Name ---!!!");
        Log.v(POCKETDUINO, device.getDeviceName());
        Log.v(POCKETDUINO, "!!!--- USB Device Product ID ---!!!");
        Log.v(POCKETDUINO, Integer.toString(device.getProductId()));
        Log.v(POCKETDUINO, "!!!--- USB Device Vendor ID ---!!!");
        Log.v(POCKETDUINO, Integer.toString(device.getVendorId()));
        Log.v(POCKETDUINO, "!!!--- USB Device Hash Code ---!!!");
        Log.v(POCKETDUINO, Integer.toString(device.hashCode()));
    }
}

From source file:de.tum.mw.lfe.drtrc.MainActivity.java

private void initUsb() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    // Find all available drivers from attached devices.
    List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
    if (availableDrivers.isEmpty()) {
        l("No device/driver");
        return;//from w  ww.  ja  v a  2  s.com
    }

    // Open a connection to the first available driver.
    UsbSerialDriver mDriver = availableDrivers.get(0);
    //are we allowed to access?
    UsbDevice device = mDriver.getDevice();

    if (!manager.hasPermission(device)) {
        //ask for permission
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(GET_USB_PERMISSION), 0);
        mContext.registerReceiver(mPermissionReceiver, new IntentFilter(GET_USB_PERMISSION));
        manager.requestPermission(device, pi);
        l("USB ask for permission");
        return;
    }

    UsbDeviceConnection connection = manager.openDevice(mDriver.getDevice());
    if (connection == null) {
        l("USB connection == null");
        return;
    }

    try {
        sPort = (UsbSerialPort) mDriver.getPorts().get(0);//Most have just one port (port 0)
        sPort.open(connection);
        sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
    } catch (IOException e) {
        l("Error setting up device: " + e.getMessage());
        try {
            sPort.close();
        } catch (IOException e2) {
            /*ignore*/}
        sPort = null;
        return;
    }

    onDeviceStateChange();

}

From source file:fr.bmartel.android.fadecandy.service.FadecandyService.java

/**
 * Open USB device & choose USBEndpoint.
 *
 * @param device Usb device object./*from w  ww.  j  a  v  a2s.  c  o  m*/
 * @return Ubs item composed of USBDevice , USBEndpoint & UsbConnection
 */
private UsbItem openDevice(UsbDevice device) {

    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    try {
        UsbDeviceConnection connection = manager.openDevice(device);

        Log.v("USB", "Device name=" + device.getDeviceName());

        UsbInterface intf = null;

        for (int interfaceIndex = 0; interfaceIndex < device.getInterfaceCount(); interfaceIndex++) {

            UsbInterface usbInterface = device.getInterface(interfaceIndex);

            if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC) {
                intf = usbInterface;
            }
        }

        if (intf == null) {
            intf = device.getInterface(0);
        }

        UsbEndpoint endpoint = intf.getEndpoint(0);

        if (connection != null) {
            connection.claimInterface(intf, true);
        } else {
            Log.e(TAG, "USB connection error");
            return null;
        }

        return new UsbItem(device, connection, endpoint);

    } catch (IllegalArgumentException e) {
    }
    return null;
}

From source file:com.github.mjdev.libaums.usbfileman.MainActivity.java

/**
* Searches for connected mass storage devices, and initializes them if it
* could find some./* w  w  w  . jav a 2s.  c  om*/
*/
private void discoverDevice() {
    UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(this);

    if (devices.length == 0) {
        Log.w(TAG, "no device found!");
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("No device");
        listView.setAdapter(null);
        return;
    }

    // we only use the first device
    device = devices[0];

    UsbDevice usbDevice = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);

    if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
        Log.d(TAG, "received usb device via intent");
        // requesting permission is not needed in this case
        setupDevice();
    } else {
        // first request permission from user to communicate with the
        // underlying
        // UsbDevice
        PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION),
                0);
        usbManager.requestPermission(device.getUsbDevice(), permissionIntent);
    }
}

From source file:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

    // Get the local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    mBluetoothDevice = null;//w  ww .  j a v a2 s.co m

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

From source file:com.example.nfcreaderorigin.MainActivity.java

/** Called when the activity is first created. */
@Override//from www  .  j ava2 s.  c  o  m
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setBlockNumber();
    // Get USB manager
    mManager = (UsbManager) getSystemService(Context.USB_SERVICE);

    // Initialize reader
    mReader = new Reader(mManager);
    mReader.setOnStateChangeListener(new OnStateChangeListener() {

        @Override
        public void onStateChange(int slotNum, int prevState, int currState) {

            if (prevState < Reader.CARD_UNKNOWN || prevState > Reader.CARD_SPECIFIC) {
                prevState = Reader.CARD_UNKNOWN;
            }

            if (currState < Reader.CARD_UNKNOWN || currState > Reader.CARD_SPECIFIC) {
                currState = Reader.CARD_UNKNOWN;
            }

            // Create output string
            final String outputString = "Slot " + slotNum + ": " + stateStrings[prevState] + " -> "
                    + stateStrings[currState];
            final String state = stateStrings[currState];

            // Show output
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    logMsg(outputString);
                    if (state.equals("Present")) {
                        mAuthenticateRead = false;
                        if (mReadMode) {
                            setBlockNumber();
                            try {

                                mTaskReadStart = false;
                                mTaskStart = false;
                                mTaskWriteStart = false;

                                TimeRead = 0;
                                TimeWrite = 0;
                                timeEnd = 0;
                                initStart = 0;
                                nowRead = 0;
                                nowWrite = 0;
                                nowStart = 0;

                                mBlockAuthen = true;
                                mReadMode = true;
                                mWriteMode = false;

                                System.gc();

                                reader();

                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }
                }
            });
        }
    });

    // Register receiver for USB permission
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mReceiver, filter);

    sdf = new SimpleDateFormat("mm:ss.SSS");

    mResponseTextView = (TextView) findViewById(R.id.main_text_view_response);
    mResponseTextView.setMovementMethod(new ScrollingMovementMethod());
    mResponseTextView.setMaxLines(MAX_LINES);
    mResponseTextView.setText("");

    mTextType = (TextView) findViewById(R.id.textType);
    mReadTime = (TextView) findViewById(R.id.textViewReadSet);
    mWriteTime = (TextView) findViewById(R.id.textViewWriteSet);
    mEndTime = (TextView) findViewById(R.id.textViewEndSet);

    mWriteType = (EditText) findViewById(R.id.EditText_writeDataType);
    mQty = (EditText) findViewById(R.id.QTY);

    formatter = new DecimalFormat("###,###,###.##");

    mWriteDataBalanceEditText = (EditText) findViewById(R.id.EditText_writeDataBalance);
    mWriteDataIdEditText = (EditText) findViewById(R.id.EditText_writeDataId);

    mTextMode = (TextView) findViewById(R.id.textMode);
    mTextBalance = (TextView) findViewById(R.id.BALANCE);

    mTextId = (TextView) findViewById(R.id.textId);
    // Initialize reader spinner

    for (UsbDevice device : mManager.getDeviceList().values()) {
        if (mReader.isSupported(device)) {
            mReaderAdapterX = device.getDeviceName().toString();
        }
    }
    // Initialize open button
    mOpenButton = (Button) findViewById(R.id.btnStart);
    mOpenButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            getDevices();
            // Disable open button
            mOpenButton.setEnabled(false);

        }
    });

    // Initialize close button
    mCloseButton = (Button) findViewById(R.id.btnStop);
    mCloseButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // Disable buttons

            mOpenButton.setEnabled(false);
            // Clear slot items

            // Close reader
            logMsg("Closing reader...");
            new CloseTask().execute();
        }
    });

    mWriteData = (Button) findViewById(R.id.btnWrite);
    mWriteData.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mAuthenticateRead == true) {
                mBlockWrite = true;
                setBlockNumber();
                mReadMode = false;
                mWriteMode = true;
                mTextMode.setText("- W R I T E -");
                //               mReadData.setVisibility(View.VISIBLE);
                //               mWriteData.setVisibility(View.GONE);
                try {
                    writer();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Please Authenticate first", Toast.LENGTH_SHORT).show();
            }

        }
    });

    mReadData = (Button) findViewById(R.id.btnRead);
    mReadData.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            mBlockAuthen = true;
            setBlockNumber();
            mReadMode = true;
            mWriteMode = false;
            mTextMode.setText("- R E A D -");
            //            mReadData.setVisibility(View.GONE);
            //            mWriteData.setVisibility(View.VISIBLE);

        }
    });

    // PIN verification command (ACOS3)
    byte[] pinVerifyData = { (byte) 0x80, 0x20, 0x06, 0x00, 0x08, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
            (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };

    // Initialize PIN verify structure (ACOS3)
    mPinVerify.setTimeOut(0);
    mPinVerify.setTimeOut2(0);
    mPinVerify.setFormatString(0);
    mPinVerify.setPinBlockString(0x08);
    mPinVerify.setPinLengthFormat(0);
    mPinVerify.setPinMaxExtraDigit(0x0408);
    mPinVerify.setEntryValidationCondition(0x03);
    mPinVerify.setNumberMessage(0x01);
    mPinVerify.setLangId(0x0409);
    mPinVerify.setMsgIndex(0);
    mPinVerify.setTeoPrologue(0, 0);
    mPinVerify.setTeoPrologue(1, 0);
    mPinVerify.setTeoPrologue(2, 0);
    mPinVerify.setData(pinVerifyData, pinVerifyData.length);

    // PIN modification command (ACOS3)
    byte[] pinModifyData = { (byte) 0x80, 0x24, 0x00, 0x00, 0x08, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
            (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };

    // Initialize PIN modify structure (ACOS3)
    mPinModify.setTimeOut(0);
    mPinModify.setTimeOut2(0);
    mPinModify.setFormatString(0);
    mPinModify.setPinBlockString(0x08);
    mPinModify.setPinLengthFormat(0);
    mPinModify.setInsertionOffsetOld(0);
    mPinModify.setInsertionOffsetNew(0);
    mPinModify.setPinMaxExtraDigit(0x0408);
    mPinModify.setConfirmPin(0x01);
    mPinModify.setEntryValidationCondition(0x03);
    mPinModify.setNumberMessage(0x02);
    mPinModify.setLangId(0x0409);
    mPinModify.setMsgIndex1(0);
    mPinModify.setMsgIndex2(0x01);
    mPinModify.setMsgIndex3(0);
    mPinModify.setTeoPrologue(0, 0);
    mPinModify.setTeoPrologue(1, 0);
    mPinModify.setTeoPrologue(2, 0);
    mPinModify.setData(pinModifyData, pinModifyData.length);

    // Initialize read key option
    mReadKeyOption.setTimeOut(0);
    mReadKeyOption.setPinMaxExtraDigit(0x0408);
    mReadKeyOption.setKeyReturnCondition(0x01);
    mReadKeyOption.setEchoLcdStartPosition(0);
    mReadKeyOption.setEchoLcdMode(0x01);

    // Disable buttons
    //      mCloseButton.setEnabled(false);
    //      mControlButton.setEnabled(false);

    // Hide input window
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

From source file:me.spadival.podmode.PodModeService.java

private podCommand readCommand() {
    byte[] rbuf = new byte[4096];
    int len = 0;//from w ww. j a  va 2 s. c om
    boolean notEnoughData = false;

    while (mPodRunning) {

        if (Thread.interrupted())
            return null;

        if (mReadLen < 6 || notEnoughData) {

            try {
                len = mSerialRead(rbuf);
            } catch (NullPointerException e) {
                Log.d("PodMode", "Read failed - Null pointer");
                mPodRunning = false;
            }

            if (len > 0) {
                System.arraycopy(rbuf, 0, mReadBuffer, mReadLen, len);
                mReadLen += len;
                notEnoughData = false;
            } else if (len < 0) {
                Log.d("PodMode read error : ", String.valueOf(len));

                if (mDeviceType == deviceType.FT232PL2303) {
                    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));
                    mSerialHost.begin(mSerialBaudRate);
                }
            }

        } else {

            if (mReadBuffer[0] == (byte) 0xFF && mReadBuffer[1] == (byte) 0x55
                    && mReadBuffer[2] == (byte) 0xF7) {
                System.arraycopy(mReadBuffer, 3, mReadBuffer, 0, mReadLen - 3);
                mReadLen -= 3;
            }

            if (mReadBuffer[0] == (byte) 0xFF && mReadBuffer[1] == (byte) 0x55) {

                int readBufLen = (int) (mReadBuffer[2] & 0xFF);
                int cmdLen = readBufLen + 4;

                if (mReadLen >= cmdLen) {

                    podCommand cmd = new podCommand(mReadBuffer, cmdLen);

                    if (mReadLen == cmdLen)
                        mReadLen = 0;
                    else {
                        System.arraycopy(mReadBuffer, cmdLen, mReadBuffer, 0, mReadLen - cmdLen);
                        mReadLen -= cmdLen;
                    }

                    return cmd;

                } else
                    notEnoughData = true;

            } else {

                if (mReadLen == 1) {
                    if (mReadBuffer[0] != (byte) 0xFF) {
                        mReadLen = 0;
                    }
                } else {
                    System.arraycopy(mReadBuffer, 1, mReadBuffer, 0, mReadLen - 1);
                    mReadLen -= 1;
                }
            }

        }
    }
    return null;
}