Example usage for android.nfc NdefMessage getRecords

List of usage examples for android.nfc NdefMessage getRecords

Introduction

In this page you can find the example usage for android.nfc NdefMessage getRecords.

Prototype

public NdefRecord[] getRecords() 

Source Link

Document

Get the NDEF Records inside this NDEF Message.

An NdefMessage always has one or more NDEF Records: so the following code to retrieve the first record is always safe (no need to check for null or array length >= 1):

 NdefRecord firstRecord = ndefMessage.getRecords()[0]; 

Usage

From source file:com.sftoolworks.nfcoptions.SelectActivity.java

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

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    Intent intent = getIntent();//from   ww w  . ja v a 2s  .co  m
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    String title = getString(R.string.default_select_title);

    TextView textViewBottom = (TextView) findViewById(R.id.textView2);
    textViewBottom.setText("");

    if (rawMessages != null) {

        ArrayList<Object> entries = new ArrayList<Object>();

        String data = null;

        for (Parcelable rawMessage : rawMessages) {
            NdefMessage message = (NdefMessage) rawMessage;
            NdefRecord[] records = message.getRecords();
            if (records.length > 1) {
                byte[] bArray = records[1].getPayload();
                byte languageLength = bArray[0];

                languageLength++; // because of the length byte

                data = new String(bArray, languageLength, bArray.length - languageLength);
            }
        }

        try {
            JSONObject json = (JSONObject) new JSONTokener(data).nextValue();
            if (json.has("title"))
                title = json.getString("title");
            if (json.has("key"))
                selectKey = json.getString("key");
            if (json.has("options")) {
                JSONArray arr = json.getJSONArray("options");
                for (int i = 0; i < arr.length(); i++) {
                    entries.add(parseJObject(arr.getJSONObject(i)));
                }
            }

            ListView list = (ListView) findViewById(R.id.listView1);
            list.setAdapter(new OptionListAdapter(this, entries.toArray()));

            list.setOnItemClickListener(new ListView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    CheckBox cb = (CheckBox) view.findViewById(R.id.optionListCheckBox);
                    cb.setChecked(!cb.isChecked());
                }
            });

            textViewBottom.setText(getString(R.string.tap_again));

        } catch (Exception e) {
            String message = getString(R.string.json_err);
            message += "\n";
            message += e.getMessage();

            Toast.makeText(this, message, Toast.LENGTH_LONG).show();

            Log.d(TAG, getString(R.string.json_err));
            Log.d(TAG, e.toString());
            Log.d(TAG, data);
        }
    } else {
        title = getString(R.string.no_tag);
    }

    TextView msg = (TextView) findViewById(R.id.textView1);
    msg.setText(title);

}

From source file:pl.edu.pw.eiti.groupbuying.partner.android.ClaimCouponsActivity.java

/**
  * Parses the NDEF Message from the intent and prints to the TextView
  *//*from  w w  w.j  a v a  2s  .co m*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
private void processIntent(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    extractCouponInfo(new String(msg.getRecords()[0].getPayload()));
    setIntent(null);
}

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

public void processReadTag(NdefMessage ndef) {

    final String tag_content = new String(ndef.getRecords()[0].getPayload());

    //setContentView(R.layout.tag_viewer); //?
    EditText twitterHandleEditText = (EditText) findViewById(R.id.txtTwitterHandle);
    final String twitter_handle = twitterHandleEditText.getText().toString();

    Log.i(">>> NDEF:", tag_content);
    Log.i(">>> TWITTER:", twitter_handle); // THIS DOESN'T GET PRINTED?!

    // this doesn't seem like the proper way to do this #yolo
    Thread thread = new Thread(new Runnable() {
        @Override/*  w w w .j  av  a2 s .c  o  m*/
        public void run() {
            try {
                // build request
                URL url = new URL("http://10.2.2.147:8666/");
                //URL url = new URL("http://httpbin.org/post");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-type", "application/json");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                /*
                // create POST body and send it over
                Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("ndef", tag_content)
                    .appendQueryParameter("twitter_handle", "omerk");
                String query = builder.build().getEncodedQuery();
                */
                OutputStream os = conn.getOutputStream();

                //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                JSONObject json = new JSONObject();
                json.put("ndef", tag_content);
                json.put("twitter", twitter_handle);

                os.write(json.toString().getBytes("UTF-8"));
                os.flush();
                os.close();

                conn.connect();

                // read the response
                Log.i(">>> ResponseCode: ", "" + conn.getResponseCode());
                InputStream in = new BufferedInputStream(conn.getInputStream());
                java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
                String r = s.hasNext() ? s.next() : "";
                Log.i(">>> ResponseBody: ", r);
            } catch (Exception e) {
                Log.i(">>> OOPS: ", e.toString());
            }
        }
    });

    thread.start();

}

