Example usage for android.nfc NdefMessage NdefMessage

List of usage examples for android.nfc NdefMessage NdefMessage

Introduction

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

Prototype

public NdefMessage(NdefRecord[] records) 

Source Link

Document

Construct an NDEF Message from one or more NDEF Records.

Usage

From source file:de.gadc.moneybeam.MoneyBeamActivity.java

/**
 * This method creates a new {@link NdefMessage} by using a
 * {@link JSONObject}./*from w ww  . jav a  2s.c  o m*/
 * 
 * @return the {@link NdefMessage} for the message callback
 */
public NdefMessage createNdefMessage(NfcEvent event) {
    NdefMessage msg = null;
    String text = null;
    try {
        text = generateJSON().toString();
        msg = new NdefMessage(
                new NdefRecord[] { createMimeRecord("application/paypal-moneybeam", text.getBytes()),
                        NdefRecord.createApplicationRecord(getPackageName()) });

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return msg;
}

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

protected void writeSelection(Intent intent) {
    ListView list = (ListView) findViewById(R.id.listView1);
    if (list.getCount() == 0)
        return;/*from   w w w  .j  av a  2s .c om*/

    try {

        Object[] results = ((OptionListAdapter) list.getAdapter()).getCheckedValues();
        JSONObject obj = new JSONObject();

        JSONArray array = new JSONArray();

        if (null != results) {
            for (Object result : results)
                array.put(result.toString());
        }

        obj.put("selection", array);
        obj.put("key", selectKey);

        SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key),
                Context.MODE_PRIVATE);

        // android studio (0.5.1) decorates this line as an error (some
        // of the time, anyway) but it's not an error.

        String identifier = sharedPref.getString(getString(R.string.user_id_key), "");
        if (identifier.length() > 0)
            obj.put("user", identifier);

        String json = obj.toString(0);

        String outbound = "\u0002en";
        outbound += json;

        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, new byte[] { 'T' }, null,
                outbound.getBytes());

        NdefMessage message = new NdefMessage(new NdefRecord[] { textRecord });
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        ndef.connect();

        ndef.writeNdefMessage(message);
        ndef.close();

        Toast.makeText(this, R.string.write_ok, Toast.LENGTH_LONG).show();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);

    } catch (Exception e) {

        Log.d(TAG, e.toString());
        String err = getString(R.string.tag_write_err) + "\n" + e.getMessage();
        Toast.makeText(this, err, Toast.LENGTH_LONG).show();
    }
}

From source file:st.alr.homA.ActivityQuickpublishNfc.java

private boolean write(String text, Tag tag) {
    boolean success = true;

    NdefRecord aar = NdefRecord.createApplicationRecord("st.alr.homA");
    NdefRecord[] records = { createRecord(text), aar };
    NdefMessage ndefMsg = new NdefMessage(records);

    try {//from w  ww. j a  va  2 s. co  m
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            ndef.connect();

            if (!ndef.isWritable()) {
                publishProgress(getResources().getString(R.string.nfcWriteDialogTagReadOnly), false);
                success = false;
            }
            if (ndef.getMaxSize() < ndefMsg.getByteArrayLength()) {
                publishProgress(
                        getResources().getString(R.string.nfcWriteDialogTagCapacityIs) + ndef.getMaxSize()
                                + " byte" + getResources().getString(R.string.nfcWriteDialogTagMessageSizeIs)
                                + ndefMsg.getByteArrayLength() + "byte.",
                        false);
                success = false;
            }

            ndef.writeNdefMessage(ndefMsg);
            success = true;
        } else {
            NdefFormatable format = NdefFormatable.get(tag);
            if (format != null) {
                try {
                    format.connect();
                    format.format(ndefMsg);
                    publishProgress(getResources().getString(R.string.nfcWriteDialogTagFormatedAndWrote), true);
                    success = true;
                } catch (IOException e) {
                    publishProgress(getResources().getString(R.string.nfcWriteDialogTagFailedToFormat), false);
                    success = false;
                }
            } else {
                publishProgress(getResources().getString(R.string.nfcWriteDialogTagNoNDEFSupport), false);
                success = false;
            }
        }
    } catch (Exception e) {
        Log.e(this.toString(),
                getResources().getString(R.string.nfcWriteDialogTagFailedToWrite) + " (" + e.getMessage() + ")",
                e);
    }

    return success;
}

From source file:org.floens.chan.ui.controller.ThreadController.java

@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    Loadable loadable = getLoadable();// w w w . ja  v a 2 s. c o  m
    String url = null;
    NdefMessage message = null;

    if (loadable != null) {
        if (loadable.isThreadMode()) {
            url = ChanUrls.getThreadUrlDesktop(loadable.board, loadable.no);
        } else if (loadable.isCatalogMode()) {
            url = ChanUrls.getCatalogUrlDesktop(loadable.board);
        }
    }

    if (url != null) {
        try {
            Logger.d(TAG, "Pushing url " + url + " to android beam");
            NdefRecord record = NdefRecord.createUri(url);
            message = new NdefMessage(new NdefRecord[] { record });
        } catch (IllegalArgumentException e) {
            Logger.e(TAG, "NdefMessage create error", e);
        }
    }

    return message;
}

From source file:jp.co.brilliantservice.android.writertdtext.HomeActivity.java

/**
 * RTD Text Record??NdefMessage????/*w  w  w.  j av a 2 s.  c o m*/
 * 
 * @param text 
 * @param languageCode (ISO/IANA)
 * @return
 */
