Example usage for android.nfc NdefRecord NdefRecord

List of usage examples for android.nfc NdefRecord NdefRecord

Introduction

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

Prototype

public NdefRecord(short tnf, byte[] type, byte[] id, byte[] payload) 

Source Link

Document

Construct an NDEF Record from its component fields.

Recommend to use helpers such as {#createUri} or { #createExternal where possible, since they perform stricter validation that the record is correctly formatted as per NDEF specifications.

Usage

From source file:com.nxp.nfc_demo.fragments.SpeedTestFragment.java

private NdefMessage createNdefMessage(String text) throws UnsupportedEncodingException {
    String lang = "en";
    byte[] textBytes = text.getBytes();
    byte[] langBytes = lang.getBytes("US-ASCII");
    int langLength = langBytes.length;
    int textLength = textBytes.length;
    byte[] payload = new byte[1 + langLength + textLength];
    payload[0] = (byte) langLength;
    System.arraycopy(langBytes, 0, payload, 1, langLength);
    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
    NdefRecord[] records = { record };/*  w  ww . j a  v a 2 s. c om*/
    NdefMessage message = new NdefMessage(records);
    return message;
}

From source file:mai.whack.StickyNotesActivity.java

private NdefMessage getNoteAsNdef() {
    byte[] textBytes = (new String("")).getBytes();
    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), new byte[] {},
            textBytes);//from   w ww  . j a va2 s  .  co m
    return new NdefMessage(new NdefRecord[] { textRecord });
}

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

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from   w ww .j  a  v  a  2s .co  m*/
    if (mInWriteMode) {
        if (intent != null) {
            String action = intent.getAction();
            if (mInWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                    && intent.hasExtra(EXTRA_DEVICE_NAME)) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String name = intent.getStringExtra(EXTRA_DEVICE_NAME);
                if ((tag != null) && (name != null)) {
                    // write the device and address
                    String lang = "en";
                    // don't write the passphrase!
                    byte[] textBytes = name.getBytes();
                    byte[] langBytes = null;
                    int langLength = 0;
                    try {
                        langBytes = lang.getBytes("US-ASCII");
                        langLength = langBytes.length;
                    } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, e.toString());
                    }
                    int textLength = textBytes.length;
                    byte[] payload = new byte[1 + langLength + textLength];

                    // set status byte (see NDEF spec for actual bits)
                    payload[0] = (byte) langLength;

                    // copy langbytes and textbytes into payload
                    if (langBytes != null) {
                        System.arraycopy(langBytes, 0, payload, 1, langLength);
                    }
                    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
                    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                            new byte[0], payload);
                    NdefMessage message = new NdefMessage(
                            new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()) });
                    // Get an instance of Ndef for the tag.
                    Ndef ndef = Ndef.get(tag);
                    if (ndef != null) {
                        try {
                            ndef.connect();
                            if (ndef.isWritable()) {
                                ndef.writeNdefMessage(message);
                            }
                            ndef.close();
                            Toast.makeText(this, "tag written", Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        } catch (FormatException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        NdefFormatable format = NdefFormatable.get(tag);
                        if (format != null) {
                            try {
                                format.connect();
                                format.format(message);
                                format.close();
                                Toast.makeText(getApplicationContext(), "tag written", Toast.LENGTH_LONG);
                            } catch (IOException e) {
                                Log.e(TAG, e.toString());
                            } catch (FormatException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    mNfcAdapter.disableForegroundDispatch(this);
                }
            }
        }
        mInWriteMode = false;
    } else {
        SharedPreferences sp = getSharedPreferences(KEY_PREFS, MODE_PRIVATE);
        onSharedPreferenceChanged(sp, KEY_DEVICES);
        // check if configuring a widget
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                final String[] displayNames = TapLock.getDeviceNames(mDevices);
                final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle("Select device for widget")
                            .setItems(displayNames, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // set the successful widget result
                                    Intent resultValue = new Intent();
                                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                                    setResult(RESULT_OK, resultValue);

                                    // broadcast the new widget to update
                                    JSONObject deviceJObj = mDevices.get(which);
                                    dialog.cancel();
                                    TapLockSettings.this.finish();
                                    try {
                                        sendBroadcast(TapLock
                                                .getPackageIntent(TapLockSettings.this, TapLockWidget.class)
                                                .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
                                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                                                .putExtra(EXTRA_DEVICE_NAME, deviceJObj.getString(KEY_NAME)));
                                    } catch (JSONException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                }
                            }).create();
                    mDialog.show();
                }
            }
        }
        // start the service before binding so that the service stays around for faster future connections
        startService(TapLock.getPackageIntent(this, TapLockService.class));
        bindService(TapLock.getPackageIntent(this, TapLockService.class), this, BIND_AUTO_CREATE);

        int serverVersion = sp.getInt(KEY_SERVER_VERSION, 0);
        if (mShowTapLockSettingsInfo && (mDevices.size() == 0)) {
            if (serverVersion < SERVER_VERSION)
                sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mShowTapLockSettingsInfo = false;
            Intent i = TapLock.getPackageIntent(this, TapLockInfo.class);
            i.putExtra(EXTRA_INFO, getString(R.string.info_taplocksettings));
            startActivity(i);
        } else if (serverVersion < SERVER_VERSION) {
            // TapLockServer has been updated
            sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_hasupdate)
                    .setMessage(R.string.msg_hasupdate)
                    .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                    .setTitle(R.string.msg_pickinstaller)
                                    .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                            final String installer_file = getResources()
                                                    .getStringArray(R.array.installer_values)[which];

                                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                                    .setTitle(R.string.msg_pickdownloader)
                                                    .setItems(R.array.download_entries,
                                                            new DialogInterface.OnClickListener() {

                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                    dialog.cancel();
                                                                    String action = getResources()
                                                                            .getStringArray(
                                                                                    R.array.download_values)[which];
                                                                    if (ACTION_DOWNLOAD_SDCARD.equals(action)
                                                                            && copyFileToSDCard(installer_file))
                                                                        Toast.makeText(TapLockSettings.this,
                                                                                "Done!", Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    else if (ACTION_DOWNLOAD_EMAIL
                                                                            .equals(action)
                                                                            && copyFileToSDCard(
                                                                                    installer_file)) {
                                                                        Intent emailIntent = new Intent(
                                                                                android.content.Intent.ACTION_SEND);
                                                                        emailIntent.setType(
                                                                                "application/java-archive");
                                                                        emailIntent.putExtra(Intent.EXTRA_TEXT,
                                                                                getString(
                                                                                        R.string.email_instructions));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_SUBJECT,
                                                                                getString(R.string.app_name));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_STREAM,
                                                                                Uri.parse("file://"
                                                                                        + Environment
                                                                                                .getExternalStorageDirectory()
                                                                                                .getPath()
                                                                                        + "/"
                                                                                        + installer_file));
                                                                        startActivity(Intent.createChooser(
                                                                                emailIntent, getString(
                                                                                        R.string.button_getserver)));
                                                                    }
                                                                }

                                                            })
                                                    .create();
                                            mDialog.show();
                                        }
                                    }).create();
                            mDialog.show();
                        }
                    }).create();
            mDialog.show();
        }
    }
}

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