From source file:net.eledge.android.europeana.gui.activity.RecordActivity.java

private void handleIntent(Intent intent) {
    String id = null;//from  ww w.  j a  va2 s.  c om
    if (intent != null) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            // only one message sent during the beam
            NdefMessage msg = (NdefMessage) rawMsgs[0];
            // record 0 contains the MIME type, record 1 is the AAR, if present
            id = new String(msg.getRecords()[0].getPayload());
        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            id = StringUtils.defaultIfBlank(intent.getDataString(), intent.getStringExtra(RECORD_ID));
        }
        if (StringUtils.contains(id, "europeana.eu/")) {
            Uri uri = Uri.parse(id);
            List<String> paths = uri.getPathSegments();
            if ((paths != null) && (paths.size() == 4)) {
                String collectionId = paths.get(paths.size() - 2);
                String recordId = StringUtils.removeEnd(paths.get(paths.size() - 1), ".html");
                id = StringUtils.join("/", collectionId, "/", recordId);
            } else {
                // invalid url/id, cancel opening record
                id = null;
            }
        }
        if (StringUtils.isNotBlank(id)) {
            openRecord(id);
        }
    }
}

From source file:net.eledge.android.europeana.gui.activity.SearchActivity.java

private void handleIntent(Intent intent) {
    String query = null;//  ww  w  .  jav a  2 s . c  om
    String[] qf = null;
    if (intent != null) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            query = intent.getStringExtra(SearchManager.QUERY);
            qf = splitFacets(intent.getStringExtra(SearchManager.USER_QUERY));
        } else if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msg = (NdefMessage) parcelables[0];
            Uri uri = Uri.parse(new String(msg.getRecords()[0].getPayload()));
            query = uri.getQueryParameter("query");
            qf = StringArrayUtils.toArray(uri.getQueryParameters("qf"));
        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            query = intent.getDataString();
            if (!TextUtils.isEmpty(query)) {
                if (StringUtils.contains(query, "europeana.eu/")) {
                    Uri uri = Uri.parse(query);
                    query = uri.getQueryParameter("query");
                    qf = StringArrayUtils.toArray(uri.getQueryParameters("qf"));
                }
            }
        } else {
            // no search action recognized? end this activity...
            closeSearchActivity();
        }
        if (!TextUtils.isEmpty(query) && !TextUtils.equals(runningSearch, query)) {
            runningSearch = query;
            if (StringArrayUtils.isNotBlank(qf)) {
                searchController.newSearch(this, query, qf);
            } else {
                searchController.newSearch(this, query);
            }
            getSupportActionBar().setTitle(searchController.getSearchTitle(this));
        }
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockToggle.java

