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:org.getlantern.firetweet.fragment.support.UserListFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);//from  www.  ja va2s .co m

    final FragmentActivity activity = getActivity();

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUserList userList = getUserList();
            if (userList == null)
                return null;
            return new NdefMessage(new NdefRecord[] { NdefRecord.createUri(
                    LinkCreator.getTwitterUserListLink(userList.user_screen_name, userList.name)), });
        }
    });

    mHeaderDrawerLayout.setDrawerCallback(this);

    mPagerAdapter = new SupportTabsAdapter(activity, getChildFragmentManager());

    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);
    if (activity instanceof IThemedActivity) {
        mPagerIndicator.setStripColor(((IThemedActivity) activity).getCurrentThemeColor());
    } else {

    }

    mTwitterWrapper = getApplication().getTwitterWrapper();
    mProfileImageLoader = getApplication().getMediaLoaderWrapper();
    mProfileImageView.setOnClickListener(this);
    mUserListDetails.setOnClickListener(this);
    mRetryButton.setOnClickListener(this);
    getUserListInfo(false);

    setupUserPages();
}

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

public void WriteTag(final Tag receivedTag) {
    tagHandler.sendEmptyMessage(TAG_IO_IN_PROGRESS);

    (new Thread() {

        public void run() {
            //This could go all kinds of weird
            Ndef thisNdef = null;/*from w ww  . j a  v  a  2s  .  com*/

            try {
                thisNdef = Ndef.get(receivedTag);
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e);
                e.printStackTrace();
            }

            if (null == thisNdef) {
                NdefFormatable formatter = null;
                try {
                    formatter = NdefFormatable.get(receivedTag);
                    formatter.connect();
                    formatter.format(
                            new NdefMessage(new NdefRecord[] { NdefRecord.createApplicationRecord("io.d0") }));
                    formatter.close();
                    thisNdef = Ndef.get(receivedTag);
                } catch (Exception d) {
                    BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", d);
                    d.printStackTrace();
                    tagHandler.sendEmptyMessage(FORMATEXCEPTION);
                }
            }

            try {
                if (null == thisNdef) {
                    throw new FormatException("No NDEF Tag returned from get");
                } else {
                    thisNdef.connect();
                }

                if (thisNdef.isWritable()) {
                    //Is this a 203 or larger?
                    if (thisNdef.getMaxSize() < aaRecord.toByteArray().length + idRecord.toByteArray().length) {
                        /*Log.i("WriteTag","This tag was too big. tried to write " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize());
                        idRecord = NdefRecord.createMime("text/plain", Integer.toString(tagMetaData.getInt("i")).getBytes(Charset.forName("US-ASCII")));
                        Log.i("WriteTag Size Check", "Writing " + (idRecord.toByteArray().length + aaRecord.toByteArray().length) + " to " + thisNdef.getMaxSize());*/
                        tagHandler.sendEmptyMessage(SIZE_ERROR);
                    } else {
                        //Log.i("WriteTag Size Check", "Writing " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize());
                        NdefMessage tagMsg = new NdefMessage(new NdefRecord[] { idRecord, aaRecord });
                        //Log.i("WriteTag Size Check", "Wrote " + tagMsg.getByteArrayLength());
                        thisNdef.writeNdefMessage(tagMsg);
                        thisNdef.makeReadOnly();
                        thisNdef.close();
                        tagHandler.sendEmptyMessage(WRITE_SUCCESS);
                    }
                } else {
                    tagHandler.sendEmptyMessage(READONLY);
                }
            } catch (IOException e) {
                BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e);
                tagHandler.sendEmptyMessage(IOEXCEPTION);
            } catch (FormatException e) {
                BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e);
                e.printStackTrace();
                tagHandler.sendEmptyMessage(FORMATEXCEPTION);
            }
        }
    }).start();
}

