Example usage for android.nfc NfcAdapter EXTRA_TAG

List of usage examples for android.nfc NfcAdapter EXTRA_TAG

Introduction

In this page you can find the example usage for android.nfc NfcAdapter EXTRA_TAG.

Prototype

String EXTRA_TAG

To view the source code for android.nfc NfcAdapter EXTRA_TAG.

Click Source Link

Document

Mandatory extra containing the Tag that was discovered for the #ACTION_NDEF_DISCOVERED , #ACTION_TECH_DISCOVERED , and #ACTION_TAG_DISCOVERED intents.

Usage

From source file:be.brunoparmentier.wifikeyshare.ui.activities.WifiNetworkActivity.java

private void handleIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    String action = intent.getAction();
    Log.d(TAG, "handleIntent: action=" + action);
    if (isInWriteMode) {
        /* Write tag */
        Log.d(TAG, "Writing tag");
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

            if (NfcUtils.writeTag(wifiNetwork, tag)) {
                Toast.makeText(this, R.string.nfc_tag_written, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, R.string.error_nfc_tag_write, Toast.LENGTH_LONG).show();
            }/* w  ww  .  ja  v  a 2s .c o  m*/
            disableTagWriteMode();
        }
    } else {
        /* Read tag */
        Log.d(TAG, "Reading tag");

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            if (NfcUtils.NFC_TOKEN_MIME_TYPE.equals(intent.getType())) {
                Intent configureNetworkIntent = new Intent(intent)
                        .setClass(this, ConfirmConnectToWifiNetworkActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(configureNetworkIntent);
            } else {
                Log.d(TAG, "Not a Wi-Fi configuration tag");
            }
        }
    }
}

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 ww  .  j  av 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.example.multi_ndef.Frag_Write.java

/**
 * Called when our blank tag is scanned executing the PendingIntent
 *///from   w w  w.j a  va2  s . c  o m
