Example usage for android.nfc.tech IsoDep get

List of usage examples for android.nfc.tech IsoDep get

Introduction

In this page you can find the example usage for android.nfc.tech IsoDep get.

Prototype

public static IsoDep get(Tag tag) 

Source Link

Document

Get an instance of IsoDep for the given tag.

Usage

From source file:org.esupportail.nfctagdroid.authentication.DesfireAuthProvider.java

public String desfireAuth(Tag tag) throws ExecutionException, InterruptedException {
    String response = "ERROR";

    IsoDep isoDep = null;//  ww  w .  j a  va  2  s. com
    String[] techList = tag.getTechList();
    for (String tech : techList) {
        if (tech.equals(IsoDep.class.getName())) {
            isoDep = IsoDep.get(tag);
            log.info("Detected Desfire tag with id : " + HexaUtils.swapPairs(tag.getId()));
        }
    }
    if (isoDep == null) {
        throw new NfcTagDroidException("Did not detect a Desfire tag ");
    }

    try {
        String[] command = new String[2];
        String result = "";
        command[1] = "1";
        isoDep.connect();

        while (!command[1].equals("OK") && !command[1].equals("ERROR")) {

            DesfireHttpRequestAsync desfireHttpRequestAsync = new DesfireHttpRequestAsync();
            response = desfireHttpRequestAsync.execute(new String[] { command[1] + "/?result=" + result })
                    .get(time, TimeUnit.MILLISECONDS);
            try {
                JSONArray jsonArr = new JSONArray(response);
                command[0] = jsonArr.getString(0);
                command[1] = jsonArr.getString(1);

                if (!command[1].equals("OK") && !command[1].equals("ERROR")) {
                    byte[] byteResult = isoDep.transceive(HexaUtils.hexStringToByteArray(command[0]));
                    result = HexaUtils.byteArrayToHexString(byteResult);
                }
                log.debug("command step: " + command[1]);
                log.debug("command to send: " + command[0]);
                log.debug("result : " + result);
            } catch (Exception e) {
                throw new NfcTagDroidException(e);
            }
        }
        response = command[0];

    } catch (TimeoutException e) {
        log.warn("Time out");
        throw new NfcTagDroidException("Time out Desfire", e);
    } catch (TagLostException e) {
        throw new NfcTagDroidPleaseRetryTagException("TagLostException - authentication aborted", e);
    } catch (NfcTagDroidException e) {
        throw new NfcTagDroidInvalidTagException("nfctagdroidInvalidTagException - tag not valid", e);
    } catch (IOException e) {
        throw new NfcTagDroidInvalidTagException("IOException - authentication aborted", e);
    } catch (ExecutionException e) {
        throw new NfcTagDroidPleaseRetryTagException("ExecutionException - authentication aborted", e);
    } catch (InterruptedException e) {
        throw new NfcTagDroidPleaseRetryTagException("InterruptedException - authentication aborted", e);
    } finally {
        try {
            isoDep.close();
        } catch (IOException e) {
            throw new NfcTagDroidException(e);
        }
    }

    return response;
}

From source file:de.lazyheroproductions.campuscardreader.CardReaderIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (BuildConfig.DEBUG) {
        Log.i(this.getClass().getName(), "CardReaderService started");
    }/*from w ww.java2s. c o  m*/

    // get an instance of the nfc tag to communicate
    IsoDep isodep = IsoDep.get((Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
    try {
        // connect to the nfc tag
        isodep.connect();
        // select application which contains the credit and last transaction
        resultOk = isodep.transceive(selectAid);
        if (resultOk[0] == 0) {
            // get the credit
            creditBytes = isodep.transceive(creditPayload);
            // get the last transaction
            lastTransactionBytes = isodep.transceive(transactionPayload);
        } else {
            if (BuildConfig.DEBUG) {
                Log.w(this.getClass().getName(), "Wrong result: " + arrayToString(resultOk));
            }
        }
        isodep.close();
    } catch (IOException e) {
        if (BuildConfig.DEBUG) {
            Log.e(this.getClass().getName(), e.getMessage());
        }
        unknownErrorBool = true;
    } catch (NullPointerException e) {
        if (BuildConfig.DEBUG) {
            Log.e(this.getClass().getName(), e.getMessage());
        }
        unknownCampusCardErrorBool = true;
    }

    // send the gathered data back to the activity
    sendBroadcast();
}

From source file:com.example.marcieltorres.nfcproject_serverapp.cardreader.LoyaltyCardReader.java

/**
 * Callback when a new tag is discovered by the system.
 *
 * <p>Communication with the card should take place here.
 *
 * @param tag Discovered tag/*from w w w .  jav a  2s.  com*/
 */
@Override
public void onTagDiscovered(Tag tag) {
    //Log.i(TAG, "New tag discovered");
    // Android's Host-based Card Emulation (HCE) feature implements the ISO-DEP (ISO 14443-4)
    // protocol.
    //
    // In order to communicate with a device using HCE, the discovered tag should be processed
    // using the IsoDep class.
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep != null) {
        try {
            // Connect to the remote NFC device
            isoDep.connect();
            // Build SELECT AID command for our loyalty card service.
            // This command tells the remote device which service we wish to communicate with.
            //Log.i(TAG, "Requesting remote AID: " + SAMPLE_LOYALTY_CARD_AID);
            byte[] command = BuildSelectApdu(SAMPLE_LOYALTY_CARD_AID);
            // Send command to remote device
            //Log.i(TAG, "Sending: " + ByteArrayToHexString(command));
            byte[] result = isoDep.transceive(command);
            // If AID is successfully selected, 0x9000 is returned as the status word (last 2
            // bytes of the result) by convention. Everything before the status word is
            // optional payload, which is used here to hold the account number.
            int resultLength = result.length;
            byte[] statusWord = { result[resultLength - 2], result[resultLength - 1] };
            byte[] payload = Arrays.copyOf(result, resultLength - 2);
            if (Arrays.equals(SELECT_OK_SW, statusWord)) {
                // The remote NFC device will immediately respond with its stored account number
                String accountNumber = new String(payload, "UTF-8");
                //Log.i(TAG, "Received: " + accountNumber);
                // Inform CardReaderFragment of received account number
                mAccountCallback.get().onAccountReceived(accountNumber);
                mAccountCallback.get().onAccountReceived(accountNumber);

            }
        } catch (IOException e) {
            //Log.e(TAG, "Error communicating with card: " + e.toString());
        }
    }
}

