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:com.example.mynsocial.BluetoothChat.java

NdefMessage[] getNdefMessages(Intent intent) {
    Log.e(TAG, "+++ getNdefMessages +++");
    NdefMessage[] msgs = null;// w  ww  . j  a  v a  2s .com
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            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("Peer to Peer 2", "Unknown intent.");
        finish();
    }

    return msgs;
}

From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java

@SuppressLint("NewApi")
NdefMessage[] getNdefMessagesFromIntent(Intent intent) {
    // Parse the intent
    NdefMessage[] msgs = null;/*w  ww  . j  a  v a  2 s .c o  m*/
    String action = intent.getAction();
    if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) || action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        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.e(TAG, "Unknown intent.");
        finish();
    }
    return msgs;
}

From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java

@SuppressLint("NewApi")
@Override//ww  w  .  j  a  va2 s  .  c o  m
public NdefMessage createNdefMessage(NfcEvent arg0) {
    String data;
    if (mEditText != null) {
        data = mEditText.getText().toString();
    } else {
        data = content;
    }

    String mimeType = "application/com.hipipal.qpy.nfc";

    byte[] mimeBytes = mimeType.getBytes(Charset.forName("UTF-8"));
    byte[] dataBytes = data.getBytes(Charset.forName("UTF-8"));
    byte[] id = new byte[0];

    NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, id, dataBytes);

    NdefMessage message = new NdefMessage(new NdefRecord[] { record });

    return message;
}

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

public NdefMessage createNdefMessage() {
    String text = "" + caught + "|" + mGender.name();
    NdefMessage msg = new NdefMessage(
            new NdefRecord[] { createMimeRecord("application/net.lp.hivawareness.beam", text.getBytes())
            /**/*from  ww w  .j  a v a 2s .c o  m*/
             * The Android Application Record (AAR) is commented out. 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.
             */
            // ,NdefRecord.createApplicationRecord("net.lp.hivawareness")
            });
    return msg;
}

From source file:com.example.multi_ndef.Frag_Write.java

/**
 * Format a tag and write our NDEF message
 *//*w  w w.j av  a  2s . c  om*/
//@SuppressLint("NewApi")
private boolean writeTag(Tag tag) {
    // record to launch Play Store if app is not installed

    NdefRecord appRecord = NdefRecord.createApplicationRecord("com.example.multi_ndef");

    try {
        ENGLISH = Locale.ENGLISH;
        encodeInUtf8 = true;
    }

    catch (Exception e) {

        Toast toast = Toast.makeText(getApplicationContext(), "Locale Error " + e.toString(),
                Toast.LENGTH_SHORT);
        toast.show();
    }

    try {

        textRecord = createTextRecord(getText(), ENGLISH, encodeInUtf8);

    }

    catch (Exception e)

    {

        Toast toast = Toast.makeText(getApplicationContext(), "Text Conversion error " + e.toString(),
                Toast.LENGTH_SHORT);
        toast.show();

    }

    try {

        uriRecord = NdefRecord.createUri(getUri());
    }

    catch (Exception e) {

        Toast toast = Toast.makeText(getApplicationContext(), "Uri Conversion error " + e.toString(),
                Toast.LENGTH_SHORT);
        toast.show();
    }

    byte[] mimeBytes = MimeType.AppName.getBytes(Charset.forName("US-ASCII"));

    byte[] mimeBytesBT = MimeType.AppNameBT.getBytes(Charset.forName("US-ASCII"));

    byte[] v_data = VCard();

    // Here data is written
    byte[] payload = data(); // payload in hex

    //Comments by neha - 3 Jul 2014
    byte[] payloadBT = btData();

    NdefRecord VcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/x-vcard".getBytes(), new byte[0],
            v_data);

    NdefRecord BTcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytesBT, new byte[0], payloadBT);

    NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);

    NdefRecord SMSRecord = NdefRecord.createUri(SMSpayload);

    NdefRecord MailRecord = NdefRecord.createUri(Mailpayload);

    NdefRecord TeleRecord = NdefRecord.createUri(Telepayload);

    NdefRecord LocationRecord = NdefRecord.createUri(Locationpayload);

    NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, textRecord, uriRecord, BTcardRecord,
            VcardRecord, SMSRecord, MailRecord, TeleRecord, LocationRecord, appRecord });
    //  ringProgressDialog.dismiss();

    try {
        // see if tag is already NDEF formatted
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            ndef.connect();

            if (!ndef.isWritable()) {
                displayMessage("Read-only tag.");

                return false;
            }

            // work out how much space we need for the data
            int size = message.toByteArray().length;
            if (ndef.getMaxSize() < size) {
                displayMessage("Tag doesn't have enough free space.");

                return false;
            }

            ndef.writeNdefMessage(message);
            displayMessage("Multiple NDEF Records written to tag successfully.");

            return true;
        } else {
            // attempt to format tag
            NdefFormatable format = NdefFormatable.get(tag);
            if (format != null) {
                try {
                    format.connect();
                    format.format(message);
                    displayMessage("Tag written successfully!\nClose this app and scan tag.");

                    return true;
                } catch (IOException e) {
                    displayMessage("Unable to format tag to NDEF.");

                    return false;
                }
            } else {
                displayMessage("Tag doesn't appear to support NDEF format.");

                return false;
            }
        }
    } catch (Exception e) {
        displayMessage("Failed to write tag");

    }

    return false;
}

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

