Example usage for android.nfc Tag getId

List of usage examples for android.nfc Tag getId

Introduction

In this page you can find the example usage for android.nfc Tag getId.

Prototype

public byte[] getId() 

Source Link

Document

Get the Tag Identifier (if it has one).

Usage

From source file:de.syss.MifareClassicTool.Common.java

/**
 * Set the new active Tag (and update {@link #mUID}).
 * @param tag The new Tag./*ww w. ja v a  2 s .c  o  m*/
 * @see #mTag
 * @see #mUID
 */
public static void setTag(Tag tag) {
    mTag = tag;
    mUID = tag.getId();
}

From source file:se.anyro.nfc_reader.TagViewer.java

private String dumpTagData(Parcelable p) {
    StringBuilder sb = new StringBuilder();
    Tag tag = (Tag) p;
    byte[] id = tag.getId();
    sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
    sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
    sb.append("ID (reversed): ").append(getReversed(id)).append("\n");

    String prefix = "android.nfc.tech.";
    sb.append("Technologies: ");
    for (String tech : tag.getTechList()) {
        sb.append(tech.substring(prefix.length()));
        sb.append(", ");
    }/*from ww  w  .  j  av  a  2  s.  c o  m*/
    sb.delete(sb.length() - 2, sb.length());
    for (String tech : tag.getTechList()) {
        if (tech.equals(MifareClassic.class.getName())) {
            sb.append('\n');
            MifareClassic mifareTag = MifareClassic.get(tag);
            String type = "Unknown";
            switch (mifareTag.getType()) {
            case MifareClassic.TYPE_CLASSIC:
                type = "Classic";
                break;
            case MifareClassic.TYPE_PLUS:
                type = "Plus";
                break;
            case MifareClassic.TYPE_PRO:
                type = "Pro";
                break;
            }
            sb.append("Mifare Classic type: ");
            sb.append(type);
            sb.append('\n');

            sb.append("Mifare size: ");
            sb.append(mifareTag.getSize() + " bytes");
            sb.append('\n');

            sb.append("Mifare sectors: ");
            sb.append(mifareTag.getSectorCount());
            sb.append('\n');

            sb.append("Mifare blocks: ");
            sb.append(mifareTag.getBlockCount());
        }

        if (tech.equals(MifareUltralight.class.getName())) {
            sb.append('\n');
            MifareUltralight mifareUlTag = MifareUltralight.get(tag);
            String type = "Unknown";
            switch (mifareUlTag.getType()) {
            case MifareUltralight.TYPE_ULTRALIGHT:
                type = "Ultralight";
                break;
            case MifareUltralight.TYPE_ULTRALIGHT_C:
                type = "Ultralight C";
                break;
            }
            sb.append("Mifare Ultralight type: ");
            sb.append(type);
        }
    }

    return sb.toString();
}

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

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

    IsoDep isoDep = null;/*w  ww.ja  v a  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:com.nfc.gemkey.MainActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (DEBUG)/*from  www.  ja  va  2  s.c om*/
        Log.d(TAG, "onNewIntent");

    final String action = intent.getAction();
    if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
        if (DEBUG)
            Log.i(TAG, "Discovered tag with intent: " + action);
        Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String nfc_tag_id = bytesToHexString(myTag.getId()).toUpperCase();
        tagId.setText("Tag ID : " + nfc_tag_id);

        if (mCheckTagInfoThread != null && mCheckTagInfoThread.isAlive()) {
            mCheckTagInfoThread.terminate();
            mCheckTagInfoThread = null;
        }
        mCheckTagInfoThread = new CheckTagInfoThread(nfc_tag_id);
        mCheckTagInfoThread.start();
    }
}

From source file:org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.NFCVideoBrowserActivity.java

/**
 * Returns text data for given parecelable 
 * /*  w w w.ja  v a 2s.c o m*/
 * @param p
 * @return
 */
