Example usage for android.hardware.usb UsbManager ACTION_USB_DEVICE_ATTACHED

List of usage examples for android.hardware.usb UsbManager ACTION_USB_DEVICE_ATTACHED

Introduction

In this page you can find the example usage for android.hardware.usb UsbManager ACTION_USB_DEVICE_ATTACHED.

Prototype

String ACTION_USB_DEVICE_ATTACHED

To view the source code for android.hardware.usb UsbManager ACTION_USB_DEVICE_ATTACHED.

Click Source Link

Document

Activity intent sent when user attaches a USB device.

Usage

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

/**
 * USB???/*from  w  w  w .  ja  v a 2s  .c o  m*/
 */
private void listenUsbDevice(CallbackContext callbackContext) {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    this.usbCallbackContext = callbackContext;
    if (this.mUsbReceiver == null) {
        this.mUsbReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String handlerName = null;
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    // plugin result of USB attached
                    handlerName = HANDLER_PREFIX + "." + "attached";
                }
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    // plugin result of USB detached
                    handlerName = HANDLER_PREFIX + "." + "detached";
                }
                try {
                    String json = "{\"handlerName\":" + handlerName + " }";
                    JSONObject parameter = new JSONObject(json);
                    PluginResult dataResult = new PluginResult(PluginResult.Status.OK, parameter);
                    dataResult.setKeepCallback(true);
                    usbCallbackContext.sendPluginResult(dataResult);
                } catch (JSONException e) {
                    Log.e(POCKETDUINO, "Exception: " + e.getMessage());
                    usbCallbackContext.error(e.toString());
                }
            }
        };
        webView.getContext().registerReceiver(this.mUsbReceiver, intentFilter);
    }
}