@Override
public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
    try {//from www. jav  a2s. co  m
        NdefMessage msg = new NdefMessage(
                new NdefRecord[] { createMime("application/vnd.net.networksaremadeofstring.rhybudd.push",
                        FilterKey.getText().toString().getBytes())
                //,NdefRecord.createApplicationRecord("com.example.android.beam")
                });
        return msg;
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("PushSettingsFragment", "createNdefMessage", e);
        return null;
    }
}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

private NdefMessage createNdefMessage(String content) {
    NdefRecord ndefRecord = createTextRecord(content);
    NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { ndefRecord });

    return ndefMessage;
}

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

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    setHasOptionsMenu(true);/*from  w w w  . jav a2s  .  c  o  m*/
    getSharedPreferences(USER_COLOR_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    getSharedPreferences(USER_NICKNAME_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    mLocale = getResources().getConfiguration().locale;
    mCardBackgroundColor = ThemeUtils.getCardBackgroundColor(activity);
    mProfileImageLoader = getApplication().getMediaLoaderWrapper();
    final Bundle args = getArguments();
    long accountId = -1, userId = -1;
    String screenName = null;
    if (savedInstanceState != null) {
        args.putAll(savedInstanceState);
    } else {
        accountId = args.getLong(EXTRA_ACCOUNT_ID, -1);
        userId = args.getLong(EXTRA_USER_ID, -1);
        screenName = args.getString(EXTRA_SCREEN_NAME);
    }

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUser user = getUser();
            if (user == null)
                return null;
            return new NdefMessage(new NdefRecord[] {
                    NdefRecord.createUri(LinkCreator.getTwitterUserLink(user.screen_name)), });
        }
    });

    activity.setEnterSharedElementCallback(new SharedElementCallback() {

        @Override
        public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            final int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionSource(bounds);
            }
            super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionDestination(bounds);
            }
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

    });

    ViewCompat.setTransitionName(mProfileImageView, TRANSITION_NAME_PROFILE_IMAGE);
    ViewCompat.setTransitionName(mProfileTypeView, TRANSITION_NAME_PROFILE_TYPE);
    //        ViewCompat.setTransitionName(mCardView, TRANSITION_NAME_CARD);

    mHeaderDrawerLayout.setDrawerCallback(this);

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

    mViewPager.setOffscreenPageLimit(3);
    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);

    mFollowButton.setOnClickListener(this);
    mProfileImageView.setOnClickListener(this);
    mProfileBannerView.setOnClickListener(this);
    mListedContainer.setOnClickListener(this);
    mFollowersContainer.setOnClickListener(this);
    mFriendsContainer.setOnClickListener(this);
    mRetryButton.setOnClickListener(this);
    mProfileBannerView.setOnSizeChangedListener(this);
    mProfileBannerSpace.setOnTouchListener(this);

    mProfileNameBackground.setBackgroundColor(mCardBackgroundColor);
    mProfileDetailsContainer.setBackgroundColor(mCardBackgroundColor);
    mPagerIndicator.setBackgroundColor(mCardBackgroundColor);
    mUuckyFooter.setBackgroundColor(mCardBackgroundColor);

    getUserInfo(accountId, userId, screenName, false);

    final float actionBarElevation = ThemeUtils.getSupportActionBarElevation(activity);
    ViewCompat.setElevation(mPagerIndicator, actionBarElevation);

    setupBaseActionBar();

    setupUserPages();
}