//@SuppressLint("InlinedApi")
@Override
public void onNewIntent(Intent intent) {
    try {

        if (mInWriteMode) {
            mInWriteMode = false;

            // write to newly scanned tag
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            ma.setCurrentTag(tagFromIntent);

            boolean cardCheck = false;

            cardCheck = varifyTag();

            if (cardCheck) {

                writeTag(tag);

            }

            else if (!cardCheck)

            {

                Toast toast = Toast.makeText(getApplicationContext(),
                        "Verification failed. Please use STMicroelectronics SR Tag to continue.",
                        Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
                toast.show();

            }
        }

    }

    catch (Exception e) {

    }

}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

@Override
protected void onNewIntent(Intent intent) {
    Log.i(nfcDebugTag, "Tag detected ");
    Toast.makeText(this, "Card detectat", Toast.LENGTH_SHORT).show();

    isCardEmpty = true;/*www . jav a 2 s .  com*/
    try {
        libInstance.filterIntent(intent, mCallback);
        //                FragmentPinDialog fragment = new FragmentPinDialog();
        //                fragment.show(getSupportFragmentManager(), "Mario popup");
        if (isDesfire == false) {

            if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
                Toast.makeText(this, "NfcIntent", Toast.LENGTH_SHORT).show();

                Log.i(nfcDebugTag, "Tag detectat");

                Parcelable[] parcelables = intent.getParcelableArrayExtra(nfcAdapter.EXTRA_NDEF_MESSAGES);
                if (parcelables != null && parcelables.length > 0) {
                    readTextFromTag((NdefMessage) parcelables[0]);
                } else {
                    Toast.makeText(this, "No NDEF Message Found", Toast.LENGTH_SHORT).show();
                }
            } else {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String mesaj = "ce mai faci";
                NdefMessage ndefMessage = createNdefMessage(mesaj);
                writeNdefMessage(tag, ndefMessage);
            }
        }

        if (isCardEmpty) {
            FragmentEmptyState Fragment = new FragmentEmptyState();
            ChangeFragment(Fragment);
            //            ChangeFragment(chooseOptions);
            //                FragmentPinDialog fragment = new FragmentPinDialog();
            //                fragment.show(getSupportFragmentManager(), "Mario popup");

        } else {
            Log.i(nfcDebugTag, "A ajuns pe else pana la fragment");

            int lengthStack = getSupportFragmentManager().getFragments().size();
            Fragment lastFragment = getSupportFragmentManager().getFragments().get(lengthStack - 1);
            boolean isDialogFragment = FragmentPinDialog.class.isInstance(lastFragment);
            if (!isDialogFragment) {
                FragmentPinDialog fragment = new FragmentPinDialog();
                fragment.show(getSupportFragmentManager(), "Mario popup");
            }
        }
    } catch (CloneDetectedException e) {
        Toast.makeText(this, "Error_with_warning", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.i(nfcDebugTag, "Exceptia este" + e.getMessage());
    } finally {
        isDesfire = false;
    }
    Log.i(nfcDebugTag, "Nfc intent a ajuns la sfarsit");
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

@Override
public void onNewIntent(Intent intent) {
    setIntent(intent);/*from   w w  w .  j a v  a2 s .  co m*/
    Log.d("TAG_VIEWER", "on new intent actually fired ");
    if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

        resolveIntent(intent);
    }

    // Tag writing mode
    if (writeContent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Log.d("TAG_VIEWER", "in Oncreate Before writing");

        // new AlertDialog.Builder(TagViewer.this)
        // .setTitle("Touch tag to write")
        // .setOnCancelListener(
        // new DialogInterface.OnCancelListener() {
        // public void onCancel(DialogInterface dialog) {
        // disableTagWriteMode();
        //
        // }
        // }).create().show();

        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        try {
            WriteToTag.write(detectedTag, writeContent);
            Context context = getApplicationContext();
            CharSequence text = "Tag sucessfully written!!";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();

            Log.d("TAG_VIEWER", "Before calling dialog.cancel");
            dialog.dismiss();
            finish();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("TAG_VIEWER", "in on create, writing to tag");
    }
    //
    // // Tag writing mode
    // if (mWriteMode
    // &&
    // NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
    // {
    // Tag detectedTag =
    // intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    // try {
    // WriteToTag.write(detectedTag);
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } catch (FormatException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // Log.d("TAG_VIEWER", "in on new intent, writing to tag");
    // }
}

From source file:com.sigilance.CardEdit.MainActivity.java

protected void handleNdefDiscoveredIntent(Intent intent) throws IOException {
    Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    isoDep = IsoDep.get(detectedTag);//  w  ww. j a v  a2s  .  c o  m
    isoDep.setTimeout(100000); // timeout is set to 100 seconds to avoid cancellation during calculation
    isoDep.connect();

    byte[] opening = { 0x00, (byte) 0xA4, 0x04, 0x00, 0x06, (byte) 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01, 0x00 };
    byte[] response = nfcCommunicate(opening);
    if (!Arrays.equals(response, SW_ACCEPTED)) {
        throw new IOException("Initialization failed!");
    }

    byte[] aid = nfcGetData(DO_AID);

    // If user is touching card for the first time, cache the AID.
    if (mCurrentAid == null) {
        mCurrentAid = aid;
    }

    // Confirm that they're still tapping the same card.
    if (!Arrays.equals(aid, mCurrentAid)) {
        throw new IOException("Serial numbers did not match; did you tap a different card?");
    }

    // With safety checks out of the way, perform pending operations.
    if (mPendingOperations.size() > 0) {
        String newAdminPIN = null;

        for (PendingOperation operation : mPendingOperations) {
            if (operation instanceof PendingVerifyPinOperation) {
                PendingVerifyPinOperation op = (PendingVerifyPinOperation) operation;
                nfcVerifyPIN(op.getSlot(), op.getPin());
                // NOTE: We do not remove the verify operation, because if the user wants to
                // edit another DO, we'll need to transmit it again.
            } else if (operation instanceof PendingPutDataOperation) {
                PendingPutDataOperation op = (PendingPutDataOperation) operation;
                nfcPutData(op.getSlot(), op.getData());
                mPendingOperations.remove(op);
            } else if (operation instanceof PendingChangePinOperation) {
                PendingChangePinOperation op = (PendingChangePinOperation) operation;
                nfcModifyPIN(op.getSlot(), op.getOldPin(), op.getNewPin());
                if (op.getSlot() == 0x83)
                    newAdminPIN = op.getNewPin();
                mPendingOperations.remove(op);
                Toast.makeText(this, "PIN was changed.", Toast.LENGTH_LONG).show();
            }
        }

        // If we changed the Admin PIN, we need the VERIFY command to reflect the new PIN.
        if (newAdminPIN != null)
            for (PendingOperation operation : mPendingOperations)
                if (operation instanceof PendingVerifyPinOperation) {
                    PendingVerifyPinOperation op = (PendingVerifyPinOperation) operation;
                    if (op.getSlot() == 0x83)
                        op.setPin(newAdminPIN);
                }
    }

    // Finally, get all the data and show the UI.
    byte[] cardholderData = nfcGetData(DO_CARDHOLDER_DATA);
    Iso7816TLV chTlv = Iso7816TLV.readSingle(cardholderData, true);
    mCardholderName = new String(Iso7816TLV.findRecursive(chTlv, TAG_NAME).mV);
    mCardholderSex = new String(Iso7816TLV.findRecursive(chTlv, TAG_SEX).mV);
    mCardholderLanguage = new String(Iso7816TLV.findRecursive(chTlv, TAG_LANGUAGE).mV);

    mUrl = new String(nfcGetData(DO_URL));
    mLoginData = nfcGetData(DO_LOGIN_DATA);

    byte[] appData = nfcGetData(DO_APPLICATION_DATA);
    Iso7816TLV appTlv = Iso7816TLV.readSingle(appData, true);
    byte[] fingerprints = Iso7816TLV.findRecursive(appTlv, TAG_FINGERPRINTS).mV;
    mSigKeyFingerprint = hexString(Arrays.copyOfRange(fingerprints, 0, 20));
    mEncKeyFingerprint = hexString(Arrays.copyOfRange(fingerprints, 20, 40));
    mAuthKeyFingerprint = hexString(Arrays.copyOfRange(fingerprints, 40, 60));
    byte[] timestamps = Iso7816TLV.findRecursive(appTlv, TAG_TIMESTAMPS).mV;
    mSigKeyTimestamp = unsignedFromByteArray(Arrays.copyOfRange(timestamps, 0, 4));
    mEncKeyTimestamp = unsignedFromByteArray(Arrays.copyOfRange(timestamps, 4, 8));
    mAuthKeyTimestamp = unsignedFromByteArray(Arrays.copyOfRange(timestamps, 8, 12));

    mPwStatusBytes = nfcGetData(DO_PW_STATUS_BYTES);

    byte[] secData = nfcGetData(DO_SECURITY_TEMPLATE);
    Iso7816TLV secTlv = Iso7816TLV.readSingle(secData, true);
    byte[] sigCount = { 0, 0, 0, 0 };
    byte[] sigCountFromCard = Iso7816TLV.findRecursive(secTlv, TAG_SIG_COUNT).mV;
    System.arraycopy(sigCountFromCard, 0, sigCount, 1, 3);
    mSignatureCount = ByteBuffer.wrap(sigCount).getInt();

    refreshUi();
}

From source file:com.moonpi.tapunlock.MainActivity.java

@Override
protected void onNewIntent(Intent intent) {
    String action = intent.getAction();

    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        // Get tag ID and turn into String
        byte[] tagIDbytes = tag.getId();
        tagID = bytesToHex(tagIDbytes);//from ww w  .  j  ava2 s. co  m

        if (!tagID.equals("")) {
            // Dismiss the 'Scan NFC Tag' dialog and show the 'Set tag name' dialog
            dismissDialog(DIALOG_READ);

            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

            MainActivity.this.showDialog(DIALOG_SET_TAGNAME);
        }
    }
}