private String dumpTagData(Parcelable p) {
    Log.d(CLASSNAME, "dumpTagData is called Parcelable" + p);

    StringBuilder sb = new StringBuilder();
    Tag tag = (Tag) p;
    byte[] id = tag.getId();
    sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
    sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");

    String prefix = "android.nfc.tech.";
    sb.append("Technologies: ");
    for (String tech : tag.getTechList()) {
        sb.append(tech.substring(prefix.length()));
        sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());
    for (String tech : tag.getTechList()) {
        if (tech.equals(MifareClassic.class.getName())) {
            sb.append('\n');
            MifareClassic mifareTag = MifareClassic.get(tag);
            String type = "Unknown";
            switch (mifareTag.getType()) {
            case MifareClassic.TYPE_CLASSIC:
                type = "Classic";
                break;
            case MifareClassic.TYPE_PLUS:
                type = "Plus";
                break;
            case MifareClassic.TYPE_PRO:
                type = "Pro";
                break;
            }
            sb.append("Mifare Classic type: ");
            sb.append(type);
            sb.append('\n');

            sb.append("Mifare size: ");
            sb.append(mifareTag.getSize() + " bytes");
            sb.append('\n');

            sb.append("Mifare sectors: ");
            sb.append(mifareTag.getSectorCount());
            sb.append('\n');

            sb.append("Mifare blocks: ");
            sb.append(mifareTag.getBlockCount());
        }

        if (tech.equals(MifareUltralight.class.getName())) {
            sb.append('\n');
            MifareUltralight mifareUlTag = MifareUltralight.get(tag);
            String type = "Unknown";
            switch (mifareUlTag.getType()) {
            case MifareUltralight.TYPE_ULTRALIGHT:
                type = "Ultralight";
                break;
            case MifareUltralight.TYPE_ULTRALIGHT_C:
                type = "Ultralight C";
                break;
            }
            sb.append("Mifare Ultralight type: ");
            sb.append(type);
        }
    }

    return sb.toString();
}

From source file:de.syss.MifareClassicTool.Common.java

/**
 * For Activities which want to treat new Intents as Intents with a new
 * Tag attached. If the given Intent has a Tag extra, it will be patched
 * by {@link MCReader#patchTag(Tag)} and  {@link #mTag} as well as
 * {@link #mUID} will be updated. A Toast message will be shown in the
 * Context of the calling Activity. This method will also check if the
 * device/tag supports Mifare Classic (see return values and
 * {@link #checkMifareClassicSupport(Tag, Context)}).
 * @param intent The Intent which should be checked for a new Tag.
 * @param context The Context in which the Toast will be shown.
 * @return/*from w  w  w  . ja  v a2 s .c  o m*/
 * <ul>
 * <li>0 - The device/tag supports Mifare Classic</li>
 * <li>-1 - Device does not support Mifare Classic.</li>
 * <li>-2 - Tag does not support Mifare Classic.</li>
 * <li>-3 - Error (tag or context is null).</li>
 * <li>-4 - Wrong Intent (action is not "ACTION_TECH_DISCOVERED").</li>
 * </ul>
 * @see #mTag
 * @see #mUID
 * @see #checkMifareClassicSupport(Tag, Context)
 */
public static int treatAsNewTag(Intent intent, Context context) {
    // Check if Intent has a NFC Tag.
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        tag = MCReader.patchTag(tag);
        setTag(tag);

        // Show Toast message with UID.
        String id = context.getResources().getString(R.string.info_new_tag_found) + " (UID: ";
        id += byte2HexString(tag.getId());
        id += ")";
        Toast.makeText(context, id, Toast.LENGTH_LONG).show();
        return checkMifareClassicSupport(tag, context);
    }
    return -4;
}

From source file:com.codebutler.farebot.activities.ReadingTagActivity.java