From source file:org.mariotaku.twidere.fragment.support.UserFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    setHasOptionsMenu(true);/* w  w  w  .  j  ava 2 s  .c  om*/
    getSharedPreferences(USER_COLOR_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    getSharedPreferences(USER_NICKNAME_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    mUserColorNameManager = UserColorNameManager.getInstance(activity);
    mPreferences = SharedPreferencesWrapper.getInstance(activity, SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE,
            SharedPreferenceConstants.class);
    mNameFirst = mPreferences.getBoolean(KEY_NAME_FIRST);
    mLocale = getResources().getConfiguration().locale;
    mCardBackgroundColor = ThemeUtils.getCardBackgroundColor(activity,
            ThemeUtils.getThemeBackgroundOption(activity), ThemeUtils.getUserThemeBackgroundAlpha(activity));
    mActionBarShadowColor = 0xA0000000;
    final TwidereApplication app = TwidereApplication.getInstance(activity);
    mProfileImageLoader = app.getMediaLoaderWrapper();
    final Bundle args = getArguments();
    long accountId = -1, userId = -1;
    String screenName = null;
    if (savedInstanceState != null) {
        args.putAll(savedInstanceState);
    } else {
        accountId = args.getLong(EXTRA_ACCOUNT_ID, -1);
        userId = args.getLong(EXTRA_USER_ID, -1);
        screenName = args.getString(EXTRA_SCREEN_NAME);
    }

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUser user = getUser();
            if (user == null)
                return null;
            return new NdefMessage(new NdefRecord[] {
                    NdefRecord.createUri(LinkCreator.getTwitterUserLink(user.screen_name)), });
        }
    });

    activity.setEnterSharedElementCallback(new SharedElementCallback() {

        @Override
        public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            final int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionSource(bounds);
            }
            super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionDestination(bounds);
            }
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

    });

    ViewCompat.setTransitionName(mProfileImageView, TRANSITION_NAME_PROFILE_IMAGE);
    ViewCompat.setTransitionName(mProfileTypeView, TRANSITION_NAME_PROFILE_TYPE);
    //        ViewCompat.setTransitionName(mCardView, TRANSITION_NAME_CARD);

    mHeaderDrawerLayout.setDrawerCallback(this);

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

    mViewPager.setOffscreenPageLimit(3);
    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);
    mPagerIndicator.setOnPageChangeListener(this);

    mFollowButton.setOnClickListener(this);
    mProfileImageView.setOnClickListener(this);
    mProfileBannerView.setOnClickListener(this);
    mListedContainer.setOnClickListener(this);
    mFollowersContainer.setOnClickListener(this);
    mFriendsContainer.setOnClickListener(this);
    mHeaderErrorIcon.setOnClickListener(this);
    mProfileBannerView.setOnSizeChangedListener(this);
    mProfileBannerSpace.setOnTouchListener(this);

    mProfileNameBackground.setBackgroundColor(mCardBackgroundColor);
    mProfileDetailsContainer.setBackgroundColor(mCardBackgroundColor);
    mPagerIndicator.setBackgroundColor(mCardBackgroundColor);
    mUuckyFooter.setBackgroundColor(mCardBackgroundColor);

    final float actionBarElevation = ThemeUtils.getSupportActionBarElevation(activity);
    ViewCompat.setElevation(mPagerIndicator, actionBarElevation);

    if (activity instanceof IThemedActivity) {
        ViewSupport.setBackground(mPagerOverlay, ThemeUtils.getNormalWindowContentOverlay(activity,
                ((IThemedActivity) activity).getCurrentThemeResourceId()));
        ViewSupport.setBackground(mErrorOverlay, ThemeUtils.getNormalWindowContentOverlay(activity,
                ((IThemedActivity) activity).getCurrentThemeResourceId()));
    }

    setupBaseActionBar();
    setupUserPages();
    if (activity instanceof IThemedActivity) {
        setUiColor(((IThemedActivity) activity).getCurrentThemeColor());
    }

    getUserInfo(accountId, userId, screenName, false);
}

