Example usage for android.nfc.tech Ndef getCachedNdefMessage

List of usage examples for android.nfc.tech Ndef getCachedNdefMessage

Introduction

In this page you can find the example usage for android.nfc.tech Ndef getCachedNdefMessage.

Prototype

public NdefMessage getCachedNdefMessage() 

Source Link

Document

Get the NdefMessage that was read from the tag at discovery time.

Usage

From source file:Main.java

static JSONObject ndefToJSON(Ndef ndef) {
    JSONObject json = new JSONObject();

    if (ndef != null) {
        try {/*from ww  w .j a va2 s  .co m*/

            Tag tag = ndef.getTag();
            // tag is going to be null for NDEF_FORMATABLE until NfcUtil.parseMessage is refactored
            if (tag != null) {
                json.put("id", byteArrayToJSON(tag.getId()));
                json.put("techTypes", new JSONArray(Arrays.asList(tag.getTechList())));
            }

            json.put("type", translateType(ndef.getType()));
            json.put("maxSize", ndef.getMaxSize());
            json.put("isWritable", ndef.isWritable());
            json.put("ndefMessage", messageToJSON(ndef.getCachedNdefMessage()));
            // Workaround for bug in ICS (Android 4.0 and 4.0.1) where
            // mTag.getTagService(); of the Ndef object sometimes returns null
            // see http://issues.mroland.at/index.php?do=details&task_id=47
            try {
                json.put("canMakeReadOnly", ndef.canMakeReadOnly());
            } catch (NullPointerException e) {
                json.put("canMakeReadOnly", JSONObject.NULL);
            }
        } catch (JSONException e) {
            Log.e(TAG, "Failed to convert ndef into json: " + ndef.toString(), e);
        }
    }
    return json;
}

From source file:com.macleod2486.androidswissknife.components.NFCCallback.java

@Override
public void onTagDiscovered(Tag tag) {

    EditText tagResult = activity.findViewById(R.id.textEntry);

    try {//from w  w  w .j  ava  2  s. c om
        Ndef ndef = Ndef.get(tag);

        if (ndef != null) {
            NdefMessage ndefMesg = ndef.getCachedNdefMessage();
            if (ndefMesg != null) {
                nfcData = "Message: " + ndefMesg.toString();
                Log.i("NFCCallback", nfcData);
            }
        } else {
            nfcData = "Attempting to format";
            Log.i("NFCCallback", "Attempting to format");

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tagResult.setText("");
                    tagResult.append("Attempting to format");
                }
            });

            NdefFormatable format = NdefFormatable.get(tag);

            if (format != null) {
                format.connect();

                if (format.isConnected()) {
                    try {
                        format.format(null);
                        nfcData = "Formatted";
                        Log.i("NFCCallback", "Formatted");
                    } catch (Exception e) {
                        nfcData = "Error occurred in formatting";
                        e.printStackTrace();
                    }

                    format.close();
                }
            } else {
                Log.i("NFCCallback", "Tag not found");
                nfcData = "Tag not found or formatted";
            }
        }

        if (tagResult != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tagResult.setText("");
                    Log.i("NFCCallback", "Cleared");
                    tagResult.append(nfcData);
                }
            });
        }
    } catch (Exception e) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tagResult.setText("");
                tagResult.append("Error reading tag");
            }
        });

        e.printStackTrace();
    }
}

From source file:com.google.samples.apps.iosched.ui.NfcBadgeActivity.java

private void readTag(Tag t) {
    byte[] id = t.getId();

    // get NDEF tag details
    Ndef ndefTag = Ndef.get(t);

    // get NDEF message details
    NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
    if (ndefMesg == null) {
        return;/*  w  w  w .  j a v a2s  .com*/
    }
    NdefRecord[] ndefRecords = ndefMesg.getRecords();
    if (ndefRecords == null) {
        return;
    }
    for (NdefRecord record : ndefRecords) {
        short tnf = record.getTnf();
        String type = new String(record.getType());
        if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) {
            String url = new String(record.getPayload());
            recordBadge(url);
        }
    }
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Handle incoming intents. Do not load a product if we already have one.
 *///from  www. j  av a  2s . c  o  m