From source file:org.getlantern.firetweet.fragment.support.StatusFragment.java

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final View view = getView();
    if (view == null)
        throw new AssertionError();
    final Context context = view.getContext();
    final boolean compact = Utils.isCompactCards(context);
    Utils.setNdefPushMessageCallback(getActivity(), new CreateNdefMessageCallback() {
        @Override// w  ww  .  j a  va 2s.c o  m
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableStatus status = getStatus();
            if (status == null)
                return null;
            return new NdefMessage(new NdefRecord[] { NdefRecord
                    .createUri(LinkCreator.getTwitterStatusLink(status.user_screen_name, status.id)), });
        }
    });
    mLayoutManager = new StatusListLinearLayoutManager(context, mRecyclerView);
    mItemDecoration = new DividerItemDecoration(context, mLayoutManager.getOrientation());
    if (compact) {
        mRecyclerView.addItemDecoration(mItemDecoration);
    }
    mLayoutManager.setRecycleChildrenOnDetach(true);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setClipToPadding(false);
    mStatusAdapter = new StatusAdapter(this, compact);
    mStatusAdapter.setEventListener(this);
    mRecyclerView.setAdapter(mStatusAdapter);

    setState(STATE_LOADING);

    getLoaderManager().initLoader(LOADER_ID_DETAIL_STATUS, getArguments(), this);
}

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());//from  ww w .j a v a 2 s  .com
    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   w  w w  . j a  va  2  s .  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/*from  w  ww. j ava  2s . c o 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;

}

From source file:com.irccloud.android.activity.ImageViewerActivity.java

private void loadImage(String urlStr) {
    try {//w w w . java2s.co m
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && urlStr.startsWith("https://")) {
            GingerbreadImageProxy proxy = new GingerbreadImageProxy();
            proxy.init();
            proxy.start();
            urlStr = String.format("http://127.0.0.1:%d/%s", proxy.getPort(), urlStr);
        }
        URL url = new URL(urlStr);

        mImage.loadDataWithBaseURL(null, "<!DOCTYPE html>\n"
                + "<html><head><style>html, body, table { height: 100%; width: 100%; background-color: #000;}</style></head>\n"
                + "<body>\n" + "<table><tr><td>" + "<img src='" + url.toString()
                + "' width='100%' onerror='Android.imageFailed()' onclick='Android.imageClicked()' style='background-color: #fff;'/>\n"
                + "</td></tr></table>" + "</body>\n" + "</html>", "text/html", "UTF-8", null);

        try {
            if (Build.VERSION.SDK_INT >= 16) {
                NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
                if (nfc != null) {
                    nfc.setNdefPushMessage(new NdefMessage(NdefRecord.createUri(urlStr)), this);
                }
            }
        } catch (Exception e) {
        }
    } catch (Exception e) {
        fail();
    }
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (writeNfcEnabled) {
        // Handle the NFC part...

        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0);
        String text = preferences.getString("SSID", "N/A") + "||" + preferences.getString("password", "N/A");

        // create a new NdefRecord
        NdefRecord record = createMimeRecord("application/ch.bfh.instacircle", text.getBytes());

        // create a new Android Application Record
        NdefRecord aar = NdefRecord.createApplicationRecord(getPackageName());

        // create a ndef message
        NdefMessage message = new NdefMessage(new NdefRecord[] { record, aar });

        // extract tag from the intent
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        // write the tag
        writeTag(tag, message);/*from  ww w. j  a  v a2  s  . c o m*/

        // close the dialog
        writeNfcEnabled = false;
        writeNfcTagDialog.dismiss();
    }
}

From source file:org.hopestarter.wallet.ui.RequestCoinsFragment.java

@Override
public NdefMessage createNdefMessage(final NfcEvent event) {
    final byte[] paymentRequest = paymentRequestRef.get();
    if (paymentRequest != null)
        return new NdefMessage(
                new NdefRecord[] { Nfc.createMime(PaymentProtocol.MIMETYPE_PAYMENTREQUEST, paymentRequest) });
    else/*from   w w w  .j ava2 s.c  o m*/
        return null;
}