Example usage for android.nfc NdefRecord createMime

List of usage examples for android.nfc NdefRecord createMime

Introduction

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

Prototype

public static NdefRecord createMime(String mimeType, byte[] mimeData) 

Source Link

Document

Create a new NDEF Record containing MIME data.

Use this method to encode MIME-typed data into an NDEF Record, such as "text/plain", or "image/jpeg".

The mimeType parameter will be normalized with Intent#normalizeMimeType to follow Android best practices for intent filtering, for example to force lower-case.

Usage

From source file:ca.psiphon.ploggy.ActivitySendIdentityByNfc.java

@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    try {/* w w  w .j a  v  a  2  s  .com*/
        String payload = Json.toJson(Data.getInstance().getSelf().mPublicIdentity);
        return new NdefMessage(new NdefRecord[] { NdefRecord.createMime(NFC_MIME_TYPE, payload.getBytes()),
                NdefRecord.createApplicationRecord(NFC_AAR_PACKAGE_NAME) });
    } catch (Utils.ApplicationError e) {
        Log.addEntry(LOG_TAG, "failed to create outbound NFC message");
    }
    return null;
}

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

/**
 * NFC: Implementation for the CreateNdefMessageCallback interface
 *//*from   w  w w  .  j  a v a 2s .c o m*/
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    /**
     * When a device receives a push with an AAR in it, the application specified in the AAR is
     * guaranteed to run. The AAR overrides the tag dispatch system. You can add it back in to
     * guarantee that this activity starts when receiving a beamed message. For now, this code
     * uses the tag dispatch system.
     */
    NdefMessage msg = new NdefMessage(NdefRecord.createMime(Constants.NFC_MIME, mSharedKeyringBytes),
            NdefRecord.createApplicationRecord(Constants.PACKAGE_NAME));
    return msg;
}

From source file:net.networksaremadeofstring.rhybudd.WriteNFCActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BugSenseHandler.initAndStartSession(WriteNFCActivity.this, "44a76a8c");

    setContentView(R.layout.write_tag_activity);

    try {//w  ww .j a v a 2  s .  c o  m
        getActionBar().setSubtitle(getString(R.string.NFCTitle));
        getActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (Exception gab) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", gab);
    }

    //Quick test
    try {
        UID = getIntent().getExtras().getString(PAYLOAD_UID).replace("/zport/dmd/Devices/", "");

        aaRecord = NdefRecord.createApplicationRecord("net.networksaremadeofstring.rhybudd");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //idRecord = NdefRecord.createExternal("rhybudd:tag", "z", UID.getBytes(Charset.forName("US-ASCII")));
            idRecord = NdefRecord.createMime("application/vnd.rhybudd.device", UID.getBytes());
        } else {
            idRecord = NdefRecord.createUri("rhybudd://" + UID);
        }

        ((TextView) findViewById(R.id.SizesText)).setText("This payload is "
                + (aaRecord.toByteArray().length + idRecord.toByteArray().length)
                + " bytes.\n\nAn ultralight can store up to 46 bytes.\nAn Ultralight C or NTAG203 can store up to 137 bytes.\nDespite the name a 1K can only store up to 716 bytes.");
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        try {
            Toast.makeText(this, "Sorry there was error parsing the passed UID, we cannot continue.",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception t) {
            BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", t);
        }

        finish();
    }

    try {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate getDefaultAdapter", e);
        mAdapter = null;
    }

    try {
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate pendingIntent", e);
    }

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

    try {
        ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
                                    You should specify only the ones that you need. */
    } catch (IntentFilter.MalformedMimeTypeException e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        throw new RuntimeException("fail", e);
    }

    try {
        IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        intentFiltersArray = new IntentFilter[] { ndef, td };

        techListsArray = new String[][] { new String[] { NfcF.class.getName(), NfcA.class.getName(),
                Ndef.class.getName(), NdefFormatable.class.getName() } };
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate IntentFilter", e);
    }

    CreateHandlers();
}

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 av 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.sufficientlysecure.keychain.ui.ViewKeyActivity.java

/**
 * NFC: Initialize NFC sharing if OS and device supports it
 *//*from  w  w  w .  j  a  v  a  2s.  c o m*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void initNfc(final Uri dataUri) {
    // check if NFC Beam is supported (>= Android 4.1)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

        // Implementation for the CreateNdefMessageCallback interface
        mNdefCallback = new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent event) {
                /*
                 * When a device receives a push with an AAR in it, the application specified in the AAR is
                 * guaranteed to run. The AAR overrides the tag dispatch system. You can add it back in to
                 * guarantee that this activity starts when receiving a beamed message. For now, this code
                 * uses the tag dispatch system.
                 */
                NdefMessage msg = new NdefMessage(NdefRecord.createMime(Constants.NFC_MIME, mNfcKeyringBytes),
                        NdefRecord.createApplicationRecord(Constants.PACKAGE_NAME));
                return msg;
            }
        };

        // Implementation for the OnNdefPushCompleteCallback interface
        mNdefCompleteCallback = new NfcAdapter.OnNdefPushCompleteCallback() {
            @Override
            public void onNdefPushComplete(NfcEvent event) {
                // A handler is needed to send messages to the activity when this
                // callback occurs, because it happens from a binder thread
                mNfcHandler.obtainMessage(NFC_SENT).sendToTarget();
            }
        };

        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter != null) {
            /*
             * Retrieve mNfcKeyringBytes here asynchronously (to not block the UI)
             * and init nfc adapter afterwards.
             * mNfcKeyringBytes can not be retrieved in createNdefMessage, because this process
             * has no permissions to query the Uri.
             */
            AsyncTask<Void, Void, Void> initTask = new AsyncTask<Void, Void, Void>() {
                protected Void doInBackground(Void... unused) {
                    try {
                        Uri blobUri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
                        mNfcKeyringBytes = (byte[]) mProviderHelper.getGenericData(blobUri,
                                KeychainContract.KeyRingData.KEY_RING_DATA, ProviderHelper.FIELD_TYPE_BLOB);
                    } catch (ProviderHelper.NotFoundException e) {
                        Log.e(Constants.TAG, "key not found!", e);
                    }

                    // no AsyncTask return (Void)
                    return null;
                }

                protected void onPostExecute(Void unused) {
                    // Register callback to set NDEF message
                    mNfcAdapter.setNdefPushMessageCallback(mNdefCallback, ViewKeyActivity.this);
                    // Register callback to listen for message-sent success
                    mNfcAdapter.setOnNdefPushCompleteCallback(mNdefCompleteCallback, ViewKeyActivity.this);
                }
            };

            initTask.execute();
        }
    }
}