From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java

/**
 * Sets the tag./*from  w  w  w .j a v a2  s. co  m*/
 *
 * @param tag the new tag
 */
private void setTag(Tag tag) throws IOException {
    _tag = tag;
    _NFC_ISO_DEP = IsoDep.get(_tag);

    byte[] atr = _NFC_ISO_DEP.getHistoricalBytes();
    try {
        _NFC_ISO_DEP.connect();
    } catch (Exception e) {
        Log.d(TAG, "Connection with the tag failed" + e);
        throw new IOException("Connection to tag failed");
    }

    // Set the time that the phone will wait for the Touchpoint to respond to a single command to 1/2 second.
    _NFC_ISO_DEP.setTimeout(500);
}

From source file:org.docrj.smartcard.reader.EmvReadActivity.java

@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();/*  ww w.j  a v a2  s. c  om*/
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        ReaderXcvr xcvr = new PaymentReaderXcvr(isoDep, "", this, TEST_MODE_EMV_READ);
        new Thread(xcvr).start();
    }
}

From source file:org.irmacard.androidmanagement.CredentialListActivity.java

public void processIntent(Intent intent) {
    tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    IsoDep isotag = IsoDep.get(tag);
    if (isotag != null) {
        // We are waiting for the card, notify dialog
        if (currentState == State.WAITING_FOR_CARD) {
            cardMissingDialog.dismiss();
            gotoState(State.TEST_CARD_PRESENCE);
        }//w  w w .  j  a  v  a2 s  .  co m
    }
}

From source file:com.tananaev.passportreader.MainActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getExtras().getParcelable(NfcAdapter.EXTRA_TAG);
        if (Arrays.asList(tag.getTechList()).contains("android.nfc.tech.IsoDep")) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            String passportNumber = preferences.getString(KEY_PASSPORT_NUMBER, null);
            String expirationDate = convertDate(preferences.getString(KEY_EXPIRATION_DATE, null));
            String birthDate = convertDate(preferences.getString(KEY_BIRTH_DATE, null));
            if (passportNumber != null && !passportNumber.isEmpty() && expirationDate != null
                    && !expirationDate.isEmpty() && birthDate != null && !birthDate.isEmpty()) {
                BACKeySpec bacKey = new BACKey(passportNumber, birthDate, expirationDate);
                new ReadTask(IsoDep.get(tag), bacKey).execute();
                mainLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.VISIBLE);
            } else {
                Snackbar.make(passportNumberView, R.string.error_input, Snackbar.LENGTH_SHORT).show();
            }/* ww w  .  j  a  va2  s.c  o m*/
        }
    }
}

From source file:com.golfwallet.main.MainActivity.java

/**   
 *  \brief//ww w . j  a  v a2  s  .  c  o  m
 *    Method called when the service detect a NFC card.
 *    \param tag Tag that the service has detected
 */
@Override
public void onTagDiscovered(Tag tag) {
    IsoDep isoDep = IsoDep.get(tag);
    IsoDepTransceiver transceiver = new IsoDepTransceiver(isoDep, this);
    Thread thread = new Thread(transceiver);
    thread.start();
}

From source file:org.docrj.smartcard.reader.BatchSelectActivity.java

@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();/* ww w . j  a v  a2s  .  c o m*/
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        // two separators between taps/discoveries
        addMessageSeparator();
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        List<SmartcardApp> memberApps = mGrpToMembersMap.get(mSelectedGrpPos);
        new Thread(new BatchReaderXcvr(isoDep, memberApps, this)).start();
    }
}

From source file:org.docrj.smartcard.reader.AppSelectActivity.java

@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();/* w  w  w  . j a  v a  2  s . c om*/
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        ReaderXcvr xcvr;
        String aid = mApps.get(mSelectedAppPos).getAid();

        if (mManual) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Animation shake = AnimationUtils.loadAnimation(AppSelectActivity.this, R.anim.shake);
                    mSelectButton.startAnimation(shake);
                }
            });
            // manual select mode; for multiple selects per tap/connect
            // does not select ppse for payment apps unless specifically configured
            xcvr = new ManualReaderXcvr(isoDep, aid, this);
        } else if (mApps.get(mSelectedAppPos).getType() == SmartcardApp.TYPE_PAYMENT) {
            // payment, ie. always selects ppse first
            xcvr = new PaymentReaderXcvr(isoDep, aid, this, TEST_MODE_APP_SELECT);
        } else {
            // other/non-payment; auto select on each tap/connect
            xcvr = new OtherReaderXcvr(isoDep, aid, this);
        }

        new Thread(xcvr).start();
    }
}