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.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 ww.j  a  v a  2  s . c o  m*/
    NdefMessage message = new NdefMessage(records);
    return message;
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Get the NDEF for a product code/*from  w w  w  . j a  v  a2s .c o m*/
 * 
 * @param productCode
 * @return
 */
private NdefMessage getNDEF(String productCode) {
    NdefMessage msg = null;
    try {
        NdefRecord uriRecord;
        uriRecord = NdefRecord.createUri(getString(R.string.nfc_url, URLEncoder.encode(productCode, "UTF-8")));
        NdefRecord appRecord = NdefRecord.createApplicationRecord(getPackageName());
        msg = new NdefMessage(new NdefRecord[] { uriRecord, appRecord });
    } catch (UnsupportedEncodingException e) {
        LoggingUtils.e(LOG_TAG, "Error trying to encode product code to UTF-8. " + e.getLocalizedMessage(),
                Hybris.getAppContext());
    }

    return msg;
}

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

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    final TwidereApplication application = TwidereApplication.getInstance(activity);
    mTwitterWrapper = application.getTwitterWrapper();
    mProfileImageLoader = application.getMediaLoaderWrapper();
    mUserColorNameManager = application.getUserColorNameManager();
    mPreferences = SharedPreferencesWrapper.getInstance(activity, SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE,
            SharedPreferenceConstants.class);

    setHasOptionsMenu(true);/*w  w  w .  j  av a  2s  .  c om*/

    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)), });
        }
    });

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

    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);
    getUserListInfo(false);
    setupUserPages();
}

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);/*w ww. ja  v  a  2 s .c  om*/
    return new NdefMessage(new NdefRecord[] { textRecord });
}

From source file:org.ulteo.ovd.AndRdpActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void startSession(int screen_width, int screen_height) {
    if (isConnected())
        return;//from  w w  w .ja v  a  2 s.  c  o m

    Bundle bundle = getIntent().getExtras();

    if (bundle == null) {
        finish();
        return;
    }

    Point res;
    // check if user has chosen a specific resolution
    if (!Settings.getResolutionAuto(this)) {
        res = Settings.getResolution(this);
    } else {
        res = new Point(screen_width, screen_height);
        // Prefer wide screen
        if (!Settings.getResolutionWide(this) && res.y > res.x) {
            int w = res.x;
            res.x = res.y;
            res.y = w;
        }
    }
    Log.i(Config.TAG, "Resolution: " + res.x + "x" + res.y);

    String gateway_token = null;
    Boolean gateway_mode = bundle.getBoolean(PARAM_GATEWAYMODE);
    if (gateway_mode)
        gateway_token = bundle.getString(PARAM_TOKEN);

    int drives = Properties.REDIRECT_DRIVES_FULL;
    Properties prop = smHandler.getResponseProperties();
    if (prop != null)
        drives = prop.isDrives();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN
            && bundle.getString(PARAM_SM_URI) != null) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null) {
            NdefRecord rtdUriRecord = NdefRecord.createUri(bundle.getString(PARAM_SM_URI));
            NdefMessage ndefMessage = new NdefMessage(rtdUriRecord);
            nfcAdapter.setNdefPushMessage(ndefMessage, this);
        }
    }

    rdp = new Rdp(res, bundle.getString(PARAM_LOGIN), bundle.getString(PARAM_PASSWD),
            bundle.getString(PARAM_IP), bundle.getInt(PARAM_PORT, SessionManagerCommunication.DEFAULT_RDP_PORT),
            gateway_mode, gateway_token, drives,
            bundle.getString(PARAM_RDPSHELL) == null ? "" : bundle.getString(PARAM_RDPSHELL),
            Settings.getBulkCompression(AndRdpActivity.this), Settings.getConnexionType(AndRdpActivity.this));

    Resources resources = getResources();
    Intent notificationIntent = new Intent(this, AndRdpActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon_bw)
            .setContentTitle(resources.getText(R.string.app_name)).setOngoing(true)
            .setContentText(resources.getText(R.string.desktop_session_active)).setContentIntent(pendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            public void onPrimaryClipChanged() {
                ClipboardManager clipboard = (ClipboardManager) AndRdpActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = clipboard.getPrimaryClip();
                String text = clip.getItemAt(0).coerceToText(AndRdpActivity.this).toString();
                if (Config.DEBUG)
                    Log.d(Config.TAG, "Android clipboard : " + text);

                if (isLoggedIn())
                    rdp.sendClipboard(text);
            }
        };
        clipboard.addPrimaryClipChangedListener(clipChangedListener);
    }
}

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

private void write(Tag tag) throws IOException, FormatException {
    //generate new random key and write them on the tag
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(output);/*  w w  w. j a  va 2  s.c o  m*/
    NdefRecord[] records = { createRecord(output.toString()) };
    NdefMessage message = new NdefMessage(records);
    Ndef ndef = Ndef.get(tag);
    ndef.connect();
    ndef.writeNdefMessage(message);
    ndef.close();
}

From source file:org.bohrmeista.chan.ui.activity.BaseActivity.java

/**
 * Set the url that Android Beam and the share action will send.
 *
 * @param url/*from   www . ja  v  a 2 s .  com*/
 */
public void setShareUrl(String url) {
    shareUrl = url;

    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);

    if (adapter != null) {
        NdefRecord record = null;
        try {
            record = NdefRecord.createUri(url);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }

        NdefMessage message = new NdefMessage(new NdefRecord[] { record });
        try {
            adapter.setNdefPushMessage(message, this);
        } catch (Exception e) {
        }
    }

    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.putExtra(android.content.Intent.EXTRA_TEXT, url);
    share.setType("text/plain");

    if (shareActionProvider != null) {
        shareActionProvider.setShareIntent(share);
    } else {
        pendingShareActionProviderIntent = share;
    }
}

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

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();//from ww w .  jav  a 2s  . c  o  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.mariotaku.twidere.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/*from w w  w  .  j  ava  2 s  .  com*/
        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);

    mRecyclerViewNavigationHelper = new RecyclerViewNavigationHelper(mRecyclerView, mLayoutManager,
            mStatusAdapter, null);

    setState(STATE_LOADING);

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

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;/*  ww w  .  j  av a 2  s . com*/
        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;
    }
}