private NdefMessage createTextMessage(String text, String languageCode) {
    try {
        byte statusByte = (byte) languageCode.length();
        byte[] rawLanguageCode = languageCode.getBytes("US-ASCII");
        byte[] rawText = text.getBytes("UTF-8");

        ByteArrayBuffer buffer = new ByteArrayBuffer(1 + rawLanguageCode.length + rawText.length);
        buffer.append(statusByte);
        buffer.append(rawLanguageCode, 0, rawLanguageCode.length);
        buffer.append(rawText, 0, rawText.length);

        byte[] payload = buffer.toByteArray();
        NdefMessage message = new NdefMessage(new NdefRecord[] {
                new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload) });
        return message;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.example.android.nfcprovisioning.NfcProvisioningFragment.java

@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    if (mProvisioningValues == null) {
        return null;
    }//from  w  w w .j a  v  a2  s  . c o m
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Properties properties = new Properties();
    // Store all the values into the Properties object
    for (Map.Entry<String, String> e : mProvisioningValues.entrySet()) {
        if (!TextUtils.isEmpty(e.getValue())) {
            String value;
            if (e.getKey().equals(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) {
                // Make sure to surround SSID with double quotes
                value = e.getValue();
                if (!value.startsWith("\"") || !value.endsWith("\"")) {
                    value = "\"" + value + "\"";
                }
            } else {
                value = e.getValue();
            }
            properties.put(e.getKey(), value);
        }
    }
    // Make sure to put local time in the properties. This is necessary on some devices to
    // reliably download the device owner APK from an HTTPS connection.
    if (!properties.contains(DevicePolicyManager.EXTRA_PROVISIONING_LOCAL_TIME)) {
        properties.put(DevicePolicyManager.EXTRA_PROVISIONING_LOCAL_TIME,
                String.valueOf(System.currentTimeMillis()));
    }
    try {
        properties.store(stream, getString(R.string.nfc_comment));
        NdefRecord record = NdefRecord.createMime(DevicePolicyManager.MIME_TYPE_PROVISIONING_NFC,
                stream.toByteArray());
        return new NdefMessage(new NdefRecord[] { record });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.openhab.habdroid.ui.OpenHABWriteTagActivity.java

private void writeTag(Tag tag, String uri) {
    Log.d(TAG, "Creating tag object for URI " + uri);
    TextView writeTagMessage = findViewById(R.id.write_tag_message);

    NdefRecord[] ndefRecords = new NdefRecord[] { NdefRecord.createUri(uri) };
    NdefMessage message = new NdefMessage(ndefRecords);
    NdefFormatable ndefFormatable = NdefFormatable.get(tag);

    if (ndefFormatable != null) {
        Log.d(TAG, "Tag is uninitialized, formating");
        try {/*  w  w w .  ja  v  a2s  . c o m*/
            ndefFormatable.connect();
            ndefFormatable.format(message);
            ndefFormatable.close();
            writeTagMessage.setText(R.string.info_write_tag_finished);
            autoCloseActivity();
        } catch (IOException | FormatException e) {
            Log.e(TAG, "Writing to unformatted tag failed: " + e);
            writeTagMessage.setText(R.string.info_write_failed);
        }
    } else {
        Log.d(TAG, "Tag is initialized, writing");
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            try {
                Log.d(TAG, "Connecting");
                ndef.connect();
                Log.d(TAG, "Writing");
                if (ndef.isWritable()) {
                    ndef.writeNdefMessage(message);
                }
                Log.d(TAG, "Closing");
                ndef.close();
                writeTagMessage.setText(R.string.info_write_tag_finished);
                autoCloseActivity();
            } catch (IOException | FormatException e) {
                Log.e(TAG, "Writing to formatted tag failed: " + e);
                writeTagMessage.setText(R.string.info_write_failed);
            }
        } else {
            Log.e(TAG, "Ndef == null");
            writeTagMessage.setText(R.string.info_write_failed);
        }
    }
}

From source file:mai.whack.StickyNotesActivity.java

private void onDataRead(Intent intent) {
    // Parse the intent
    NdefMessage[] msgs = null;/* w w w .  ja  v a 2  s  .  c om*/
    String action = intent.getAction();
    byte[] tagId = null;
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            // Unknown tag type
            byte[] empty = new byte[] {};
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            msgs = new NdefMessage[] { msg };
        }
    } else {
        Log.d(TAG, "Unknown intent.");
        finish();
    }

    String msg = new String(msgs[0].getRecords()[0].getPayload());
    mHttpGetThread = new HttpGetThread("http://192.168.1.192/store/" + toHex(tagId));
    mHttpGetThread.start();
    // mHttpPostThread = new HttpPostThread("aaaaa", "bbbbb", "sdgsdfdsfs");
    // mHttpPostThread.start();
}

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

@TargetApi(14)
private void createNdefPushMessageCallback() {
    NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter != null) {
        mNfcAdapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
            @Override//from   w  w  w  .  j a  va 2  s . c o  m
            public NdefMessage createNdefMessage(NfcEvent event) {
                return new NdefMessage(new NdefRecord[] {
                        new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                                "application/vnd.net.eledge.android.europeana.search".getBytes(), new byte[0],
                                searchController.getPortalUrl().getBytes()),
                        NdefRecord.createApplicationRecord(getPackageName()) });
            }
        }, this);
    }
}