Example usage for android.nfc NdefRecord TNF_WELL_KNOWN

List of usage examples for android.nfc NdefRecord TNF_WELL_KNOWN

Introduction

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

Prototype

short TNF_WELL_KNOWN

To view the source code for android.nfc NdefRecord TNF_WELL_KNOWN.

Click Source Link

Document

Indicates the type field contains a well-known RTD type name.

Use this tnf with RTD types such as #RTD_TEXT , #RTD_URI .

Usage

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

/**
 * RTD Text Record??NdefMessage????/*from w  w w .j av  a2  s. com*/
 * 
 * @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:mobisocial.nfcserver.DesktopNfcServer.java

private static NdefMessage getHandoverNdef(String ref) {
    NdefRecord[] records = new NdefRecord[3];

    /* Handover Request */
    byte[] version = new byte[] { (0x1 << 4) | (0x2) };
    records[0] = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_HANDOVER_REQUEST, new byte[0],
            version);//from   w w w.java 2 s. com

    /* Collision Resolution */
    records[1] = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, new byte[] { 0x63, 0x72 }, new byte[0],
            new byte[] { 0x0, 0x0 });

    /* Handover record */
    byte[] payload = new byte[ref.length() + 1];
    System.arraycopy(ref.getBytes(), 0, payload, 1, ref.length());
    records[2] = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);

    return new NdefMessage(records);
}

From source file:org.croudtrip.fragments.offer.MyTripDriverFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    setHasOptionsMenu(true);/*from   w ww  .  j  a v a2 s.  co  m*/

    nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], null);
    ndefMessage = new NdefMessage(new NdefRecord[] { ndefRecord });

    return inflater.inflate(R.layout.fragment_my_trip_driver, container, false);
}

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

private NdefMessage createUriMessage(String uri) {
    try {/*from   w  ww.  ja v a2s  .  co m*/
        int index = getProtocolIndex(uri);
        String protocol = sProtocolList.get(index);

        String uriBody = uri.replace(protocol, "");
        byte[] uriBodyBytes = uriBody.getBytes("UTF-8");

        ByteArrayBuffer buffer = new ByteArrayBuffer(1 + uriBody.length());
        buffer.append((byte) index);
        buffer.append(uriBodyBytes, 0, uriBodyBytes.length);

        byte[] payload = buffer.toByteArray();
        NdefMessage message = new NdefMessage(new NdefRecord[] {
                new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload) });

        return message;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

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 {//w  ww. j  a  v  a  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.
 *///  w  w  w  . j av  a  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: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 };//from  w  w  w .ja  v  a2 s. c om
    NdefMessage message = new NdefMessage(records);
    return message;
}

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  v  a 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:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from   w w w.j a va2  s. 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: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);
}