void resolveIntent(Intent intent) {
    // Parse the intent
    String action = intent.getAction();
    Log.d("TAG_VIEWER", "in resolve intent");
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        // When a tag is discovered we send it to the service to
        // be save. We
        // include a PendingIntent for the service to call back
        // onto. This
        // will cause this activity to be restarted with
        // onNewIntent(). At
        // that time we read it from the database and view it.
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;/* w ww  .  j  av a  2  s  .c  o  m*/
        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 };
        }
        // Setup the views
        setTitle(R.string.title_scanned_tag);
        buildTagViews(msgs);
    } else {
        Log.e(TAG, "Unknown intent " + intent);
        // finish();
        return;
    }
}

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

private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
    //low-level method for writing nfc
    String lang = "en";
    byte[] textBytes = text.getBytes();
    byte[] langBytes = lang.getBytes("US-ASCII");
    int langLength = langBytes.length;
    int textLength = textBytes.length;
    byte[] payload = new byte[1 + langLength + textLength];

    // set status byte (see NDEF spec for actual bits)
    payload[0] = (byte) langLength;
    // copy langbytes and textbytes into payload
    System.arraycopy(langBytes, 0, payload, 1, langLength);
    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
}

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

/**
 * Build NDEF text record for given parameters
 * /*from w ww.j  a va2 s .com*/
 * @param text
 * @param locale
 * @param encodeInUtf8
 * @return
 */
private NdefRecord buildTextRecord(String text, Locale locale, boolean encodeInUtf8) {

    Log.d(CLASSNAME, "buildTextRecord is called Text:" + text + " Locale:" + locale.toString()
            + " encodeinUtf8:" + encodeInUtf8);
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = text.getBytes(utfEncoding);

    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);

    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}

From source file:mobisocial.musubi.ui.FeedListActivity.java

public void writeGroupToTag(Uri uri) {
    NdefRecord urlRecord = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, NdefRecord.RTD_URI, new byte[] {},
            uri.toString().getBytes());// w  w  w. j av  a  2 s  .c o  m
    NdefMessage ndef = new NdefMessage(new NdefRecord[] { urlRecord });
    mNfc.enableTagWriteMode(ndef);
    Toast.makeText(this, "Touch a tag to write the group...", Toast.LENGTH_SHORT).show();
}

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

/**
 * On create, process NDEF message with its intent action
 *  /*from  ww w .  ja v  a 2s .co m*/
 * @param intent
 */
private String resolveIntent(Intent intent) {
    Log.d(CLASSNAME, "resolveIntent is called intent:" + intent.toString());
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;
        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[0];
            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] payload = dumpTagData(tag).getBytes();
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            msgs = new NdefMessage[] { msg };
        }

        return processNdefMessageArray(msgs);

    }

    return IParsedNdefCommand.COMMAND_UNKNOWN;
}

From source file:com.evandroid.musica.fragment.LyricsViewFragment.java

@TargetApi(16)
private void beamLyrics(final Lyrics lyrics, Activity activity) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter != null && nfcAdapter.isEnabled()) {
        if (lyrics.getText() != null) {
            nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
                @Override/*ww w  .j  a v a  2 s .  co m*/
                public NdefMessage createNdefMessage(NfcEvent event) {
                    try {
                        byte[] payload = lyrics.toBytes(); // whatever data you want to send
                        NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                                "application/lyrics".getBytes(), new byte[0], payload);
                        return new NdefMessage(new NdefRecord[] { record, // your data
                                NdefRecord.createApplicationRecord("com.geecko.QuickLyric"), // the "application record"
                        });
                    } catch (IOException e) {
                        return null;
                    }
                }
            }, activity);
        }
    }
}

From source file:com.example.mynsocial.BluetoothChat.java

NdefMessage create_RTD_TEXT_NdefMessage(String inputText) {

    Log.e(TAG, "+++ create_RTD +++");
    Locale locale = new Locale("en", "US");
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

    boolean encodeInUtf8 = false;
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    byte status = (byte) (utfBit + langBytes.length);

    byte[] textBytes = inputText.getBytes(utfEncoding);

    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
    NdefMessage message = new NdefMessage(new NdefRecord[] { textRecord });
    return message;

}