From source file:com.grupohqh.carservices.operator.ManipulateCarActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manipulate_car);

    if (getIntent().getExtras().containsKey("userId"))
        userId = getIntent().getExtras().getInt("userId");
    if (getIntent().getExtras().containsKey("carOwnerId"))
        carOwnerId = getIntent().getExtras().getInt("carOwnerId");

    CARBRAND_URL = getString(R.string.base_url) + getString(R.string.carbrands_url);
    CARLINE_URL = getString(R.string.base_url) + getString(R.string.carmodels_url);
    SAVECAR_URL = getString(R.string.base_url) + "savecar/";
    SAVEPHOTO_URL = getString(R.string.base_url) + "savephoto/";
    hasCamera = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

    etTagNumber = (EditText) findViewById(R.id.etTagNumber);
    etUsernameOwner = (EditText) findViewById(R.id.etUsernameOwner);
    etCarBrand = (EditText) findViewById(R.id.etCarBrand);
    etCarModel = (EditText) findViewById(R.id.etCarModel);
    etCarYear = (EditText) findViewById(R.id.etCarYear);
    etColor = (EditText) findViewById(R.id.etCarColor);
    etSerialNumber = (EditText) findViewById(R.id.etSerialNumber);
    etLicensePlate = (EditText) findViewById(R.id.etLicensePlate);
    etKM = (EditText) findViewById(R.id.etKm);
    imgCar = (ImageView) findViewById(R.id.imgCar);
    spCarBrand = (Spinner) findViewById(R.id.spCarBrand);
    spCarModel = (Spinner) findViewById(R.id.spCarModel);
    btnSaveCar = (Button) findViewById(R.id.btnSaveCar);
    btnTakePicture = (Button) findViewById(R.id.btnTakePicture);
    bar = (ProgressBar) findViewById(R.id.progressBar);
    viewUsername = findViewById(R.id.viewUsername);

    if (savedInstanceState != null) {
        bm = savedInstanceState.getParcelable("bm");
        if (bm != null)
            imgCar.setImageBitmap(bm);/*from   ww w  . java  2  s . com*/
    }

    bar.setVisibility(View.GONE);
    etCarBrand.setVisibility(View.GONE);
    etCarModel.setVisibility(View.GONE);
    viewUsername.setVisibility(carOwnerId == 0 ? View.VISIBLE : View.GONE);

    btnTakePicture.setEnabled(hasCamera);
    btnTakePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(ManipulateCarActivity.this)));
            startActivityForResult(intent, CAPTURE_IMAGE);
        }
    });

    btnSaveCar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate())
                new SaveCarAsyncTask().execute(SAVECAR_URL);
        }
    });

    spCarBrand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapBrands.get(brands.get(position)) == otherId) {
                etCarBrand.setVisibility(View.VISIBLE);
                etCarModel.setVisibility(View.VISIBLE);
                spCarModel.setVisibility(View.GONE);
                etCarBrand.requestFocus();
            } else {
                etCarBrand.setVisibility(View.GONE);
                etCarModel.setVisibility(View.GONE);
                spCarModel.setVisibility(View.VISIBLE);
                new LoadCarModelsAsyncTask().execute(CARLINE_URL + mapBrands.get(brands.get(position)) + "/");
                reload = true;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spCarModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapModels.get(models.get(position)) == otherId) {
                etCarModel.setVisibility(View.VISIBLE);
                etCarModel.requestFocus();
            } else {
                etCarModel.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    if (useMiniMe) {
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        usbCommunication = UsbCommunication.newInstance();

        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); // will intercept by system
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, filter);

        etEPC = (EditText) findViewById(R.id.etEPC);
        btnReadTAG = (Button) findViewById(R.id.btnReadTAG);
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        btnReadTAG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etEPC.setText("");
                if (txtStatus.getText().toString().equals("conectado")) {
                    readTag();
                } else {
                    Toast.makeText(getBaseContext(), "dispositivo " + txtStatus.getText(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
    }

    etKM.addTextChangedListener(new NumberTextWatcher(etKM));
}

From source file:jp.ksksue.app.terminal.AndroidUSBSerialMonitorLite.java

/** Called when the activity is first created. */
@Override//w  w w  .  j  a v a2 s. co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* FIXME : How to check that there is a title bar menu or not.
            // Should not set a Window.FEATURE_NO_TITLE on Honeycomb because a user cannot see menu button.
            if(isICSorHigher) {
    if(!getWindow().hasFeature(Window.FEATURE_ACTION_BAR)) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }
            }
    */
    setContentView(R.layout.main);

    mSvText = (ScrollView) findViewById(R.id.svText);
    mTvSerial = (TextView) findViewById(R.id.tvSerial);
    btWrite = (Button) findViewById(R.id.btWrite);
    btWrite.setEnabled(false);
    etWrite = (EditText) findViewById(R.id.etWrite);
    etWrite.setEnabled(false);
    etWrite.setHint("CR : \\r, LF : \\n, bin : \\u0000");

    if (SHOW_DEBUG) {
        Log.d(TAG, "New FTDriver");
    }

    // get service
    mSerial = new Physicaloid(this);

    if (SHOW_DEBUG) {
        Log.d(TAG, "New instance : " + mSerial);
    }
    // listen for new devices
    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    if (SHOW_DEBUG) {
        Log.d(TAG, "FTDriver beginning");
    }

    openUsbSerial();

    etWrite.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
                writeDataToSerial();
                return true;
            }
            return false;
        }
    });
    // ---------------------------------------------------------------------------------------
    // Write Button
    // ---------------------------------------------------------------------------------------
    if (!USE_WRITE_BUTTON_FOR_DEBUG) {
        btWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeDataToSerial();
            }
        });
    } else {
        // Write test button for debug
        btWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strWrite = "";
                for (int i = 0; i < 3000; ++i) {
                    strWrite = strWrite + " " + Integer.toString(i);
                }
                if (SHOW_DEBUG) {
                    Log.d(TAG, "FTDriver Write(" + strWrite.length() + ") : " + strWrite);
                }
                mSerial.write(strWrite.getBytes(), strWrite.length());
            }
        });
    } // end of if(SHOW_WRITE_TEST_BUTTON)

    btnLoad = (Button) findViewById(R.id.btnLoad);
    btnLoad.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            SimpleFileDialog simpleFileDialog = new SimpleFileDialog(AndroidUSBSerialMonitorLite.this,
                    "FileOpen", new SimpleFileDialog.SimpleFileDialogListener() {
                        @Override
                        public void onChosenDir(String chosenDir) {
                            File file = null;
                            FileInputStream fileInputStream = null;
                            byte[] data;

                            try {
                                file = new File(chosenDir);
                                if (file.isDirectory()) {
                                    throw new IOException("not file");
                                }

                                fileInputStream = new FileInputStream(file);
                                data = new byte[(int) file.length()];
                                fileInputStream.read(data);

                                String dataText = new String(data, "UTF-8");
                                parseJSON(dataText);

                            } catch (IOException e) {
                                Toast.makeText(AndroidUSBSerialMonitorLite.this, e.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            } finally {
                                if (fileInputStream != null) {
                                    try {
                                        fileInputStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    });
            simpleFileDialog.chooseFile_or_Dir();
        }
    });

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startIrBeaconPulse();
        }
    });

    btnStop = (Button) findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopIrBeaconPulse();
        }
    });

    btnPlay.setEnabled(false);
    btnStop.setEnabled(false);
}

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

private void onUsbDeviceAttached(Intent intent) {
    if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
        UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        onDeviceReady(usbDevice);//from  www.  j  av  a  2s .  c o  m
    }
}

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

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

    serviceIntent = new Intent(this, UsbFileHttpServerService.class);

    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.listview);

    listView.setOnItemClickListener(this);
    registerForContextMenu(listView);/*w w  w.  jav  a 2s  .  c om*/

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(usbReceiver, filter);
    discoverDevice();
}

