Example usage for android.nfc NdefRecord createUri

List of usage examples for android.nfc NdefRecord createUri

Introduction

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

Prototype

public static NdefRecord createUri(String uriString) 

Source Link

Document

Create a new NDEF Record containing a URI.

Use this method to encode a URI (or URL) into an NDEF Record.

Uses the well known URI type representation: #TNF_WELL_KNOWN and #RTD_URI .

Usage

From source file:Main.java

@TargetApi(14)
public static boolean setPushMessage(Activity activity, Uri toShare) {
    NfcAdapter adapter = getAdapter(activity);
    if (adapter != null) {
        adapter.setNdefPushMessage(new NdefMessage(new NdefRecord[] { NdefRecord.createUri(toShare), }),
                activity);//  www.ja  v  a2 s  .  co  m
        return true;
    }
    return false;
}

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 {//from ww w.  ja v a 2 s  .co  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:org.floens.chan.ui.controller.ThreadController.java

@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    Loadable loadable = getLoadable();//from  w  w  w .  j  a va2s  .c  om
    String url = null;
    NdefMessage message = null;

    if (loadable != null) {
        if (loadable.isThreadMode()) {
            url = ChanUrls.getThreadUrlDesktop(loadable.board, loadable.no);
        } else if (loadable.isCatalogMode()) {
            url = ChanUrls.getCatalogUrlDesktop(loadable.board);
        }
    }

    if (url != null) {
        try {
            Logger.d(TAG, "Pushing url " + url + " to android beam");
            NdefRecord record = NdefRecord.createUri(url);
            message = new NdefMessage(new NdefRecord[] { record });
        } catch (IllegalArgumentException e) {
            Logger.e(TAG, "NdefMessage create error", e);
        }
    }

    return message;
}

From source file:org.openhab.habdroid.ui.OpenHABWriteTagActivity.java

private void writeTag(Tag tag, String uri) {
    Log.d(TAG, "Creating tag object for URI " + uri);
    TextView writeTagMessage = findViewById(R.id.write_tag_message);

    NdefRecord[] ndefRecords = new NdefRecord[] { NdefRecord.createUri(uri) };
    NdefMessage message = new NdefMessage(ndefRecords);
    NdefFormatable ndefFormatable = NdefFormatable.get(tag);

    if (ndefFormatable != null) {
        Log.d(TAG, "Tag is uninitialized, formating");
        try {//from  w  w w .  j  ava2s.co m
            ndefFormatable.connect();
            ndefFormatable.format(message);
            ndefFormatable.close();
            writeTagMessage.setText(R.string.info_write_tag_finished);
            autoCloseActivity();
        } catch (IOException | FormatException e) {
            Log.e(TAG, "Writing to unformatted tag failed: " + e);
            writeTagMessage.setText(R.string.info_write_failed);
        }
    } else {
        Log.d(TAG, "Tag is initialized, writing");
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            try {
                Log.d(TAG, "Connecting");
                ndef.connect();
                Log.d(TAG, "Writing");
                if (ndef.isWritable()) {
                    ndef.writeNdefMessage(message);
                }
                Log.d(TAG, "Closing");
                ndef.close();
                writeTagMessage.setText(R.string.info_write_tag_finished);
                autoCloseActivity();
            } catch (IOException | FormatException e) {
                Log.e(TAG, "Writing to formatted tag failed: " + e);
                writeTagMessage.setText(R.string.info_write_failed);
            }
        } else {
            Log.e(TAG, "Ndef == null");
            writeTagMessage.setText(R.string.info_write_failed);
        }
    }
}

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

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    setHasOptionsMenu(true);/*  w  w w  .j a  v a 2  s  .c o m*/

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

    getUserListInfo(false);
}

From source file:com.brq.wallet.activity.receive.ReceiveCoinsActivity.java

@TargetApi(16)
protected void shareByNfc() {
    if (Build.VERSION.SDK_INT < 16) {
        // the function isNdefPushEnabled is only available for SdkVersion >= 16
        // We would be theoretically able to push the message over Ndef, but it is not
        // possible to check if Ndef/NFC is available or not - so dont try it at all, if
        // SdkVersion is too low
        return;//from  w  w w.j av  a2s.co  m
    }

    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc != null && nfc.isNdefPushEnabled()) {
        nfc.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent event) {
                NdefRecord uriRecord = NdefRecord.createUri(getPaymentUri());
                return new NdefMessage(new NdefRecord[] { uriRecord });
            }
        }, this);
        ivNfc.setVisibility(View.VISIBLE);
        ivNfc.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.showSimpleMessageDialog(ReceiveCoinsActivity.this,
                        getString(R.string.nfc_payment_request_hint));
            }
        });
    } else {
        ivNfc.setVisibility(View.GONE);
    }
}

From source file:biz.wiz.android.wallet.ui.WalletAddressFragment.java

@Override
public NdefMessage createNdefMessage(final NfcEvent event) {
    final String uri = currentAddressUriRef.get();
    if (uri != null)
        return new NdefMessage(new NdefRecord[] { NdefRecord.createUri(uri) });
    else/*from   w ww. jav  a2s .  co m*/
        return null;
}

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

/**
 * Get the NDEF for a product code//from www  . ja  v a 2s.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);//www  .  ja va 2  s.  c o  m

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