private void resolveIntent(Intent intent) {
    final TextView textView = (TextView) findViewById(R.id.textView);

    try {//w ww . j av  a  2 s .co  m
        Bundle extras = intent.getExtras();

        final Tag tag = (Tag) extras.getParcelable("android.nfc.extra.TAG");
        ;
        final String[] techs = tag.getTechList();

        new AsyncTask<Void, String, MifareCard>() {
            Exception mException;

            @Override
            protected MifareCard doInBackground(Void... params) {
                try {
                    if (ArrayUtils.contains(techs, "android.nfc.tech.NfcB"))
                        return CEPASCard.dumpTag(tag.getId(), tag);
                    else if (ArrayUtils.contains(techs, "android.nfc.tech.IsoDep"))
                        return DesfireCard.dumpTag(tag.getId(), tag);
                    else
                        throw new UnsupportedTagException(techs, Utils.getHexString(tag.getId()));
                } catch (Exception ex) {
                    mException = ex;
                    return null;
                }
            }

            @Override
            protected void onPostExecute(MifareCard card) {
                if (mException != null) {
                    if (mException instanceof UnsupportedTagException) {
                        UnsupportedTagException ex = (UnsupportedTagException) mException;
                        new AlertDialog.Builder(ReadingTagActivity.this).setTitle("Unsupported Tag")
                                .setMessage(ex.getMessage()).setCancelable(false)
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        finish();
                                    }
                                }).show();
                    } else {
                        Utils.showErrorAndFinish(ReadingTagActivity.this, mException);
                    }
                    return;
                }

                try {
                    String cardXml = Utils.xmlNodeToString(card.toXML().getOwnerDocument());

                    ContentValues values = new ContentValues();
                    values.put(CardsTableColumns.TYPE, card.getCardType().toInteger());
                    values.put(CardsTableColumns.TAG_SERIAL, Utils.getHexString(card.getTagId()));
                    values.put(CardsTableColumns.DATA, cardXml);
                    values.put(CardsTableColumns.SCANNED_AT, card.getScannedAt().getTime());

                    Uri uri = getContentResolver().insert(CardProvider.CONTENT_URI_CARD, values);
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    finish();
                } catch (Exception ex) {
                    Utils.showErrorAndFinish(ReadingTagActivity.this, ex);
                }
            }

            @Override
            protected void onProgressUpdate(String... values) {
                textView.setText(values[0]);
            }

        }.execute();

    } catch (Exception ex) {
        Utils.showErrorAndFinish(this, ex);
    }
}

From source file:org.kegbot.app.HomeActivity.java

@Override
protected void onNewIntent(Intent intent) {
    Log.d(LOG_TAG, "onNewIntent: Got intent: " + intent);

    if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] id = tag.getId();
        if (id != null && id.length > 0) {
            String tagId = HexDump.toHexString(id).toLowerCase(Locale.US);
            Log.d(LOG_TAG, "Read NFC tag with id: " + tagId);
            // TODO: use tag technology as part of id?
            AuthenticatingActivity.startAndAuthenticate(this, "nfc", tagId);
        }/*  w  w w.j a  va  2 s  .  c om*/
    }
}

From source file:org.protocoderrunner.apprunner.AppRunnerActivity.java

@Override
public void onNewIntent(Intent intent) {
    MLog.d(TAG, "New intent " + intent);

    if (intent.getAction() != null) {
        MLog.d(TAG, "Discovered tag with intent: " + intent);
        // mText.setText("Discovered tag " + ++mCount + " with intent: " +
        // intent);

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String nfcID = StrUtils.bytetostring(tag.getId());

        // if there is mContext message waiting to be written
        if (PNFC.nfcMsg != null) {
            MLog.d(TAG, "->" + PNFC.nfcMsg);
            PNFC.writeTag(this, tag, PNFC.nfcMsg);
            onNFCWrittenListener.onNewTag();
            onNFCWrittenListener = null;
            PNFC.nfcMsg = null;// ww  w.  j  a  va  2s  .co  m

            // read the nfc tag info
        } else {

            // get NDEF tag details
            Ndef ndefTag = Ndef.get(tag);
            if (ndefTag == null) {
                return;
            }

            int size = ndefTag.getMaxSize(); // tag size
            boolean writable = ndefTag.isWritable(); // is tag writable?
            String type = ndefTag.getType(); // tag type

            String nfcMessage = "";

            // get NDEF message details
            NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
            if (ndefMesg != null) {
                NdefRecord[] ndefRecords = ndefMesg.getRecords();
                int len = ndefRecords.length;
                String[] recTypes = new String[len]; // will contain the
                // NDEF record types
                String[] recPayloads = new String[len]; // will contain the
                // NDEF record types
                for (int i = 0; i < len; i++) {
                    recTypes[i] = new String(ndefRecords[i].getType());
                    recPayloads[i] = new String(ndefRecords[i].getPayload());
                    MLog.d(TAG, "qq " + i + " " + recTypes[i] + " " + recPayloads[i]);

                }
                nfcMessage = recPayloads[0];

            }

            onNFCListener.onNewTag(nfcID, nfcMessage);
        }

    }

}