@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
    mServiceInterface = ITapLockService.Stub.asInterface(binder);
    if (mUIInterface != null) {
        try {/*from   w w  w . java 2  s  . c o m*/
            mServiceInterface.setCallback(mUIInterface);
        } catch (RemoteException e) {
            Log.e(TAG, e.toString());
        }
    }
    Intent intent = getIntent();
    if (intent != null) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
                && intent.hasExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)) {
            Log.d(TAG, "service connected, NDEF_DISCOVERED");
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage message;
            if (rawMsgs != null) {
                // process the first message
                message = (NdefMessage) rawMsgs[0];
                // process the first record
                NdefRecord record = message.getRecords()[0];
                if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
                    try {
                        byte[] payload = record.getPayload();
                        /*
                         * payload[0] contains the "Status Byte Encodings" field, per the
                         * NFC Forum "Text Record Type Definition" section 3.2.1.
                         *
                         * bit7 is the Text Encoding Field.
                         *
                         * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
                         * The text is encoded in UTF16
                         *
                         * Bit_6 is reserved for future use and must be set to zero.
                         *
                         * Bits 5 to 0 are the length of the IANA language code.
                         */
                        String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
                        int languageCodeLength = payload[0] & 0077;
                        String taggedDeviceName = new String(payload, languageCodeLength + 1,
                                payload.length - languageCodeLength - 1, textEncoding);
                        manageDevice(taggedDeviceName, ACTION_TOGGLE);
                    } catch (UnsupportedEncodingException e) {
                        // should never happen unless we get a malformed tag.
                        Log.e(TAG, e.toString());
                        finish();
                    }
                } else
                    finish();
            } else
                finish();
        } else if (intent.getData() != null) {
            String taggedDeviceName = intent.getData().getHost();
            if (taggedDeviceName != null)
                manageDevice(taggedDeviceName, ACTION_TOGGLE);
            else
                finish();
        } else if (ACTION_UNLOCK.equals(action) || ACTION_LOCK.equals(action) || ACTION_TOGGLE.equals(action))
            manageDevice(intent.getStringExtra(EXTRA_DEVICE_NAME), action);
        else
            finish();
    } else
        finish();
}

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

/**
 * Handle incoming intents. Do not load a product if we already have one.
 *//*from   ww w.j a  va 2 s. c  om*/
@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:net.networksaremadeofstring.rhybudd.ViewZenossDeviceActivity.java

void processIntent(Intent intent) {
    try {//from  ww w  .  j a va 2s .c o m
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

        if (null != rawMsgs && rawMsgs.length > 0) {
            NdefMessage msg = (NdefMessage) rawMsgs[0];

            /*for(NdefRecord nR : msg.getRecords())
            {
            String tmpString = new String(nR.getPayload());
            Log.e("Found: ", tmpString);
            }*/

            currentDeviceID = "/zport/dmd/Devices/" + new String(msg.getRecords()[0].getPayload());

        }
    } catch (Exception e) {
        e.printStackTrace();
        BugSenseHandler.sendExceptionMessage("ViewZenossDeviceActivity", "processIntent", e);
        try {
            Toast.makeText(this, "There was a problem trying to find the device ID that was beamed",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e1) {
            BugSenseHandler.sendExceptionMessage("ViewZenossDeviceActivity", "processIntent Toast", e1);
        }
    } finally {
        try {
            triggerUIHandler.sendEmptyMessage(UI_POPULATE);
        } catch (Exception e) {
            BugSenseHandler.sendExceptionMessage("ViewZenossDeviceActivity", "processIntent", e);
        }
    }
}

From source file:org.thialfihar.android.apg.ui.ImportKeysActivity.java

/**
 * NFC: Parses the NDEF Message from the intent and prints to the TextView
 *//*from  w w w .j a  va  2s  .c  o  m*/
@SuppressLint("NewApi")
void handleActionNdefDiscovered(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    byte[] receivedKeyringBytes = msg.getRecords()[0].getPayload();

    Intent importIntent = new Intent(this, ImportKeysActivity.class);
    importIntent.setAction(ImportKeysActivity.ACTION_IMPORT_KEY);
    importIntent.putExtra(ImportKeysActivity.EXTRA_KEY_BYTES, receivedKeyringBytes);

    handleActions(null, importIntent);
}

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   ww w.java2 s  .co  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;
}