@Override
protected void onResume() {
    super.onResume();

    String[] options = { InternalConstants.PRODUCT_OPTION_BASIC, InternalConstants.PRODUCT_OPTION_CATEGORIES,
            InternalConstants.PRODUCT_OPTION_CLASSIFICATION, InternalConstants.PRODUCT_OPTION_DESCRIPTION,
            InternalConstants.PRODUCT_OPTION_GALLERY, InternalConstants.PRODUCT_OPTION_PRICE,
            InternalConstants.PRODUCT_OPTION_PROMOTIONS, InternalConstants.PRODUCT_OPTION_REVIEW,
            InternalConstants.PRODUCT_OPTION_STOCK, InternalConstants.PRODUCT_OPTION_VARIANT };

    String productCode = null;

    Intent intent = getIntent();

    // Direct Call
    if (intent.hasExtra(DataConstants.PRODUCT_CODE)) //direct call from search list for example
    {
        productCode = intent.getStringExtra(DataConstants.PRODUCT_CODE);
    }
    // NFC Call
    else if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) //NFC 
    {
        Tag tag = getIntent().getExtras().getParcelable(NfcAdapter.EXTRA_TAG);

        Ndef ndef = Ndef.get(tag);
        NdefMessage message = ndef.getCachedNdefMessage();

        NdefRecord record = message.getRecords()[0];
        if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN
                && Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
            productCode = RegexUtil
                    .getProductCode(new String(record.getPayload(), 1, record.getPayload().length - 1));
        }
    }
    // Call from another application (QR Code) 
    else if (StringUtils.equals(intent.getAction(), Intent.ACTION_VIEW)) {
        productCode = RegexUtil.getProductCode(intent.getDataString());
    }

    if (StringUtils.isNotEmpty(productCode)) {
        this.enableAndroidBeam(productCode);
    }

    // Only load if we don't have a product already
    if (mProduct == null) {
        populateProduct(productCode, options);
    }

    invalidateOptionsMenu();
}

From source file:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java

private String read(Tag tag) throws IOException, FormatException {
    //read string from tag
    String password = null;/*from   w  w w  . j  a  va  2s  . c  o m*/
    Ndef ndef = Ndef.get(tag);
    ndef.connect();
    NdefMessage ndefMessage = ndef.getCachedNdefMessage();

    NdefRecord[] records = ndefMessage.getRecords();
    for (NdefRecord ndefRecord : records) {
        if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN
                && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            try {
                password = readText(ndefRecord);
            } catch (UnsupportedEncodingException e) {
                Log.e(Constants.TAG, "Failed to read password from tag", e);
            }
        }
    }
    ndef.close();
    return password;
}

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Handles an intent as received by the Activity, be it with a MAIN or an
 * NDEF_DISCOVERED action./*from  ww w  .j a  va2s  .  co  m*/
 *
 * @param intent The intent to handle
 */
private void handleIntent(Intent intent) {
    String action = intent.getAction();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        // This is an "NFC tag scanned" intent
        String type = intent.getType();
        Log.d(TAG, "Read tag with type: " + type);

        if (MIME_VCARD.equals(type) || MIME_XVCARD.equals(type)) {
            if (mVCardEngine == null) {
                mVCardEngine = new VCardEngine();
            }

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                Ndef ndefTag = Ndef.get(tag);
                NdefMessage ndefMessage;

                // ndefTag can be null if the tag was INITIALIZED
                // but not actually written to
                if (ndefTag != null) {
                    ndefMessage = ndefTag.getCachedNdefMessage();
                    parseAndInsertVCard(ndefMessage);
                }
            }
        } else {
            Log.i(TAG, "Ignoring NDEF with mime type: " + type);
        }
    }

    // Nothing else to do if this is a MAIN intent...
}

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;// www.jav  a  2 s.  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);
        }

    }

}