From source file:org.mariotaku.twidere.fragment.UserFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    mUserColorNameManager.registerColorChangedListener(this);
    mUserColorNameManager.registerNicknameChangedListener(this);
    mNameFirst = mPreferences.getBoolean(KEY_NAME_FIRST);
    mLocale = getResources().getConfiguration().locale;
    mCardBackgroundColor = ThemeUtils.getCardBackgroundColor(activity,
            ThemeUtils.getThemeBackgroundOption(activity), ThemeUtils.getUserThemeBackgroundAlpha(activity));
    mActionBarShadowColor = 0xA0000000;/*from   w  ww.j  av a2 s .  c  o  m*/
    final Bundle args = getArguments();
    UserKey accountId = null;
    UserKey userId = null;
    String screenName = null;
    if (savedInstanceState != null) {
        args.putAll(savedInstanceState);
    } else {
        accountId = args.getParcelable(EXTRA_ACCOUNT_KEY);
        userId = args.getParcelable(EXTRA_USER_KEY);
        screenName = args.getString(EXTRA_SCREEN_NAME);
    }

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUser user = getUser();
            if (user == null)
                return null;
            return new NdefMessage(
                    new NdefRecord[] { NdefRecord.createUri(LinkCreator.getUserWebLink(user)), });
        }
    });

    mTintedStatusFrameLayout.setWindowInsetsListener(new TintedStatusFrameLayout.WindowInsetsListener() {
        @Override
        public void onApplyWindowInsets(int left, int top, int right, int bottom) {
            mProfileContentContainer.setPadding(0, top, 0, 0);
            mProfileBannerSpace.setStatusBarHeight(top);

            if (mProfileBannerSpace.getToolbarHeight() == 0) {
                int toolbarHeight = mToolbar.getMeasuredHeight();
                if (toolbarHeight == 0) {
                    toolbarHeight = ThemeUtils.getActionBarHeight(getContext());
                }
                mProfileBannerSpace.setToolbarHeight(toolbarHeight);
            }
        }

    });
    mProfileContentContainer.setOnSizeChangedListener(new OnSizeChangedListener() {
        @Override
        public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {
            final int toolbarHeight = mToolbar.getMeasuredHeight();
            mHeaderDrawerLayout.setPadding(0, toolbarHeight, 0, 0);
            mProfileBannerSpace.setToolbarHeight(toolbarHeight);
        }
    });

    mHeaderDrawerLayout.setDrawerCallback(this);

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

    mViewPager.setOffscreenPageLimit(3);
    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);
    mPagerIndicator.setOnPageChangeListener(this);

    mFollowButton.setOnClickListener(this);
    mProfileImageView.setOnClickListener(this);
    mProfileBannerView.setOnClickListener(this);
    mListedContainer.setOnClickListener(this);
    mGroupsContainer.setOnClickListener(this);
    mFollowersContainer.setOnClickListener(this);
    mFriendsContainer.setOnClickListener(this);
    mHeaderErrorIcon.setOnClickListener(this);
    mProfileBirthdayBannerView.setOnClickListener(this);
    mProfileBannerView.setOnSizeChangedListener(this);
    mProfileBannerSpace.setOnTouchListener(this);

    mProfileNameBackground.setBackgroundColor(mCardBackgroundColor);
    mProfileDetailsContainer.setBackgroundColor(mCardBackgroundColor);
    mPagerIndicator.setBackgroundColor(mCardBackgroundColor);

    final float actionBarElevation = ThemeUtils.getSupportActionBarElevation(activity);
    ViewCompat.setElevation(mPagerIndicator, actionBarElevation);

    setupBaseActionBar();
    setupUserPages();

    getUserInfo(accountId, userId, screenName, false);
}