From source file:com.igniva.filemanager.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    if (materialDialog != null && !materialDialog.isShowing()) {
        materialDialog.show();/* www  .j a  va2s  .  c  o m*/
        materialDialog = null;
    }
    IntentFilter newFilter = new IntentFilter();
    newFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    newFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    newFilter.addDataScheme(ContentResolver.SCHEME_FILE);
    registerReceiver(mainActivityHelper.mNotificationReceiver, newFilter);
    registerReceiver(receiver2, new IntentFilter("general_communications"));
    if (getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getName()
            .contains("TabFragment")) {

        floatingActionButton.setVisibility(View.VISIBLE);
        floatingActionButton.showMenuButton(false);
    } else {

        floatingActionButton.setVisibility(View.INVISIBLE);
        floatingActionButton.hideMenuButton(false);
    }

    // Registering intent filter for OTG
    IntentFilter otgFilter = new IntentFilter();
    otgFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    otgFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    if (materialDialog != null && !materialDialog.isShowing()) {
        materialDialog.show();// w ww .  ja va2 s . c o m
        materialDialog = null;
    }

    IntentFilter newFilter = new IntentFilter();
    newFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    newFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    newFilter.addDataScheme(ContentResolver.SCHEME_FILE);
    registerReceiver(mainActivityHelper.mNotificationReceiver, newFilter);
    registerReceiver(receiver2, new IntentFilter(TAG_INTENT_FILTER_GENERAL));
    if (getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getName()
            .contains("TabFragment")) {

        floatingActionButton.setVisibility(View.VISIBLE);
        floatingActionButton.showMenuButton(false);
    } else {

        floatingActionButton.setVisibility(View.INVISIBLE);
        floatingActionButton.hideMenuButton(false);
    }

    if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // Registering intent filter for OTG
        IntentFilter otgFilter = new IntentFilter();
        otgFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        otgFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mOtgReceiver, otgFilter);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // let's register encryption service to know when we've decrypted
        Intent encryptIntent = new Intent(this, EncryptService.class);
        bindService(encryptIntent, mEncryptServiceConnection, 0);

        if (!isEncryptOpen && encryptBaseFile != null) {
            // we've opened the file and are ready to delete it
            // don't move this to ondestroy as we'll be getting destroyed and starting
            // an async task just before it is not a good idea
            ArrayList<BaseFile> baseFiles = new ArrayList<>();
            baseFiles.add(encryptBaseFile);
            new DeleteTask(getContentResolver(), this).execute(baseFiles);
        }
    }
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

@Override
public void onNewIntent(Intent i) {
    intent = i;/*from   w w w.j  av  a 2 s  . c  o m*/
    path = i.getStringExtra("path");

    if (path != null) {
        if (new File(path).isDirectory()) {
            Fragment f = getDFragment();
            if ((f.getClass().getName().contains("TabFragment"))) {
                MainFragment m = ((MainFragment) getFragment().getTab());
                m.loadlist(path, false, OpenMode.FILE);
            } else
                goToMain(path);
        } else
            utils.openFile(new File(path), mainActivity);
    } else if (i.getStringArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS) != null) {
        ArrayList<BaseFile> failedOps = i.getParcelableArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS);
        if (failedOps != null) {
            mainActivityHelper.showFailedOperationDialog(failedOps, i.getBooleanExtra("move", false), this);
        }
    } else if (i.getCategories() != null && i.getCategories().contains(CLOUD_AUTHENTICATOR_GDRIVE)) {

        // we used an external authenticator instead of APIs. Probably for Google Drive
        CloudRail.setAuthenticationResponse(intent);

    } else if ((openProcesses = i.getBooleanExtra(KEY_INTENT_PROCESS_VIEWER, false))) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_frame, new ProcessViewer(), KEY_INTENT_PROCESS_VIEWER);
        //   transaction.addToBackStack(null);
        selectedStorage = SELECT_102;
        openProcesses = false;
        //title.setText(utils.getString(con, R.string.process_viewer));
        //Commit the transaction
        transaction.commitAllowingStateLoss();
        supportInvalidateOptionsMenu();
    } else if (intent.getAction() != null) {
        if (intent.getAction().equals(Intent.ACTION_GET_CONTENT)) {
            // file picker intent
            mReturnIntent = true;
            Toast.makeText(this, getString(R.string.pick_a_file), Toast.LENGTH_LONG).show();
        } else if (intent.getAction().equals(RingtoneManager.ACTION_RINGTONE_PICKER)) {
            // ringtone picker intent
            mReturnIntent = true;
            mRingtonePickerIntent = true;
            Toast.makeText(this, getString(R.string.pick_a_file), Toast.LENGTH_LONG).show();
        } else if (intent.getAction().equals(Intent.ACTION_VIEW)) {
            // zip viewer intent
            Uri uri = intent.getData();
            zippath = uri.toString();
            openZip(zippath);
        }

        if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
                if (sharedPref.getString(KEY_PREF_OTG, null) == null) {
                    sharedPref.edit().putString(KEY_PREF_OTG, VALUE_PREF_OTG_NULL).apply();
                    refreshDrawer();
                }
            } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                sharedPref.edit().putString(KEY_PREF_OTG, null).apply();
                refreshDrawer();
            }
        }
    }
}