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.nps.micro.UsbService.java

@Override
public void onCreate() {
    Log.d(TAG, "Creating service...");
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    executorService = Executors.newSingleThreadExecutor();
    statusThread = new StatusThread(this);
    showNotification();//from   w  w  w  .  j a v a  2 s  . c o  m
    isRunning = true;
}

From source file:nl.bennyjacobs.aapbridge.aap.UsbConnection.java

/**
 * Connect to the first usb accessory./*from   www  . j av a2 s  .  c o m*/
 * 
 * @param context
 * @return A connection to the first usb accessory or null in case of failure.
 * @throws IOException 
 */
public static UsbConnection easyConnect(Context context) throws IOException {
    UsbManager mUSBManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    UsbAccessory[] accessories = mUSBManager.getAccessoryList();
    UsbAccessory accessory = (accessories == null ? null : accessories[0]);
    if (accessory != null) {
        if (mUSBManager.hasPermission(accessory)) {
            UsbConnection connection = new UsbConnection(context, mUSBManager, accessory);
            Log.v(TAG, "Connected to USB accessory");
            return connection;
        }
        throw new IOException("No permission to operate on accessory");
    }
    throw new IOException("No USB accessory found");
}

From source file:com.numato.usbgenie.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Listen to the SwipeTorefresh events
    mDevicesSwipeRefreshLayout.setOnRefreshListener(this);

    mDevicesManager = DevicesManager.getInstance();

    mDeviceListView.setOnItemClickListener(new OnItemClickListener() {
        @Override/* w  ww  .j ava  2s  . c o m*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // Get the USB device
            NumatoUSBDevice numatoUSBDevice = mDevicesManager.getDevices().get(position);

            // request USB permission for the device
            UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
                    new Intent(ACTION_USB_PERMISSION).putExtra(AppConstant.EXTRA_DEVICE_INDEX, position), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            registerReceiver(mUsbReceiver, filter);
            manager.requestPermission(numatoUSBDevice.getDevice(), mPermissionIntent);

        }
    });

    enumerateDevices();

    /*
     * Create a new ArrayAdapter and initialize the list with it.
     */
    mDeviceListArrayAdapter = new DeviceListArrayAdapter(this, new ArrayList<NumatoUSBDevice>());
    mDeviceListView.setAdapter(mDeviceListArrayAdapter);

    listDevices();
}

From source file:info.martinmarinov.dvbservice.DeviceChooserActivity.java

private void handleException(DvbException e) {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    Collection<UsbDevice> availableDevices = manager.getDeviceList().values();
    int[] productIds = new int[availableDevices.size()];
    int[] vendorIds = new int[availableDevices.size()];

    int id = 0;/*  w  ww. j av  a 2 s.  c  o  m*/
    for (UsbDevice usbDevice : availableDevices) {
        productIds[id] = usbDevice.getProductId();
        vendorIds[id] = usbDevice.getVendorId();
        id++;
    }

    response.putExtra(CONTRACT_ERROR_CODE, e.getErrorCode().name());
    response.putExtra(CONTRACT_RAW_TRACE, StackTraceSerializer.serialize(e));
    response.putExtra(CONTRACT_USB_PRODUCT_IDS, productIds);
    response.putExtra(CONTRACT_USB_VENDOR_IDS, vendorIds);

    finishWith(RESULT_ERROR);
}

From source file:com.wordpress.ebc81.rtl_ais_android.tools.DialogManager.java

@SuppressLint("NewApi")
private Dialog genUSBDeviceDialog() {

    try {/*from w w w  .  ja v  a 2 s  .c  om*/
        if (!(getActivity() instanceof DeviceOpenActivity))
            return null;
        final DeviceOpenActivity sdrviewer = (DeviceOpenActivity) getActivity();

        final UsbManager manager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
        final HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        if (deviceList.isEmpty()) {
            sdrviewer.finishWithError(err_info.no_devices_found);
            return null;
        }
        final String[] options = new String[deviceList.size()];
        int i = 0;
        for (final String s : deviceList.keySet())
            options[i++] = s;

        return new AlertDialog.Builder(getActivity()).setItems(options, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String selected = options[which];

                final UsbDevice selected_device = deviceList.get(selected);

                sdrviewer.openDevice(selected_device);
            }
        }).setOnCancelListener(new AlertDialog.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                sdrviewer.finishWithError(err_info.no_devices_found);
            }
        }).setTitle(R.string.choose_device).create();
    } catch (Throwable t) {
        t.printStackTrace();
        return null;
    }
}

From source file:marto.rtl_tcp_andro.DeviceOpenActivity.java

/**
 * Opens a certain USB device and prepares an argument to be passed to libusb
 * @param device//from ww w  .  ja v  a2  s  . c  om
 */
@SuppressLint("NewApi")
public void openDevice(final UsbDevice device) {
    final UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    if (device != null && !manager.hasPermission(device)) {
        android.util.Log.d("rtl_tcp_andro", "No permissions for device, requesting!");
        manager.requestPermission(device, permissionIntent);
        return;
    }

    if (device == null || !manager.hasPermission(device))
        finishWithError(err_info.permission_denied);

    final UsbDeviceConnection connection = manager.openDevice(device);

    if (connection == null)
        finishWithError(err_info.unknown_error);

    startBinary(arguments, connection.getFileDescriptor(), properDeviceName(device.getDeviceName()));
}

From source file:com.mahali.gpslogger.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    firstInstance = this;

    setContentView(R.layout.activity_main);

    // TODO: pull a GPS recvr config file from dropbox

    mTimer.start();//w  ww .ja  v  a2s.c  om

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

    // ------------------------------------------------
    //Setup for DropBox connection

    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);

    //apparently the below is deprecated, but I got it directly from the tutorial at https://www.dropbox.com/developers/core/start/android
    AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);

    // See if we already have information about a dropbox connection stored in the shared preferences file

    // returns the preferences file for "this" (i.e. MainActivity object). See http://developer.android.com/training/basics/data-storage/shared-preferences.html
    // SharedPreferences is a simple way to store basic key-value pairs. In this case we're using it to store dropbox configuration info
    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);

    // get value of DB OAuth2AccessToken from shared preferences file. If it's not present, will take value "not_authenticated"
    String OAuth2AccessToken = sharedPref.getString("OAuth2AccessToken", "not_authenticated");

    Log.i(TAG, "OAuth2AccessToken at startup: " + OAuth2AccessToken);

    // if we do already have info about a DB session stored, set that up
    if (!OAuth2AccessToken.equals("not_authenticated")) {

        Log.i(TAG, "authenticated, at startup: ");
        //sets the OAuth2AccessToken, causing the mDBApi AndroidAuthSession object to be linked (and thus useable for dropbox transactions)
        mDBApi.getSession().setOAuth2AccessToken(OAuth2AccessToken);
        assert mDBApi.getSession().isLinked();
    }

    // ------------------------------------------------

    // TODO: make sure external storage is mounted/available see info here:
    // http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage
    dirFile = new File(Environment.getExternalStorageDirectory(), mahali_directory);
    if (!dirFile.mkdirs()) {
        Log.i(TAG, "Directory not created - it already exists!");
    }

    Log.i(TAG, "Directory loaded: " + dirFile.exists());
    final ListView lv = (ListView) findViewById(R.id.sessionListView);

    updateSessionListView();

    // this method handles the selection of sessions from the list (single quick tap on session)
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            Object o = lv.getItemAtPosition(position);
            GPSSession fullObject = (GPSSession) o;
            Log.i(TAG, "You have chosen: " + " " + fullObject.getFileName());

            // Try to upload the file to dropbox
            sendToDB(fullObject.getAbsolutePath());
        }
    });

    // For Dropbox upload notification. Can only get system service once onCreate has been called.
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}

From source file:com.dslr.dashboard.PtpService.java

@Override
public void onCreate() {
    Log.d(TAG, "onCreate");
    super.onCreate();

    mGpsHelper = new GpsLocationHelper(this);

    IntentFilter usbDetachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mUsbDeviceDetached, usbDetachedFilter);

    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbPermissionReceiver, filter);

    // get the shared preferences
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // create the ptpdevice
    mPtpDevice = new PtpDevice(this);

    try {/*from ww w  . j a va 2  s  .  c o  m*/
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    } catch (Exception e) {
        Log.d(TAG, "UsbManager not available: " + e.getMessage());
    }

}

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

@Override
public void onCreate() {
    super.onCreate();
    Log.v(TAG, "onCreate()");

    mExit = false;/*from ww w  .j  a  v  a2 s  . com*/

    mBinder = new FadecandyServiceBinder(this);

    prefs = this.getSharedPreferences(Constants.PREFERENCE_PREFS, Context.MODE_PRIVATE);
    String configStr = prefs.getString(Constants.PREFERENCE_CONFIG, getDefaultConfig().toJsonString());
    int serviceType = prefs.getInt(Constants.PREFERENCE_SERVICE_TYPE,
            ServiceType.getState(Constants.DEFAULT_SERVICE_TYPE));
    mServerPort = prefs.getInt(Constants.PREFERENCE_PORT, Constants.DEFAULT_SERVER_PORT);
    mServerAddress = prefs.getString(Constants.PREFERENCE_IP_ADDRESS, Constants.DEFAULT_SERVER_ADDRESS);

    mServiceType = ServiceType.getServiceType(serviceType);

    try {
        mConfig = new FadecandyConfig(new JSONObject(configStr));
    } catch (JSONException e) {
        mConfig = getDefaultConfig();
        e.printStackTrace();
    }

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

    initBroadcastReceiver();
}

From source file:com.ekumen.tangobot.application.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

    // Load raw resources
    for (Pair<Integer, String> ip : mResourcesToLoad) {
        mOpenedResources.add(new ParameterLoaderNode.Resource(
                getResources().openRawResource(ip.first.intValue()), ip.second));
    }//from w  ww  .  ja  v a 2 s  .c  om

    mSharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // UI
    initializeUI();

    // USB handling code
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mUsbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    mUsbAttachedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mLog.info("Received USB Intent");
            if (intent.getAction() == ACTION_USB_PERMISSION
                    && intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                onDeviceReady((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
            }
        }
    };
    mUsbDetachedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mLog.info("Received USB disconnection Intent");
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            onDeviceDetached(device);
        }
    };
}